-1

I'm new to writing python test code and am currently dabbling with unittest.

Why is this complaining:

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
BenH
  • 690
  • 1
  • 11
  • 23

2 Answers2

1

Because variable testdata is defined as CLASS VARIABLE, its not a local variable of any function. To refer to such variable use class namespace (MyTestClass.testdata).

Here you can learn about class variables in Python: Static class variables in Python

Maybe use instance variable? Instance variables should be defined within some method (ideally constructor).

If you want local (method) variable, define it inside function you want to use it in and don't use any prefixes - classname nor self.

Wax Cage
  • 788
  • 2
  • 8
  • 24
0

try this:

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

that way testdate becomes a public property if you want to leave it private use the solution of @Wax Cage

Phillip
  • 789
  • 4
  • 22
  • 1
    `unittest.TestCase.__init__` exists and should not be overridden, you arebreaking the test entirely. You'd use the `setUp()` method instead. Not that that's needed here, the class attribute was just fine, it didn't need moving to an instance attribute. – Martijn Pieters Jan 10 '18 at 15:15