def from_json(obj): if '__class__' in obj: if obj['__class__'] == 'User': user = User(obj['name']) user.skillset = obj['skills'] return user if obj['__class__'] == 'Skill': return Skill(obj['name'], obj['hours']) return obj
class TKSerializerTest(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.user = User("rdg") def tearDown(self): unittest.TestCase.tearDown(self) del self.user.skillset[:] def test_serializer(self): """serializer should successfully convert from custom classes to json and vice versa""" self.user.add_skill("programming", 50) self.user.add_skill("chinese", 200) with open('test.tk', encoding='utf-8', mode='w') as f: json.dump(self.user, f, default=tkserializer.to_json, indent=2) with open('test.tk', encoding='utf-8', mode='r') as f: user2 = json.load(f, object_hook=tkserializer.from_json) os.remove('test.tk') self.assertEqual(self.user, user2)
def setUp(self): unittest.TestCase.setUp(self) self.user = User("rdg")