【问题标题】:Why is it complaining about variable not being defined [duplicate]为什么它抱怨没有定义变量[重复]
【发布时间】:2018-01-10 14:56:47
【问题描述】:

我是编写 python 测试代码的新手,目前正在涉足 unittest。

为什么会这样抱怨:

class MyTestClass(unittest.TestCase):
    testdata = "somefile.json"
    def testparse(self):
        data = json.loads(open(testdata).read())


Traceback (most recent call last):
  File "test.py", line 14, in test_instantiation
    data = json.loads(open(testdata).read())
NameError: global name 'testdata' is not defined

【问题讨论】:

  • 'testdata' != 'testfile'。也是的,这是一个类属性而不是全局变量。
  • 请接受我的回答...

标签: python python-2.7 python-unittest


【解决方案1】:

因为变量 testdata 被定义为 CLASS VARIABLE,所以它不是任何函数的局部变量。要引用此类变量,请使用类命名空间 (MyTestClass.testdata)。

在这里您可以了解 Python 中的类变量:Static class variables in Python

也许使用实例变量?实例变量应该在某个方法(最好是构造函数)中定义。

如果您想要本地(方法)变量,请在您要使用它的函数中定义它,并且不要使用任何前缀 - 类名或 self。

【讨论】:

    【解决方案2】:

    试试这个:

    class MyTestClass(unittest.TestCase):
        def __init__(self):
            self.testdata = "somefile.json"
        def testparse(self):
            data = json.loads(open(self.testdata).read())
    

    这样 testdate 成为公共财产 如果您想将其保留为私有,请使用@Wax Cage 的解决方案

    【讨论】:

    • unittest.TestCase.__init__ 存在且不应被覆盖,您完全破坏了测试。您将改用setUp() 方法。这里不需要,类属性就可以了,不需要移动到实例属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多