0

I have a simple file program (removed code from functions since its irrelevant for the problem):

import random
import sys


def poziom(level):
    *does something and returns something*

def gra(chance):
    *does something and returns something*


def save(name):
    *does something and returns something*


while True:
    *does something in loop, executing other functions above*

I'm trying to run a simple unit test against one of its functions:

import unittest

from my_game import save
from my_game import gra
from my_game import poziom




class TestSum(unittest.TestCase):
    def test_list_int(self):
        """
        Test that it can sum a list of integers
        """
        check = "Test string"
        result = poziom(check)
        self.assertEqual(result, 0)

if __name__ == '__main__':
    unittest.main()

However, this test instead of running a poziom() function, runs through entire file, also executing the code behind the While True statement. Do I do something wrong? Is it possible in such case to write a test that checks ONLY one function and value returned by it?

1
  • If you put the while True: in an if __name__ == "__main__": statement, does that fix it? Otherwise, just importing that file will execute the contents of that loop. Commented Jun 24, 2021 at 16:46

1 Answer 1

4

However, this test instead of running a poziom() function, runs through entire file, also executing the code behind the While True statement. Do I do something wrong?

This is how import works. It executes the code in the file that you import. To solve the problem put the while loop in a if __name__ == '__main__': just like you do in your test file.

Sign up to request clarification or add additional context in comments.

2 Comments

Does not work, unfortunately. I did like you said: if name == 'main': while True: unittest.main() But executing tests still throws me to the while true loop inside the main file.
@MikaelDiak Which file did you edit? unittest.main() is in the test file, but while True is in the file with the functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.