Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run unittests from a different file

I have a file TestProtocol.py that has unittests. I can run that script and get test results for my 30 tests as expected. Now I want to run those tests from another file tester.py that is located in the same directory. Inside tester.py I tried import TestProtocol, but it runs 0 tests.

Then I found the documentation which says I should do something like this:

suite = unittest.TestLoader().discover(".", pattern = "*")
unittest.run(suite)

This should go through all files in the current directory . that match the pattern *, so all tests in all files. Unfortunately it again runs 0 tests.

There is a related QA that suggests to do

import TestProtocol
suite = unittest.findTestCases(TestProtocol)
unittest.run(suite)

but that also does not find any tests.

How do I import and run my tests?

like image 218
nwp Avatar asked Jul 22 '15 09:07

nwp


1 Answers

You can try with following

# preferred module name would be test_protol as CamelCase convention are used for class name
import TestProtocol

# try to load all testcases from given module, hope your testcases are extending from unittest.TestCase
suite = unittest.TestLoader().loadTestsFromModule(TestProtocol)
# run all tests with verbosity 
unittest.TextTestRunner(verbosity=2).run(suite)

Here is a full example

file 1: test_me.py

# file 1: test_me.py 
import unittest

class TestMe(unittest.TestCase):
    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

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

file 2: test_other.py, put this under same directory

# file 2: test_other.py, put this under same directory
import unittest
import test_me

suite = unittest.TestLoader().loadTestsFromModule(test_me)
unittest.TextTestRunner(verbosity=2).run(suite)

run each file, it will show the same result

# python test_me.py - Ran 1 test in 0.000s
# python test_other.py - Ran 1 test in 0.000s
like image 155
Shaikhul Avatar answered Oct 02 '22 23:10

Shaikhul