18

I want to have the files of my application under the folder /Files, whereas the test units in /UnitTests, so that I have clearly separated app and test.

To be able to use the same module routes as the mainApp.py, I have created a testController.py in the root folder.

mainApp.py
testController.py
Files
  |__init__.py
  |Controllers
     | blabla.py
  | ...
UnitTests
  |__init__.py
  |test_something.py

So if in test_something.py I want to test one function that is in /Files/Controllers/blabla.py, I try the following:

import unittest
import Files.Controllers.blabla as blabla


class TestMyUnit(unittest.TestCase):

    def test_stupid(self):
        self.assertTrue(blabla.some_function())


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


And then from the file testController.py, I execute the following code:

import TestUnits.test_something as my_test
my_test.unittest.main()

Which outputs no failures, but no tests executed

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

OK
[Finished in 0.3s]


I have tried with a test that has no dependences, and if executed as "main" works, but when called from outside, outputs the same:

import unittest


def tested_unit():
    return True


class TestMyUnit(unittest.TestCase):

    def test_stupid(self):
        self.assertTrue(tested_unit())


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

Question: how do I get this to work?

3 Answers 3

26

The method unittest.main() looks at all the unittest.TestCase classes present in the context. So you just need to import your test classes in your testController.py file and call unittest.main() in the context of this file.

So your file testController.py should simply look like this :

import unittest    
from UnitTests.test_something import *
unittest.main()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but it does not work. The result is the same: it executes no test.
Ok my bad. You have to import all test cases from test_something file. Try with from UnitTests.test_something import TestMyUnit (or *) and it should work!
11

In test_something.py, do this:

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestMyUnit, 'test'))
    return suite

In testController.py, do this:

from TestUnits import test_something

def suite():
    suite = unittest.TestSuite()
    suite.addTest(test_something.suite())
    return suite

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

Comments

-1

There is a workaround of using subprocess.call() to run tests, like:

import subprocess

args = ["python", "test_something.py"]
subprocess.call(args)

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.