Search code examples
pythonjsonpython-unittestattributeerror

object has no attribute 'loads' in UnitTest class


Im trying to run some tests in python. Im using Unittest framework.

The test "test_processJson" uses a test Json, dictTestString, and then checks if it has one or more elements. This is my script "testing.py"

import json
import starter#The code Im trying to test
import unittest

class MyTests(unittest.TestCase):

    def test_processJson(json):
        dictTestString = '{"city":"Barcelona"}'
        jTest = json.loads(dictTestString)  
        dictProcess = starter.processJson(dictTest)

        self.assertEquals(dictProcess["city"], "Barcelona")

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

The problem comes when I run the test I get this error:

Traceback (most recent call last):

File "testing.py", line 16, in test_processJson

jTest = json.loads(dictTestString)

AttributeError: 'MyTests' object has no attribute 'loads'

I'm new to python, so I've been looking for an answer but any of the mistakes I've seen Im not doing.

Any help will be appreciated.

Thanks.


Solution

  • Your function's argument is named json, which shadow's the global json module. Actually since this is the first argument of a method, it get bound to the current MyTest instance, and since unittest test methods only expect the current instance as argument AND you don't have any need for a json argument here, you just have to rename it to self (which is the convention for the first argument of instance methods) and you problem will be solved.

    NB : There are a couple other typos / issues with your code but I leave it up to you to find and solve them - that's part of the fun isn't it ?