简体   繁体   中英

Can I call “python -m unittest test_code” by “runpy.run_module”?

I am learning unittest of python.

I learned that I can run a test, test_code, by

python -m unittest test_code

from command line.

Now I would like to run unittest in python script. I learned "runpy.run_module()" corresponds with "python -m". However I could not understand how to give arguments to unittest in the way of "runpy.run_module()". That is,

runpy.run_module(unittest)  # where should I put 'test_code'?

Can I run unittest with test_code with runpy.run_module() in the python script?

Thank you very much.

Here are some ways to do it:

import unittest

import tests # where my unit tests are at
import tests_copy # where my unit tests are at

# make a collection of TestCases
suit = unittest.TestSuite()

# add all testcases in tests module
suit.addTest(unittest.defaultTestLoader.loadTestsFromName('tests'))

# add testcase tester1 from module  tests_copy
suit.addTest(unittest.defaultTestLoader.loadTestsFromName('tests_copy.tester1'))

# add all testcases in tests module
suit.addTest(unittest.defaultTestLoader.loadTestsFromModule(tests))

# add testcase tester1 from module tests_copy
suit.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(tests.tester1))


# run the tests
runner = unittest.TextTestRunner()
runner.run(suit)

Read the docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM