9

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?

Community
  • 1
  • 1
nwp
  • 9,623
  • 5
  • 38
  • 68

1 Answers1

18

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
Shaikhul
  • 642
  • 5
  • 8
  • Unfortunately that too gives me `Ran 0 tests in 0.000s OK`. – nwp Jul 27 '15 at 10:15
  • @nwp I have updated my answer with a working example, hope this would be helpful – Shaikhul Jul 27 '15 at 15:29
  • 2
    It is working now. The reason it did not work for me before was that I had `unittest.main()` (without `if __name__ == '__main__'`) inside `test_me.py` which prevented the tests from being found. – nwp Jul 28 '15 at 09:37
  • @Shaikhul very nice, thank you for sharing. How would you just receive the status code? –  May 03 '18 at 12:30
  • Late to the party. @Eric you'd just change `verbosity=2` to `verbosity=1` (or another level). – Evan Fiddler Mar 09 '23 at 01:15