| 1 |
import jsonpickle |
| 2 |
|
| 3 |
|
| 4 |
class Node: |
| 5 |
def __init__(self, name): |
| 6 |
self._name = name |
| 7 |
self._children = [] |
| 8 |
self._parent = None |
| 9 |
|
| 10 |
def add_child(self, child, index=-1): |
| 11 |
if index == -1: |
| 12 |
index = len(self._children) |
| 13 |
self._children.insert(index, child) |
| 14 |
child._parent = self |
| 15 |
|
| 16 |
|
| 17 |
class Document(Node): |
| 18 |
def __init__(self, name): |
| 19 |
Node.__init__(self, name) |
| 20 |
|
| 21 |
def __repr__(self): |
| 22 |
return str(self) |
| 23 |
|
| 24 |
def __str__(self): |
| 25 |
ret_str = 'Document "%s"\n' % self._name |
| 26 |
for c in self._children: |
| 27 |
ret_str += repr(c) |
| 28 |
return ret_str |
| 29 |
|
| 30 |
|
| 31 |
class Question(Node): |
| 32 |
def __init__(self, name): |
| 33 |
Node.__init__(self, name) |
| 34 |
|
| 35 |
def __str__(self): |
| 36 |
return f'Question "{self._name}", parent: "{self._parent._name}"\n' |
| 37 |
|
| 38 |
def __repr__(self): |
| 39 |
return self.__str__() |
| 40 |
|
| 41 |
|
| 42 |
class Section(Node): |
| 43 |
def __init__(self, name): |
| 44 |
Node.__init__(self, name) |
| 45 |
|
| 46 |
def __str__(self): |
| 47 |
ret_str = f'Section "{self._name}", parent: "{self._parent._name}"\n' |
| 48 |
for c in self._children: |
| 49 |
ret_str += repr(c) |
| 50 |
return ret_str |
| 51 |
|
| 52 |
def __repr__(self): |
| 53 |
return self.__str__() |
| 54 |
|
| 55 |
|
| 56 |
def test_cyclical(): |
| 57 |
"""Test that we can pickle cyclical data structure |
| 58 |
|
| 59 |
This test is ensures that we can reference objects which |
| 60 |
first appear within a list (in other words, not a top-level |
| 61 |
object or attribute). Later children will reference that |
| 62 |
object through its "_parent" field. |
| 63 |
|
| 64 |
This makes sure that we handle this case correctly. |
| 65 |
|
| 66 |
""" |
| 67 |
document = Document('My Document') |
| 68 |
section1 = Section('Section 1') |
| 69 |
section2 = Section('Section 2') |
| 70 |
question1 = Question('Question 1') |
| 71 |
question2 = Question('Question 2') |
| 72 |
question3 = Question('Question 3') |
| 73 |
question4 = Question('Question 4') |
| 74 |
document.add_child(section1) |
| 75 |
document.add_child(section2) |
| 76 |
section1.add_child(question1) |
| 77 |
section1.add_child(question2) |
| 78 |
section2.add_child(question3) |
| 79 |
section2.add_child(question4) |
| 80 |
pickled = jsonpickle.encode(document) |
| 81 |
unpickled = jsonpickle.decode(pickled) |
| 82 |
assert str(document) == str(unpickled) |