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__
class ClassValidation(unittest.TestCase):
def __init__(self, *args, **kwargs):
__main__.Foo = Foo
self.cls = Foo
self.instance = Foo().load_class()
unittest.TestCase.__init__(self, *args, **kwargs)
def test_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...)"