Merge pull request #187 from chisholm/pickle_proof

Pickle-proof stix objects
stix2.0
Greg Back 2018-06-12 10:46:13 -05:00 committed by GitHub
commit 3ea4474615
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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 # Handle attribute access just like key access
def __getattr__(self, name): 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) return self.__getitem__(name)
raise AttributeError("'%s' object has no attribute '%s'" % raise AttributeError("'%s' object has no attribute '%s'" %
(self.__class__.__name__, name)) (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))