Python unittesting: run tests in another module

独自空忆成欢 提交于 2019-12-21 03:38:21

问题


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?


回答1:


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')



回答2:


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()



回答3:


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

import subprocess

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


来源:https://stackoverflow.com/questions/15334042/python-unittesting-run-tests-in-another-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!