python unit test - how to test function local JSON object has correct key value pairs?

3.1k Views Asked by At

I'm new to Python and unit testing as I just started looking into it this morning. I have a object that has a number of key/pair values as well as one of those key/pairs being another object.

ie.

my_program.py

    def my_function(self):
        my_obj = {
            "someKey": 1234-5678,
            "locationId": self.location_id,
            "environment": self.environment_name,
            "metaData" : {
                "log_id": self.last_log_id,
                "satisfied": False 
            }
        }


tests_my_program.py

import unittest2
import mock

    def test_should_check__my_function__payload_obj_is_set(self):
        #code here to test the variable has all of those key/pair values

How do I write a unit test to ensure that this object always has these key/pair values (someKey, locationId, etc.) ? My tests are in a separate python file (test_my_program.py) so would i need to mock my_obj to the test function?

This variable is local to a function so it's not global.

1

There are 1 best solutions below

4
On
import unittest
from my_program import my_obj

class MyTest(unittest.TestCase):
    def test_the_thing(self):
        self.assertEqual(my_obj['key1']['key2'], 3)

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

if you just want to know if the value is true use self.assertTrue(my_obj['key1']['key2']) or self.assertFalse

I'm not sure what you mean by "mock my_obj" but you can just import it from the other module to test it. Why mock when you can use the real thing?