简体   繁体   English

Python中的单元测试

[英]unittest in Python

Below program: 下面的程序:

import unittest

class my_class(unittest.TestCase):


  def setUp(self):
        print "In Setup"
        self.x=100
        self.y=200

    def test_case1(self):
        print "-------------"
        print "test case1"
        print self.x
        print "-------------"
    def test_case2(self):
        print "-------------"
        print "test case2"
        print self.y
        print "-------------"
    def tearDown(self):
        print "In Tear Down"
        print "      "
        print "      "

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

Gives the output: 给出输出:

>>> ================================ RESTART ================================
>>> 
In Setup
-------------
test case1
100
-------------
In Tear Down

.In Setup
-------------
test case2
200
-------------
In Tear Down
      .
----------------------------------------------------------------------
Ran 2 tests in 0.113s

OK
>>> 
>>> 

Questions: 问题:

  1. what's the meaning of: if __name__ == "__main__": unittest.main() ? 是什么意思: if __name__ == "__main__": unittest.main()

  2. Why do we have double underscores prefixed and postfixed for name and main ? 为什么我们在namemain前面加上双下划线前缀和后缀?

  3. Where will the object for my_class be created? my_class的对象将在哪里创建?

The if __name__ == "__main__": bit allows your code to be imported as a module without invoking the unittest.main() code - that will only be run if this code is invoked as the main entry point of your program (ie if you called it like python program.py if your program was in program.py ). if __name__ == "__main__":位允许您在不调用unittest.main()代码的情况下将代码作为模块导入-仅在将此代码作为程序的主入口点调用时才运行(即,如果如果您的程序位于program.py则您将其称为python program.py

The prefix and postfix of double underscores means: 双下划线的前缀和后缀表示:

__double_leading_and_trailing_underscore__ : "magic" objects or attributes that live in user-controlled namespaces. __double_leading_and_trailing_underscore__ :存在于用户控制的名称空间中的“魔术”对象或属性。 Eg __init__ , __import__ or __file__ . 例如__init____init__ __import____file__ Never invent such names; 请勿发明此类名称; only use them as documented. 仅按记录使用它们。

That comes from the PEP 8 Style Guide - this is a really useful resource to read and internalize. 这来自PEP 8样式指南 -这是阅读和内部化的非常有用的资源。

Finally, your my_class class will be instantiated within the unittest framework as it runs, as it inherits from unittest.TestCase . 最后,您的my_class类将在运行时在unittest框架中实例化,因为它继承自unittest.TestCase

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

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