Pickle-proof stix objects

stix2.0
Michael Chisholm 2018-06-06 15:30:45 -04:00
parent d67f2da0ea
commit 5a9f627669
2 changed files with 24 additions and 1 deletions

View File

@ -185,7 +185,13 @@ class _STIXBase(collections.Mapping):
# Handle attribute access just like key access
def __getattr__(self, name):
if name in self:
# Pickle-proofing: pickle invokes this on uninitialized instances (i.e.
# __init__ has not run). So no "self" attributes are set yet. The
# usual behavior of this method reads an __init__-assigned attribute,
# which would cause infinite recursion. So this check disables all
# attribute reads until the instance has been properly initialized.
unpickling = "_inner" not in self.__dict__
if not unpickling and name in self:
return self.__getitem__(name)
raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name))

17
stix2/test/test_pickle.py Normal file
View File

@ -0,0 +1,17 @@
import pickle
import stix2
def test_pickling():
"""
Ensure a pickle/unpickle cycle works okay.
"""
identity = stix2.Identity(
id="identity--d66cb89d-5228-4983-958c-fa84ef75c88c",
name="alice",
description="this is a pickle test",
identity_class="some_class"
)
pickle.loads(pickle.dumps(identity))