1

I want to write tests for my main file,calc.py, with unittest in module file, MyTests.py.

Here is my main python file, calc.py:

import myTests

def first(x):
    return x**2

def second(x):
    return x**3

def main():
    one = first(5)
    two = second(5)

if __name__ == "__main__":
    main()
    try:
        myTests.unittest.main()
    except SystemExit:
        pass

And here is my MyTests.py file:

import unittest
import calc

class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.testInput = 10

    def test_first(self):
        output = calc.first(self.testInput)
        correct = 100
        assert(output == correct)

    def test_second(self):
        output = calc.second(self.testInput)
        correct = 1000
        assert(output == correct)

When i run my calc.py, i get the following output:

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

Why does unittest prints me that "Ran 0 test"?
And what is the right way to write unittest in module?

1 Answer 1

3

unittests.main() looks for TestCase instances in the current module. Your module has no such testcases; it only has a myTests global.

Best practice is to run the tests themselves. Add the __main__ section there to the myTests.py file:

import unittest
import calc

class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        self.testInput = 10

    def test_first(self):
        output = calc.first(self.testInput)
        correct = 100
        assert(output == correct)

    def test_second(self):
        output = calc.second(self.testInput)
        correct = 1000
        assert(output == correct)

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

and run python myTests.py instead.

Alternatively, pass in the imported myTests module into unittest.main(). You may want to move the import myTests line down into __main__, because you have a circular import too. That is fine in your case, myTests doesn't use any globals from calc outside of the test cases, but it is better to be explicit about this.

if __name__ == "__main__":
    main()
    try:
        import myTests
        myTests.unittest.main(myTests)
    except SystemExit:
        pass
Sign up to request clarification or add additional context in comments.

Comments

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.