File: collections_test.py

package info (click to toggle)
jsonpickle 3.0.0%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,184 kB
  • sloc: python: 6,088; javascript: 654; makefile: 90; sh: 17
file content (369 lines) | stat: -rw-r--r-- 11,356 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# -*- coding: utf-8 -*-
#
# This document is free and open-source software, subject to the OSI-approved
# BSD license below.
#
# Copyright (c) 2014 Alexis Petrounias <www.petrounias.org>,
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the author nor the names of its contributors may be used
# to endorse or promote products derived from this software without specific
# prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
Unit tests for collections
"""
from __future__ import absolute_import, division, print_function, unicode_literals

import sys
from collections import OrderedDict, defaultdict

import pytest

import jsonpickle

__status__ = "Stable"
__version__ = "1.0.0"
__maintainer__ = "Alexis Petrounias <www.petrounias.org>"
__author__ = "Alexis Petrounias <www.petrounias.org>"


"""
Classes featuring various collections used by
:mod:`restorable_collections_tests` unit tests; these classes must be
module-level (including the default dictionary factory method) so that they
can be pickled.

Tests restorable collections by creating pickled structures featuring
no cycles, self cycles, and mutual cycles, for all supported dictionary and
set wrappers. Python built-in dictionaries and sets are also tested with
expectation of failure via raising exceptions.

