Ame*_*mey 24 python oop unit-testing nose python-unittest
Python unittest使用nosetests来试验Python Class和Module fixture,在我的测试中进行最小化设置.
我面临的问题是,我不确定如何使用我的测试中setupUpModule的setUpClass函数和函数中定义的任何变量(例如: - test_1).
这是我用来尝试的:
import unittest
def setUpModule():
a = "Setup Module variable"
print "Setup Module"
def tearDownModule():
print "Closing Module"
class TrialTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
print a #<======
b = "Setup Class variable"
@classmethod
def tearDownClass(cls):
print "Closing Setup Class"
def test_1(self):
print "in test 1"
print a #<======
print b #<======
def test_2(self):
print "in test 2"
def test_3(self):
print "in test 3"
def test_4(self):
print "in test 4"
def test_5(self):
print "in test 5"
if __name__ == "__main__":
unittest.main()
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
Setup Module
ERROR
Closing Module
======================================================================
ERROR: test suite for <class 'one_setup.TrialTest'>
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/nose/suite.py", line 208, in run
self.setUp()
File "/Library/Python/2.7/site-packages/nose/suite.py", line 291, in setUp
self.setupContext(ancestor)
File "/Library/Python/2.7/site-packages/nose/suite.py", line 314, in setupContext
try_run(context, names)
File "/Library/Python/2.7/site-packages/nose/util.py", line 469, in try_run
return func()
File "/Users/patila14/Desktop/experimental short scripts/one_setup.py", line 13, in setUpClass
print a
NameError: global name 'a' is not defined
----------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
当然,如果这样做gloabl a,并global b,它会工作.有没有更好的办法?
nof*_*tor 26
对于str变量a,唯一的解决方案是global a.如果您查看Python 2 unittest源代码,setupModule()似乎没有做任何神奇的事情,因此所有常用的命名空间规则都适用.
如果a是一个可变变量,如列表,您可以在全局范围内定义它,然后在setupModule中附加到它.
变量b更容易使用,因为它是在类中定义的.试试这个:
@classmethod
def setUpClass(cls):
cls.b = "Setup Class variable"
def test_1(self):
print self.b
Run Code Online (Sandbox Code Playgroud)