File: test_default.py

package info (click to toggle)
python-orjson 3.10.7-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,180 kB
  • sloc: ansic: 11,270; python: 6,658; sh: 135; makefile: 9
file content (339 lines) | stat: -rw-r--r-- 9,050 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
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

import datetime
import sys
import uuid

import pytest

import orjson

try:
    import numpy
except ImportError:
    numpy = None  # type: ignore


class Custom:
    def __init__(self):
        self.name = uuid.uuid4().hex

    def __str__(self):
        return f"{self.__class__.__name__}({self.name})"


class Recursive:
    def __init__(self, cur):
        self.cur = cur


def default_recursive(obj):
    if obj.cur != 0:
        obj.cur -= 1
        return obj
    return obj.cur


def default_raises(obj):
    raise TypeError


class TestType:
    def test_default_not_callable(self):
        """
        dumps() default not callable
        """
        with pytest.raises(orjson.JSONEncodeError):
            orjson.dumps(Custom(), default=NotImplementedError)

        ran = False
        try:
            orjson.dumps(Custom(), default=NotImplementedError)
        except Exception as err:
            assert isinstance(err, orjson.JSONEncodeError)
            assert str(err) == "default serializer exceeds recursion limit"
            ran = True
        assert ran

    def test_default_func(self):
        """
        dumps() default function
        """
        ref = Custom()

        def default(obj):
            return str(obj)

        assert orjson.dumps(ref, default=default) == b'"%s"' % str(ref).encode("utf-8")

    def test_default_func_none(self):
        """
        dumps() default function None ok
        """
        assert orjson.dumps(Custom(), default=lambda x: None) == b"null"

    def test_default_func_empty(self):
        """
        dumps() default function no explicit return
        """
        ref = Custom()

        def default(obj):
            if isinstance(obj, set):
                return list(obj)

        assert orjson.dumps(ref, default=default) == b"null"
        assert orjson.dumps({ref}, default=default) == b"[null]"

    def test_default_func_exc(self):
        """
        dumps() default function raises exception
        """

        def default(obj):
            raise NotImplementedError

        with pytest.raises(orjson.JSONEncodeError):
            orjson.dumps(Custom(), default=default)

        ran = False
        try:
            orjson.dumps(Custom(), default=default)
        except Exception as err:
            assert isinstance(err, orjson.JSONEncodeError)
            assert str(err) == "Type is not JSON serializable: Custom"
            ran = True
        assert ran

    def test_default_exception_type(self):
        """
        dumps() TypeError in default() raises orjson.JSONEncodeError
        """
        ref = Custom()

        with pytest.raises(orjson.JSONEncodeError):
            orjson.dumps(ref, default=default_raises)

    def test_default_vectorcall_str(self):
        """
        dumps() default function vectorcall str
        """

        class SubStr(str):
            pass

        obj = SubStr("saasa")
        ref = b'"%s"' % str(obj).encode("utf-8")
        assert (
            orjson.dumps(obj, option=orjson.OPT_PASSTHROUGH_SUBCLASS, default=str)
            == ref
        )

    def test_default_vectorcall_list(self):
        """
        dumps() default function vectorcall list
        """
        obj = {1, 2}
        ref = b"[1,2]"
        assert orjson.dumps(obj, default=list) == ref

    def test_default_func_nested_str(self):
        """
        dumps() default function nested str
        """
        ref = Custom()

        def default(obj):
            return str(obj)

        assert orjson.dumps({"a": ref}, default=default) == b'{"a":"%s"}' % str(
            ref
        ).encode("utf-8")

    def test_default_func_list(self):
        """
        dumps() default function nested list
        """
        ref = Custom()

        def default(obj):
            if isinstance(obj, Custom):
                return [str(obj)]

        assert orjson.dumps({"a": ref}, default=default) == b'{"a":["%s"]}' % str(
            ref
        ).encode("utf-8")

    def test_default_func_nested_list(self):
        """
        dumps() default function list
        """
        ref = Custom()

        def default(obj):
            return str(obj)

        assert orjson.dumps([ref] * 100, default=default) == b"[%s]" % b",".join(
            b'"%s"' % str(ref).encode("utf-8") for _ in range(100)
        )

    def test_default_func_bytes(self):
        """
        dumps() default function errors on non-str
        """
        ref = Custom()

        def default(obj):
            return bytes(obj)

        with pytest.raises(orjson.JSONEncodeError):
            orjson.dumps(ref, default=default)

        ran = False
        try:
            orjson.dumps(ref, default=default)
        except Exception as err:
            assert isinstance(err, orjson.JSONEncodeError)
            assert str(err) == "Type is not JSON serializable: Custom"
            ran = True
        assert ran

    def test_default_func_invalid_str(self):
        """
        dumps() default function errors on invalid str
        """
        ref = Custom()

        def default(obj):
            return "\ud800"

        with pytest.raises(orjson.JSONEncodeError):
            orjson.dumps(ref, default=default)

    def test_default_lambda_ok(self):
        """
        dumps() default lambda
        """
        ref = Custom()
        assert orjson.dumps(ref, default=lambda x: str(x)) == b'"%s"' % str(ref).encode(
            "utf-8"
        )

    def test_default_callable_ok(self):
        """
        dumps() default callable
        """

        class CustomSerializer:
            def __init__(self):
                self._cache = {}

            def __call__(self, obj):
                if obj not in self._cache:
                    self._cache[obj] = str(obj)
                return self._cache[obj]

        ref_obj = Custom()
        ref_bytes = b'"%s"' % str(ref_obj).encode("utf-8")
        for obj in [ref_obj] * 100:
            assert orjson.dumps(obj, default=CustomSerializer()) == ref_bytes

    def test_default_recursion(self):
        """
        dumps() default recursion limit
        """
        assert orjson.dumps(Recursive(254), default=default_recursive) == b"0"

    def test_default_recursion_reset(self):
        """
        dumps() default recursion limit reset
        """
        assert (
            orjson.dumps(
                [Recursive(254), {"a": "b"}, Recursive(254), Recursive(254)],
                default=default_recursive,
            )
            == b'[0,{"a":"b"},0,0]'
        )

    def test_default_recursion_infinite(self):
        """
        dumps() default infinite recursion
        """
        ref = Custom()

        def default(obj):
            return obj

        refcount = sys.getrefcount(ref)
        with pytest.raises(orjson.JSONEncodeError):
            orjson.dumps(ref, default=default)
        assert sys.getrefcount(ref) == refcount

    def test_reference_cleanup_default_custom_pass(self):
        ref = Custom()

        def default(obj):
            if isinstance(ref, Custom):
                return str(ref)
            raise TypeError

        refcount = sys.getrefcount(ref)
        orjson.dumps(ref, default=default)
        assert sys.getrefcount(ref) == refcount

    def test_reference_cleanup_default_custom_error(self):
        """
        references to encoded objects are cleaned up
        """
        ref = Custom()

        def default(obj):
            raise TypeError

        refcount = sys.getrefcount(ref)
        with pytest.raises(orjson.JSONEncodeError):
            orjson.dumps(ref, default=default)
        assert sys.getrefcount(ref) == refcount

    def test_reference_cleanup_default_subclass(self):
        ref = datetime.datetime(1970, 1, 1, 0, 0, 0)

        def default(obj):
            if isinstance(ref, datetime.datetime):
                return repr(ref)
            raise TypeError

        refcount = sys.getrefcount(ref)
        orjson.dumps(ref, option=orjson.OPT_PASSTHROUGH_DATETIME, default=default)
        assert sys.getrefcount(ref) == refcount

    def test_reference_cleanup_default_subclass_lambda(self):
        ref = uuid.uuid4()

        refcount = sys.getrefcount(ref)
        orjson.dumps(
            ref, option=orjson.OPT_PASSTHROUGH_DATETIME, default=lambda val: str(val)
        )
        assert sys.getrefcount(ref) == refcount

    @pytest.mark.skipif(numpy is None, reason="numpy is not installed")
    def test_default_numpy(self):
        ref = numpy.array([""] * 100)
        refcount = sys.getrefcount(ref)
        orjson.dumps(
            ref, option=orjson.OPT_SERIALIZE_NUMPY, default=lambda val: val.tolist()
        )
        assert sys.getrefcount(ref) == refcount

    def test_default_set(self):
        """
        dumps() default function with set
        """

        def default(obj):
            if isinstance(obj, set):
                return list(obj)
            raise TypeError

        assert orjson.dumps({1, 2}, default=default) == b"[1,2]"