Python unittest - 在测试中使用模块和类级别设置函数中定义的变量

标签 python unit-testing oop nose python-unittest

我正在使用 nosetests 进行 Python 单元测试来试验 Python class and module fixtures , 在我的测试中进行最少的设置。

问题是我不确定如何在我的测试中使用 setupUpModulesetUpClass 函数中定义的任何变量(例如: 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()

我得到的错误是:

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

----------------------------------------------------------------------

当然,如果我执行 gloabl aglobal b,它会起作用。有没有更好的办法?

最佳答案

对于字符串变量a,唯一的解决方案是global a。如果您查看 Python 2Python 3源代码,setupModule() 似乎没有做任何神奇的事情,所以所有常用的命名空间规则都适用。

如果 a 是一个可变变量,如列表,您可以在全局范围内定义它,然后在 setupModule 中附加到它。

变量b更容易使用,因为它是在一个类中定义的。试试这个:

@classmethod
def setUpClass(cls):
    cls.b = "Setup Class variable"

def test_1(self):
    print self.b

关于Python unittest - 在测试中使用模块和类级别设置函数中定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19144235/

相关文章:

javascript - 如何在不需要运行浏览器或服务器的情况下在 Maven 中运行 javascript 单元测试?

python - 在 Python 中,测试函数的标准输出

Swift不支持多重继承,如何实现?

c++ - 指向类和函数的指针 - 问题

python - 从pymol中的笛卡尔坐标绘制彩色球体

javascript - Django、Nodejs 还是 Ruby on Rails?

python - 计算 Pandas DataFrame 的百分比变化

c# - 带有自动生成的 Web 服务客户端的 DI

c# - LINQ to SQL - 使用部分类和方法扩展数据上下文时出现编译错误

python - Django 模型没有将日期字段转换为 datetime.date?