Skip to content Skip to sidebar Skip to footer

Unittest Unable To Import Class From Pickle (attributeerror: Can't Get Attribute...)

I need a unittest to load a previously saved class in a pickle. However, when I load the pickle in the unittest (out of unittest works), it raises the error: AttributeError: Can't

Solution 1:

The problem is that pickle saves the object relative to __main__, where dump was called (via save_class). To load the same object, you have to provide the same environment - a workaround is to add the class to __main__ in your test, so that pickle can find it:

import __main__

classClassValidation(unittest.TestCase):

    def__init__(self, *args, **kwargs):
        __main__.Foo = Foo
        self.cls = Foo
        self.instance = Foo().load_class()
        unittest.TestCase.__init__(self, *args, **kwargs)

    deftest_anything(self):
        self.assertEqual("saving a bar", self.instance.bar)

Solution 2:

Try to instanciate the Foo object in the ClassValidation in this way : self.cls = Foo()

Post a Comment for "Unittest Unable To Import Class From Pickle (attributeerror: Can't Get Attribute...)"