"""


class Group(object):
    def __init__(self, name):
        super(Group, self).__init__()
        self.name = name
        self.elements = []

    def __repr__(self):
        return 'Group({})'.format(self.name)


class C(object):
    def __init__(self, v):
        super(C, self).__init__()
        self.v = v
        self.plain = dict()
        self.plain_ordered = OrderedDict()
        self.plain_default = defaultdict(c_factory)

    def add(self, key, value):
        self.plain[key] = (key, value)
        self.plain_ordered[key] = (key, value)
        self.plain_default[key] = (key, value)

    def __hash__(self):
        return hash(self.v) if hasattr(self, 'v') else id(self)

    def __repr__(self):
        return 'C({})'.format(self.v)


def c_factory():
    return (C(0), '_')


class D(object):
    def __init__(self, v):
        super(D, self).__init__()
        self.v = v
        self.plain = set()

    def add(self, item):
        self.plain.add(item)

    def __hash__(self):
        return hash(self.v) if hasattr(self, 'v') else id(self)

    def __repr__(self):
        return 'D({})'.format(self.v)


def pickle_and_unpickle(obj):
    encoded = jsonpickle.encode(obj, keys=True)
    return jsonpickle.decode(encoded, keys=True)


def test_dict_no_cycle():
    g = Group('group')
    c1 = C(42)
    g.elements.append(c1)
    c2 = C(67)
    g.elements.append(c2)
    c1.add(c2, 'a')  # points to c2, which does not point to anything

    assert c2 in c1.plain
    assert c2 in c1.plain_ordered
    assert c2 in c1.plain_default

    gu = pickle_and_unpickle(g)
    c1u = gu.elements[0]
    c2u = gu.elements[1]

    # check existence of keys directly
    assert c2u in c1u.plain.keys()
    assert c2u in c1u.plain_ordered.keys()
    assert c2u in c1u.plain_default.keys()

    # check direct key-based lookup
    assert c2u == c1u.plain[c2u][0]
    assert c2u == c1u.plain_ordered[c2u][0]
    assert c2u == c1u.plain_default[c2u][0]

    # check key lookup with key directly from keys()
    plain_keys = list(c1u.plain.keys())
    ordered_keys = list(c1u.plain_ordered.keys())
    default_keys = list(c1u.plain_default.keys())
    assert c2u == c1u.plain[plain_keys[0]][0]
    assert c2u == c1u.plain_ordered[ordered_keys[0]][0]
    assert c2u == c1u.plain_default[default_keys[0]][0]
    assert c2u == c1u.plain[plain_keys[0]][0]
    assert c2u == c1u.plain_ordered[ordered_keys[0]][0]
    assert c2u == c1u.plain_default[default_keys[0]][0]


def test_dict_self_cycle():
    g = Group('group')
    c1 = C(42)
    g.elements.append(c1)
    c2 = C(67)
    g.elements.append(c2)
    c1.add(c1, 'a')  # cycle to itself
    c1.add(c2, 'b')  # c2 does not point to itself nor c1

    assert c1 in c1.plain
    assert c1 in c1.plain_ordered
    assert c1 in c1.plain_default

    gu = pickle_and_unpickle(g)
    c1u = gu.elements[0]
    c2u = gu.elements[1]

    # check existence of keys directly
    # key c1u
    assert c1u in list(c1u.plain.keys())
    assert c1u in list(c1u.plain_ordered.keys())
    assert c1u in list(c1u.plain_default.keys())

    # key c2u
    assert c2u in list(c1u.plain.keys())
    assert c2u in list(c1u.plain_ordered.keys())
    assert c2u in list(c1u.plain_default.keys())

    # check direct key-based lookup

    # key c1u
    assert 42 == c1u.plain[c1u][0].v
    assert 42 == c1u.plain_ordered[c1u][0].v

    assert len(c1u.plain_default) == 2
    assert 42 == c1u.plain_default[c1u][0].v
    # No new entries were created.
    assert len(c1u.plain_default) == 2

    # key c2u
    # succeeds because c2u does not have a cycle to itself
    assert c2u == c1u.plain[c2u][0]
    # succeeds because c2u does not have a cycle to itself
    assert c2u == c1u.plain_ordered[c2u][0]
    # succeeds because c2u does not have a cycle to itself
    assert c2u == c1u.plain_default[c2u][0]
    assert c2u == c1u.plain[c2u][0]
    assert c2u == c1u.plain_ordered[c2u][0]
    assert c2u == c1u.plain_default[c2u][0]

    # check key lookup with key directly from keys()
    # key c1u
    plain_keys = list(c1u.plain.keys())
    ordered_keys = list(c1u.plain_ordered.keys())
    default_keys = list(c1u.plain_default.keys())
    value = 42
    assert value == c1u.plain[plain_keys[0]][0].v
    42 == c1u.plain_ordered[ordered_keys[0]][0].v
    42 == c1u.plain_default[default_keys[0]][0].v

    # key c2u
    # succeeds because c2u does not have a cycle to itself
    assert c2u == c1u.plain[plain_keys[1]][0]
    # succeeds because c2u does not have a cycle to itself
    assert c2u == c1u.plain_ordered[ordered_keys[1]][0]
    assert 67 == c1u.plain_default[default_keys[1]][0].v


def test_dict_mutual_cycle():
    g = Group('group')
    c1 = C(42)
    g.elements.append(c1)
    c2 = C(67)
    g.elements.append(c2)

    c1.add(c2, 'a')  # points to c2, which points to c1, forming cycle
    c2.add(c1, 'a')  # points to c1 in order to form cycle

    assert c2 in c1.plain
    assert c2 in c1.plain_ordered
    assert c2 in c1.plain_default

    assert c1 in c2.plain
    assert c1 in c2.plain_ordered
    assert c1 in c2.plain_default

    gu = pickle_and_unpickle(g)
    c1u = gu.elements[0]
    c2u = gu.elements[1]

    # check existence of keys directly
    # key c2u
    assert c2u in c1u.plain.keys()
    assert c2u in c1u.plain_ordered.keys()
    assert c2u in c1u.plain_default.keys()

    # key c1u
    assert c1u in list(c2u.plain.keys())
    assert c1u in list(c2u.plain_ordered.keys())
    assert c1u in list(c2u.plain_default.keys())

    # check direct key-based lookup
    # key c2u, succeed because c2u added to c1u after __setstate__
    assert c2u == c1u.plain[c2u][0]
    assert c2u == c1u.plain_ordered[c2u][0]
    assert c2u == c1u.plain_default[c2u][0]

    # key c1u
    assert isinstance(c2u.plain[c1u][0], C)
    assert 42 == c2u.plain[c1u][0].v
    assert isinstance(c2u.plain_ordered[c1u][0], C)

    # succeeds
    assert len(c2u.plain_default) == 1
    assert 42 == c2u.plain_default[c1u][0].v
    # Ensure that no new entry is created by verifying that the length
    # has not changed.
    assert len(c2u.plain_default) == 1

    # check key lookup with key directly from keys()

    # key c2u, succeed because c2u added to c1u after __setstate__
    plain_keys = list(c1u.plain.keys())
    ordered_keys = list(c1u.plain_ordered.keys())
    default_keys = list(c1u.plain_default.keys())
    assert c2u == c1u.plain[plain_keys[0]][0]
    assert c2u == c1u.plain_ordered[ordered_keys[0]][0]
    assert c2u == c1u.plain_default[default_keys[0]][0]

    # key c1u
    plain_keys = list(c2u.plain.keys())
    ordered_keys = list(c2u.plain_ordered.keys())
    default_keys = list(c2u.plain_default.keys())
    assert 42 == c2u.plain[plain_keys[0]][0].v
    assert 42 == c2u.plain_ordered[ordered_keys[0]][0].v
    assert 42 == c2u.plain_default[default_keys[0]][0].v
    assert isinstance(c2u.plain[plain_keys[0]], tuple)
    assert isinstance(c2u.plain_ordered[ordered_keys[0]], tuple)


def test_set_no_cycle():
    g = Group('group')
    d1 = D(42)
    g.elements.append(d1)
    d2 = D(67)
    g.elements.append(d2)
    d1.add(d2)  # d1 points to d1, d2 does not point to anything, no cycles

    assert d2 in d1.plain

    gu = pickle_and_unpickle(g)
    d1u = gu.elements[0]
    d2u = gu.elements[1]

    # check element directly
    assert d2u in d1u.plain
    # check element taken from elements
    assert list(d1u.plain)[0] in d1u.plain


def test_set_self_cycle():
    g = Group('group')
    d1 = D(42)
    g.elements.append(d1)
    d2 = D(67)
    g.elements.append(d2)
    d1.add(d1)  # cycle to itself
    d1.add(d2)  # d1 also points to d2, but d2 does not point to d1

    assert d1 in d1.plain

    gu = pickle_and_unpickle(g)
    d1u = gu.elements[0]
    d2u = gu.elements[1]
    assert d2u is not None

    # check element directly
    assert d1u in d1u.plain
    # check element taken from elements
    assert list(d1u.plain)[0] in d1u.plain
    # succeeds because d2u added to d1u after __setstate__
    assert list(d1u.plain)[1] in d1u.plain


def test_set_mutual_cycle():
    g = Group('group')
    d1 = D(42)
    g.elements.append(d1)
    d2 = D(67)
    g.elements.append(d2)
    d1.add(d2)  # points to d2, which points to d1, forming cycle
    d2.add(d1)  # points to d1 in order to form cycle

    assert d2 in d1.plain
    assert d1 in d2.plain

    gu = pickle_and_unpickle(g)
    d1u = gu.elements[0]
    d2u = gu.elements[1]

    # check element directly
    # succeeds because d2u added to d1u after __setstate__
    assert d2u in d1u.plain
    assert d1u in d2u.plain
    # check element taken from elements
    # succeeds because d2u added to d1u after __setstate__
    assert list(d1u.plain)[0] in d1u.plain
    assert list(d2u.plain)[0] in d2u.plain


if __name__ == '__main__':
    pytest.main([__file__] + sys.argv[1:])