简体   繁体   English

Python unittest 模块中 unittest.main() 的含义

[英]Meaning of unittest.main() in Python unittest module

I was trying to learn unit testing in Python, specifically the unittest module.我试图在 Python 中学习单元测试,特别是unittest模块。

Consider the following lines:考虑以下几行:

import unittest

class abc(unittest.TestCase):
    def xyz():
      ...

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

I could see all my test cases running because of the call to unittest.main() .由于对unittest.main()的调用,我可以看到我所有的测试用例都在运行。

I was just curious to know how this call is making all the test cases run.我只是想知道这个调用是如何让所有测试用例运行的。

I know since I'm inheriting from unittest.TestCase for every test class, it is doing all the magic.我知道自从我为每个测试类继承unittest.TestCase以来,它正在发挥所有作用。 Any insights?任何见解?

main associated with unittest is actually an instance of TestProgram which, when instantiated, runs all your tests.unittest相关的main实际上是 TestProgram 的一个实例,它在实例化时运行所有测试。

Below is the relevant code copied from the unittest source at http://pythonhosted.org/gchecky/unittest-pysrc.html :以下是从http://pythonhosted.org/gchecky/unittest-pysrc.htmlunittest源复制的相关代码:

735  class TestProgram:
752 -    def __init__(self, module='__main__', defaultTest=None,
753                   argv=None, testRunner=None, testLoader=defaultTestLoader):
754          if type(module) == type(''):
755              self.module = __import__(module)
756              for part in module.split('.')[1:]:
757                  self.module = getattr(self.module, part)
758          else:
759              self.module = module
760          if argv is None:
761              argv = sys.argv
762          self.verbosity = 1
763          self.defaultTest = defaultTest
764          self.testRunner = testRunner
765          self.testLoader = testLoader
766          self.progName = os.path.basename(argv[0])
767          self.parseArgs(argv)
768          self.runTests()
769
770 -    def usageExit(self, msg=None):
771          if msg: print msg
772          print self.USAGE % self.__dict__
773          sys.exit(2)
774
775 -    def parseArgs(self, argv):
776          import getopt
777          try:
778              options, args = getopt.getopt(argv[1:], 'hHvq',
779                                            ['help','verbose','quiet'])
780              for opt, value in options:
781                  if opt in ('-h','-H','--help'):
782                      self.usageExit()
783                  if opt in ('-q','--quiet'):
784                      self.verbosity = 0
785                  if opt in ('-v','--verbose'):
786                      self.verbosity = 2
787              if len(args) == 0 and self.defaultTest is None:
788                  self.test = self.testLoader.loadTestsFromModule(self.module)
789                  return
790              if len(args) > 0:
791                  self.testNames = args
792              else:
793                  self.testNames = (self.defaultTest,)
794              self.createTests()
795          except getopt.error, msg:
796              self.usageExit(msg)
797
798 -    def createTests(self):
799          self.test = self.testLoader.loadTestsFromNames(self.testNames,
800                                                         self.module)
801
802 -    def runTests(self):
803          if self.testRunner is None:
804              self.testRunner = TextTestRunner(verbosity=self.verbosity)
805          result = self.testRunner.run(self.test)
806          sys.exit(not result.wasSuccessful())
807
808  main = TestProgram

So when you execute unittest.main() , an object of TestProgram gets created which calls self.runTests() at line 768. The constructor also takes your current file as the default module containing the tests ( module='__main__' ).因此,当您执行unittest.main() ,会创建一个TestProgram对象,它在第 768 行调用self.runTests() 。构造函数还将您当前的文件作为包含测试的默认模块( module='__main__' )。

When runTests() is called, it in turn calls self.testrunner.run() .runTests()被调用时,它依次调用self.testrunner.run() When you refer to the "run" method of TextTestRunner class, you will find that it actually runs and reports all your test results.当你参考TextTestRunner类的“run”方法时,你会发现它实际上运行并报告了你所有的测试结果。

Test discovery is done by TestProgram.parseArgs at line 775 when you call unittest.main().当您调用 unittest.main() 时,测试发现由TestProgram.parseArgs在第 775 行完成。 self.createTests at line 798 is actually responsible for discovering all your test cases and creating a test suite.第 798 行的self.createTests实际上负责发现所有测试用例并创建测试套件。 This is all the magic.这就是所有的魔法。

Internally, unittest.main() is using a few tricks to figure out the name of the module (source file) that contains the call to main() .在内部, unittest.main()使用一些技巧来找出包含对main()调用的模块(源文件)的名称。

It then imports this modules, examines it, gets a list of all classes and functions which could be tests (according the configuration) and then creates a test case for each of them.然后它导入这个模块,检查它,获取所有可以测试的类和函数的列表(根据配置),然后为每个类和函数创建一个测试用例。

When the list is ready, it executes each test in turn.当列表准备好后,它会依次执行每个测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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