pax_global_header00006660000000000000000000000064144042200720014505gustar00rootroot0000000000000052 comment=ebe1deeb8d24e44ae5f41156c6139febd807d17f python-canonicaljson-2.0.0/000077500000000000000000000000001440422007200156445ustar00rootroot00000000000000python-canonicaljson-2.0.0/.github/000077500000000000000000000000001440422007200172045ustar00rootroot00000000000000python-canonicaljson-2.0.0/.github/CODEOWNERS000066400000000000000000000001641440422007200206000ustar00rootroot00000000000000# Automatically request reviews from the synapse-core team when a pull request comes in. * @matrix-org/synapse-core python-canonicaljson-2.0.0/.github/workflows/000077500000000000000000000000001440422007200212415ustar00rootroot00000000000000python-canonicaljson-2.0.0/.github/workflows/tests.yaml000066400000000000000000000026231440422007200232720ustar00rootroot00000000000000name: Tests on: push: branches: ["main"] pull_request: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: lint: runs-on: ubuntu-latest strategy: matrix: toxenv: - "pep8" - "black" - "mypy" steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: '3.7' - run: pip install tox - run: tox -e ${{ matrix.toxenv }} unittest: runs-on: ubuntu-latest strategy: matrix: python-version: ['3.7', '3.8', '3.9', '3.10', 'pypy-3.7'] steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - run: pip install tox - run: tox -e py packaging: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest] steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: python -m pip install tox - run: tox -e packaging macos-tests: runs-on: macos-latest strategy: matrix: python-version: ["3.8", "3.9", "3.10"] steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - run: pip install tox - run: tox -e py python-canonicaljson-2.0.0/.gitignore000066400000000000000000000001301440422007200176260ustar00rootroot00000000000000/.coverage /.idea/ /.tox/ __pycache__/ *.egg-info/ *.pyc /build/ /dist/ .python-version python-canonicaljson-2.0.0/CHANGES.md000066400000000000000000000063361440422007200172460ustar00rootroot00000000000000Version 2.0.0 released 2023-03-15 Additions: * Add a generic `register_preserialisation_callback` mechanism, which allows users to teach canonicaljson how to JSON-encode custom types. Breaking changes: * Remove support for serialising `frozendict` instances. Use the new `register_preserialisation_callback` mechanism to replace this functionality if needed. * Remove support for `simplejson` and the `set_json_library`alternative json libraries. Version 1.6.5 released 2023-02-15 * Update type hints to pass under mypy 1.0. Version 1.6.4 released 2022-11-04 * Remove unused `setuptools_scm` build requirement. Version 1.6.3 released 2022-09-23 * Properly package the `canonicaljson` module. Version 1.6.2 released 2022-06-08 * Bump version to 1.6.2 The v1.6.1 tag was created without having bumped the version in `canonicaljson.py`. This means that installing from source at the `v1.6.1` tag will install the package with the wrong version in its metadata. The 1.6.1 artefacts uploaded to PyPI did have the correct version; `pip install`ing directly from the archive resulted in a consistent version number. Version 1.6.1 released 2022-05-02 * Add type annotations. Version 1.6.0 released 2022-03-04 * `frozendict` is now an optional dependency; it is no longer required. Version 1.5.0 released 2021-10-20 * Switch CI from Travis to Github Actions * Add code to handle frozendict implementations using c-extension * Add tests for Python 3.10 * Remove outdated Debian packaging code Version 1.4.0 released 2020-09-03 * Fix producing non-standard JSON for Infinity, -Infinity, and NaN. This could cause errors when encoding objects into canonical JSON that previously used to work, but were incompatible with JSON implementations in other languages. * Use UTF-8 to fix ASCII encoding errors when data containing Unicode was attempted to be pretty-printed. Version 1.3.0 released 2020-08-14 * The minimum version of simplejson was bumped to 3.14.0. * Obsolete workaround for slow encoding of Unicode characters was removed. * New APIs were added to iteratively encode JSON. Version 1.2.0 released 2020-07-27 * JSON from the standard library is used automatically on PyPy. * Support for Python versions which are end-of-lifed was dropped, Python >= 3.5 is supported and tested in continuous integration. * An API to configure the underlying JSON library was added (`set_json_library`). Version 1.1.4 released 2018-05-23 * Fix error when encoding non-BMP characters on UCS-2 python builds (fixes issue #12). Version 1.1.3 released 2018-04-13 * Bump depencency on frozendict to >=1.0, to fix conflicts with older versions. Version 1.1.2 released 2018-04-12 * Fix escaping of control characters U+0000 to U+001F AGAIN, which was STILL broken in the previous release Version 1.1.1 released 2018-04-11 * Fix escaping of control characters U+0000 to U+001F, which was broken in the previous release Version 1.1.0 released 2018-04-06 * Significant performance improvements ([\#7](https://github.com/matrix-org/python-canonicaljson/pull/7), [\#8](https://github.com/matrix-org/python-canonicaljson/pull/8), [\#9](https://github.com/matrix-org/python-canonicaljson/pull/9)) Version 1.0.0 released 2015-08-21 * Initial release python-canonicaljson-2.0.0/LICENSE000066400000000000000000000236761440422007200166670ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS python-canonicaljson-2.0.0/MANIFEST.in000066400000000000000000000001071440422007200174000ustar00rootroot00000000000000prune .github include *.md include tox.ini recursive-include tests *.pypython-canonicaljson-2.0.0/README.rst000066400000000000000000000037221440422007200173370ustar00rootroot00000000000000Canonical JSON ============== .. image:: https://img.shields.io/pypi/v/canonicaljson.svg :target: https://pypi.python.org/pypi/canonicaljson/ :alt: Latest Version Features -------- * Encodes objects and arrays as `RFC 7159`_ JSON. * Sorts object keys so that you get the same result each time. * Has no insignificant whitespace to make the output as small as possible. * Escapes only the characters that must be escaped, U+0000 to U+0019 / U+0022 / U+0056, to keep the output as small as possible. * Uses the shortest escape sequence for each escaped character. * Encodes the JSON as UTF-8. * Can be configured to encode custom types unknown to the stdlib JSON encoder. Supports Python versions 3.7 and newer. .. _`RFC 7159`: https://tools.ietf.org/html/rfc7159 Installing ---------- .. code:: bash pip install canonicaljson Using ----- To encode an object into the canonicaljson: .. code:: python import canonicaljson assert canonicaljson.encode_canonical_json({}) == b'{}' There's also an iterator version: .. code:: python import canonicaljson assert b''.join(canonicaljson.iterencode_canonical_json({})) == b'{}' The underlying JSON implementation can be chosen with the following: .. code:: python import json import canonicaljson canonicaljson.set_json_library(json) .. note:: By default canonicaljson uses `simplejson`_ under the hood (except for PyPy, which uses the standard library json module). .. _simplejson: https://simplejson.readthedocs.io/ A preserialisation hook allows you to encode objects which aren't encodable by the standard library ``JSONEncoder``. .. code:: python import canonicaljson from typing import Dict class CustomType: pass def callback(c: CustomType) -> Dict[str, str]: return {"Hello": "world!"} canonicaljson.register_preserialisation_callback(CustomType, callback) assert canonicaljson.encode_canonical_json(CustomType()) == b'{"Hello":"world!"}' python-canonicaljson-2.0.0/pyproject.toml000066400000000000000000000002441440422007200205600ustar00rootroot00000000000000[tool.mypy] show_error_codes = true strict = true files = ["."] [build-system] requires = [ "setuptools >= 35.0.2", ] build-backend = "setuptools.build_meta" python-canonicaljson-2.0.0/releasing.md000066400000000000000000000004661440422007200201450ustar00rootroot00000000000000Releasing python-canonicaljson ============================== * bump version in `src/canonicaljson/__init__.py` * update changelog * Build and upload to pypi: * `rm -r ./**/*.egg-info` * `rm -r dist` * `python -m build` * `twine upload -s dist/*` * `git tag -s v` * `git push` * `git push --tags`python-canonicaljson-2.0.0/setup.cfg000066400000000000000000000017061440422007200174710ustar00rootroot00000000000000[metadata] name = canonicaljson description = Canonical JSON long_description = file: README.rst long_description_content_type = text/x-rst version = attr: canonicaljson.__version__ keywords = json url = https://github.com/matrix-org/python-canonicaljson license = Apache License, Version 2.0 author = Matrix.org Team and Contributors author_email = packages@matrix.org license_file = LICENSE classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: Apache Software License Programming Language :: Python :: 2 Programming Language :: Python :: 3 [options] zip_safe = true python_requires = >=3.7 package_dir = =src packages = canonicaljson [options.package_data] canonicaljson = py.typed [flake8] # see https://pycodestyle.readthedocs.io/en/latest/intro.html#error-codes # for error codes. The ones we ignore are: # E501: Line too long (black enforces this for us) ignore=E501 python-canonicaljson-2.0.0/src/000077500000000000000000000000001440422007200164335ustar00rootroot00000000000000python-canonicaljson-2.0.0/src/canonicaljson/000077500000000000000000000000001440422007200212545ustar00rootroot00000000000000python-canonicaljson-2.0.0/src/canonicaljson/__init__.py000066400000000000000000000076721440422007200234010ustar00rootroot00000000000000# Copyright 2014 OpenMarket Ltd # Copyright 2018 New Vector Ltd # Copyright 2022 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import json from typing import Callable, Generator, Type, TypeVar __version__ = "2.0.0" @functools.singledispatch def _preprocess_for_serialisation(obj: object) -> object: # pragma: no cover """Transform an `obj` into something the JSON library knows how to encode. This is only called for types that the JSON library does not recognise. """ raise TypeError( "Object of type %s is not JSON serializable" % obj.__class__.__name__ ) T = TypeVar("T") def register_preserialisation_callback( data_type: Type[T], callback: Callable[[T], object] ) -> None: """ Register a `callback` to preprocess `data_type` objects unknown to the JSON encoder. When canonicaljson encodes an object `x` at runtime that its JSON library does not know how to encode, it will - select a `callback`, - compute `y = callback(x)`, then - JSON-encode `y` and return the result. The `callback` should return an object that is JSON-serialisable by the stdlib json module. If this is called multiple times with the same `data_type`, the most recently registered callback is used when serialising that `data_type`. """ if data_type is object: raise ValueError("Cannot register callback for the `object` type") _preprocess_for_serialisation.register(data_type, callback) # Declare these once for re-use. _canonical_encoder = json.JSONEncoder( ensure_ascii=False, allow_nan=False, separators=(",", ":"), sort_keys=True, default=_preprocess_for_serialisation, ) _pretty_encoder = json.JSONEncoder( ensure_ascii=False, allow_nan=False, indent=4, sort_keys=True, default=_preprocess_for_serialisation, ) def encode_canonical_json(data: object) -> bytes: """Encodes the given `data` as a UTF-8 canonical JSON bytestring. This encoding is the shortest possible. Dictionary keys are lexicographically sorted by unicode code point. """ s = _canonical_encoder.encode(data) return s.encode("utf-8") def iterencode_canonical_json(data: object) -> Generator[bytes, None, None]: """Iteratively encodes the given `data` as a UTF-8 canonical JSON bytestring. This yields one or more bytestrings; concatenating them all together yields the full encoding of `data`. Building up the encoding gradually in this way allows us to encode large pieces of `data` without blocking other tasks. This encoding is the shortest possible. Dictionary keys are lexicographically sorted by unicode code point. """ for chunk in _canonical_encoder.iterencode(data): yield chunk.encode("utf-8") def encode_pretty_printed_json(data: object) -> bytes: """Encodes the given `data` as a UTF-8 human-readable JSON bytestring.""" return _pretty_encoder.encode(data).encode("utf-8") def iterencode_pretty_printed_json(data: object) -> Generator[bytes, None, None]: """Iteratively encodes the given `data` as a UTF-8 human-readable JSON bytestring. This yields one or more bytestrings; concatenating them all together yields the full encoding of `data`. Building up the encoding gradually in this way allows us to encode large pieces of `data` without blocking other tasks. """ for chunk in _pretty_encoder.iterencode(data): yield chunk.encode("utf-8") python-canonicaljson-2.0.0/src/canonicaljson/py.typed000066400000000000000000000000001440422007200227410ustar00rootroot00000000000000python-canonicaljson-2.0.0/tests/000077500000000000000000000000001440422007200170065ustar00rootroot00000000000000python-canonicaljson-2.0.0/tests/__init__.py000066400000000000000000000011241440422007200211150ustar00rootroot00000000000000# Copyright 2022 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. python-canonicaljson-2.0.0/tests/test_canonicaljson.py000066400000000000000000000140631440422007200232440ustar00rootroot00000000000000# Copyright 2015 OpenMarket Ltd # Copyright 2018 New Vector Ltd # Copyright 2022 The Matrix.org Foundation C.I.C. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unittest.mock import Mock from math import inf, nan from canonicaljson import ( encode_canonical_json, encode_pretty_printed_json, iterencode_canonical_json, iterencode_pretty_printed_json, register_preserialisation_callback, ) import unittest class TestCanonicalJson(unittest.TestCase): def test_encode_canonical(self) -> None: self.assertEqual(encode_canonical_json({}), b"{}") # ctrl-chars should be encoded. self.assertEqual( encode_canonical_json(u"text\u0003\r\n"), b'"text\\u0003\\r\\n"', ) # quotes and backslashes should be escaped. self.assertEqual( encode_canonical_json(r'"\ test'), b'"\\"\\\\ test"', ) # non-ascii should come out utf8-encoded. self.assertEqual( encode_canonical_json({u"la merde amusée": u"💩"}), b'{"la merde amus\xc3\xa9e":"\xF0\x9F\x92\xA9"}', ) # so should U+2028 and U+2029 self.assertEqual( encode_canonical_json({u"spaces": u"\u2028 \u2029"}), b'{"spaces":"\xe2\x80\xa8 \xe2\x80\xa9"}', ) # but we need to watch out for 'u1234' after backslash, which should # get encoded to an escaped backslash, followed by u1234 self.assertEqual( encode_canonical_json(u"\\u1234"), b'"\\\\u1234"', ) # Iteratively encoding should work. self.assertEqual(list(iterencode_canonical_json({})), [b"{}"]) def test_ascii(self) -> None: """ Ensure the proper ASCII characters are escaped. See https://matrix.org/docs/spec/appendices#grammar. """ # Some characters go to their common shorthands. escaped = { 0x08: b'"\\b"', 0x09: b'"\\t"', 0x0A: b'"\\n"', 0x0C: b'"\\f"', 0x0D: b'"\\r"', 0x22: b'"\\""', 0x5C: b'"\\\\"', } for c, expected in escaped.items(): self.assertEqual(encode_canonical_json(chr(c)), expected) # Others go to the \uXXXX. hex_escaped = list(range(0x08)) + [0x0B] + list(range(0x0E, 0x20)) for c in hex_escaped: self.assertEqual(encode_canonical_json(chr(c)), b'"\\u00%02x"' % (c,)) # And other characters are passed unescaped. unescaped = [0x20, 0x21] + list(range(0x23, 0x5C)) + list(range(0x5D, 0x7E)) for c in unescaped: s = chr(c) self.assertEqual(encode_canonical_json(s), b'"' + s.encode("ascii") + b'"') def test_encode_pretty_printed(self) -> None: self.assertEqual(encode_pretty_printed_json({}), b"{}") self.assertEqual(list(iterencode_pretty_printed_json({})), [b"{}"]) # non-ascii should come out utf8-encoded. self.assertEqual( encode_pretty_printed_json({u"la merde amusée": u"💩"}), b'{\n "la merde amus\xc3\xa9e": "\xF0\x9F\x92\xA9"\n}', ) def test_unknown_type(self) -> None: class Unknown(object): pass unknown_object = Unknown() with self.assertRaises(Exception): encode_canonical_json(unknown_object) with self.assertRaises(Exception): encode_pretty_printed_json(unknown_object) def test_invalid_float_values(self) -> None: """Infinity/-Infinity/NaN are not allowed in canonicaljson.""" with self.assertRaises(ValueError): encode_canonical_json(inf) with self.assertRaises(ValueError): encode_pretty_printed_json(inf) with self.assertRaises(ValueError): encode_canonical_json(-inf) with self.assertRaises(ValueError): encode_pretty_printed_json(-inf) with self.assertRaises(ValueError): encode_canonical_json(nan) with self.assertRaises(ValueError): encode_pretty_printed_json(nan) def test_encode_unknown_class_raises(self) -> None: class C: pass with self.assertRaises(Exception): encode_canonical_json(C()) def test_preserialisation_callback(self) -> None: class C: pass # Naughty: this alters the global state of the module. However this # `C` class is limited to this test only, so this shouldn't affect # other types and other tests. register_preserialisation_callback(C, lambda c: "I am a C instance") result = encode_canonical_json(C()) self.assertEqual(result, b'"I am a C instance"') def test_cannot_register_preserialisation_callback_for_object(self) -> None: with self.assertRaises(Exception): register_preserialisation_callback( object, lambda c: "shouldn't be able to do this" ) def test_most_recent_preserialisation_callback_called(self) -> None: class C: pass callback1 = Mock(return_value="callback 1 was called") callback2 = Mock(return_value="callback 2 was called") # Naughty: this alters the global state of the module. However this # `C` class is limited to this test only, so this shouldn't affect # other types and other tests. register_preserialisation_callback(C, callback1) register_preserialisation_callback(C, callback2) encode_canonical_json(C()) callback1.assert_not_called() callback2.assert_called_once() python-canonicaljson-2.0.0/tox.ini000066400000000000000000000013271440422007200171620ustar00rootroot00000000000000[tox] envlist = packaging, pep8, black, py37, py38, py39, py310, pypy3, mypy, isort isolated_build = True [testenv:py] deps = coverage nose2 commands = coverage run --source canonicaljson -m nose2 coverage report -m --fail-under 100 [testenv:packaging] deps = check-manifest commands = check-manifest [testenv:pep8] basepython = python3.7 deps = flake8 commands = flake8 src tests [testenv:black] basepython = python3.7 deps = black==21.9b0 # Workaround black+click incompatability, see https://github.com/psf/black/issues/2964 click==8.0.4 commands = python -m black --check --diff src tests [testenv:mypy] deps = mypy==1.0 types-setuptools==57.4.14 commands = mypy src tests