pax_global_header00006660000000000000000000000064137242123570014520gustar00rootroot0000000000000052 comment=f691369863a11a0204097e3578172a04b5f6b14a python-canonicaljson-1.4.0/000077500000000000000000000000001372421235700156625ustar00rootroot00000000000000python-canonicaljson-1.4.0/.gitignore000066400000000000000000000001301372421235700176440ustar00rootroot00000000000000/.coverage /.idea/ /.tox/ __pycache__/ *.egg-info/ *.pyc /build/ /dist/ .python-version python-canonicaljson-1.4.0/.travis.yml000066400000000000000000000010331372421235700177700ustar00rootroot00000000000000language: python # tell travis to cache ~/.cache/pip cache: pip matrix: include: - python: 3.6 env: TOXENV=packaging - python: 3.6 env: TOXENV=pep8 - python: 3.6 env: TOXENV=black - python: 3.5 env: TOXENV=py35 - python: 3.6 env: TOXENV=py36 - python: 3.7 env: TOXENV=py37 - python: 3.8 env: TOXENV=py38 - os: osx language: generic env: TOXENV=py38 - python: pypy3 env: TOXENV=pypy3 install: - ./.travis/install.sh script: - tox python-canonicaljson-1.4.0/.travis/000077500000000000000000000000001372421235700172505ustar00rootroot00000000000000python-canonicaljson-1.4.0/.travis/install.sh000077500000000000000000000010101372421235700212450ustar00rootroot00000000000000#!/bin/bash set -xe if [[ $TRAVIS_OS_NAME == 'osx' ]]; then # osx build uses a 'generic' language which doesn't come with pip case "${TOXENV}" in py38) # for py38, use homebrew python, which comes with pip. # see also https://docs.brew.sh/Homebrew-and-Python brew upgrade python pip3 install tox ;; *) echo "TOXENV ${TOXENV} not supported on osx" >&2 exit 1 ;; esac else pip install tox fi python-canonicaljson-1.4.0/CHANGES.md000066400000000000000000000033671372421235700172650ustar00rootroot00000000000000Version 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-1.4.0/LICENSE000066400000000000000000000236761372421235700167050ustar00rootroot00000000000000 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-1.4.0/MANIFEST.in000066400000000000000000000001421372421235700174150ustar00rootroot00000000000000include *.in include *.py include *.md include LICENSE include tox.ini prune .travis prune debian python-canonicaljson-1.4.0/README.rst000066400000000000000000000031541372421235700173540ustar00rootroot00000000000000Canonical JSON ============== .. image:: https://img.shields.io/pypi/v/canonicaljson.svg :target: https://pypi.python.org/pypi/canonicaljson/ :alt: Latest Version .. image:: https://img.shields.io/travis/matrix-org/python-canonicaljson.svg :target: https://travis-ci.org/matrix-org/python-canonicaljson 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 encode ``frozendict`` immutable dictionaries. Supports Python versions 3.5 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/ python-canonicaljson-1.4.0/canonicaljson.py000066400000000000000000000074421372421235700210640ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright 2014 OpenMarket Ltd # Copyright 2018 New Vector Ltd # # 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 platform from frozendict import frozendict __version__ = "1.4.0" def _default(obj): if type(obj) is frozendict: # fishing the protected dict out of the object is a bit nasty, # but we don't really want the overhead of copying the dict. return obj._dict raise TypeError( "Object of type %s is not JSON serializable" % obj.__class__.__name__ ) # Declare these in the module scope, but they get configured in # set_json_library. _canonical_encoder = None _pretty_encoder = None def set_json_library(json_lib): """ Set the underlying JSON library that canonicaljson uses to json_lib. Params: json_lib: The module to use for JSON encoding. Must have a `JSONEncoder` property. """ global _canonical_encoder _canonical_encoder = json_lib.JSONEncoder( ensure_ascii=False, allow_nan=False, separators=(",", ":"), sort_keys=True, default=_default, ) global _pretty_encoder _pretty_encoder = json_lib.JSONEncoder( ensure_ascii=False, allow_nan=False, indent=4, sort_keys=True, default=_default, ) def encode_canonical_json(json_object): """Encodes the shortest UTF-8 JSON encoding with dictionary keys lexicographically sorted by unicode code point. Args: json_object (dict): The JSON object to encode. Returns: bytes encoding the JSON object""" s = _canonical_encoder.encode(json_object) return s.encode("utf-8") def iterencode_canonical_json(json_object): """Encodes the shortest UTF-8 JSON encoding with dictionary keys lexicographically sorted by unicode code point. Args: json_object (dict): The JSON object to encode. Returns: generator which yields bytes encoding the JSON object""" for chunk in _canonical_encoder.iterencode(json_object): yield chunk.encode("utf-8") def encode_pretty_printed_json(json_object): """ Encodes the JSON object dict as human readable UTF-8 bytes. Args: json_object (dict): The JSON object to encode. Returns: bytes encoding the JSON object""" return _pretty_encoder.encode(json_object).encode("utf-8") def iterencode_pretty_printed_json(json_object): """Encodes the JSON object dict as human readable UTF-8 bytes. Args: json_object (dict): The JSON object to encode. Returns: generator which yields bytes encoding the JSON object""" for chunk in _pretty_encoder.iterencode(json_object): yield chunk.encode("utf-8") if platform.python_implementation() == "PyPy": # pragma: no cover # pypy ships with an optimised JSON encoder/decoder that is faster than # simplejson's C extension. import json else: # pragma: no cover # using simplejson rather than regular json on CPython for backwards # compatibility (simplejson on Python 3.5 handles parsing of bytes while # the standard library json does not). # # Note that it seems performance is on par or better using json from the # standard library as of Python 3.7. import simplejson as json # Set the JSON library to the backwards compatible version. set_json_library(json) python-canonicaljson-1.4.0/debian/000077500000000000000000000000001372421235700171045ustar00rootroot00000000000000python-canonicaljson-1.4.0/debian/changelog000066400000000000000000000027001372421235700207550ustar00rootroot00000000000000python-canonicaljson (1.1.4) stable; urgency=medium * Fix error when encoding non-BMP characters on UCS-2 python builds (fixes issue #12). -- Richard van der Hoff Wed, 23 May 2018 09:07:26 +0100 python-canonicaljson (1.1.3) stable; urgency=medium * Bump depencency on frozendict to >=1.0, to fix conflicts with older versions. -- Richard van der Hoff Fri, 13 Apr 2018 09:51:24 +0100 python-canonicaljson (1.1.2) stable; urgency=medium * Fix escaping of control characters U+0000 to U+001F AGAIN, which was STILL broken in the previous release -- Richard van der Hoff Thu, 12 Apr 2018 15:53:56 +0100 python-canonicaljson (1.1.1) stable; urgency=medium * Fix escaping of control characters U+0000 to U+001F, which was broken in the previous release -- Richard van der Hoff Wed, 11 Apr 2018 18:01:50 +0100 python-canonicaljson (1.1.0) stable; urgency=medium * Significant performance improvements (https://github.com/matrix-org/python-canonicaljson/pull/7, https://github.com/matrix-org/python-canonicaljson/pull/8, https://github.com/matrix-org/python-canonicaljson/pull/9) -- Richard van der Hoff Tue, 10 Apr 2018 16:42:19 +0100 canonicaljson (1.0.0-1) wheezy; urgency=low * source package automatically created by stdeb 0.6.0+git -- Erik Johnston Fri, 13 Nov 2015 14:47:18 +0000 python-canonicaljson-1.4.0/debian/clean000066400000000000000000000000151372421235700201050ustar00rootroot00000000000000*.egg-info/* python-canonicaljson-1.4.0/debian/compat000066400000000000000000000000021372421235700203020ustar00rootroot000000000000009 python-canonicaljson-1.4.0/debian/control000066400000000000000000000035771372421235700205230ustar00rootroot00000000000000Source: python-canonicaljson Maintainer: Richard van der Hoff Section: python Priority: optional Build-Depends: debhelper (>= 9), dh-python, python-all (>= 2.6.6-3), python-setuptools (>= 0.6.24), python3-all, python3-setuptools (>= 0.6.24), python-frozendict (>= 0.4), python-simplejson (>= 3.6.5), python3-frozendict (>= 0.4), python3-simplejson (>= 3.6.5) Standards-Version: 3.9.7 X-Python-Version: >= 2.7 Package: python-canonicaljson Architecture: all Depends: python-frozendict (>= 0.4), python-simplejson (>= 3.6.5), ${misc:Depends}, ${python:Depends} Provides: ${python:Provides} Description: canonical JSON implementation for Python 2 Canonical JSON implementation for Python 2. . * Encodes objects and arrays as RFC 7159 JSON. * Sorts object keys so that you get the same result each time. * Has no inignificant 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 encode frozendict immutable dictionaries. Package: python3-canonicaljson Architecture: all Depends: python3-frozendict (>= 0.4), python3-simplejson (>= 3.6.5), ${misc:Depends}, ${python3:Depends} Description: canonical JSON implementation for Python 3 Canonical JSON implementation for Python 3. . * Encodes objects and arrays as RFC 7159 JSON. * Sorts object keys so that you get the same result each time. * Has no inignificant 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 encode frozendict immutable dictionaries. python-canonicaljson-1.4.0/debian/copyright000066400000000000000000000020471372421235700210420ustar00rootroot00000000000000Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Contact: Richard van der Hoff Files: * Copyright: 2014-2015 OpenMarket Ltd 2018 New Vector Ltd License: Apache-2.0 Files: debian/* Copyright: 2014-2015 OpenMarket Ltd 2017 Andrew Shadura 2018 New Vector Ltd License: Apache-2.0 License: Apache-2.0 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. . On Debian systems, the complete text of the Apache License, version 2.0 can be found in ‘/usr/share/common-licenses/Apache-2.0’. python-canonicaljson-1.4.0/debian/python-canonicaljson.docs000066400000000000000000000000131372421235700241100ustar00rootroot00000000000000README.rst python-canonicaljson-1.4.0/debian/python3-canonicaljson.docs000066400000000000000000000000131372421235700241730ustar00rootroot00000000000000README.rst python-canonicaljson-1.4.0/debian/rules000077500000000000000000000001561372421235700201660ustar00rootroot00000000000000#!/usr/bin/make -f export PYBUILD_NAME=canonicaljson %: dh $@ --with python2,python3 --buildsystem=pybuild python-canonicaljson-1.4.0/debian/source/000077500000000000000000000000001372421235700204045ustar00rootroot00000000000000python-canonicaljson-1.4.0/debian/source/format000066400000000000000000000000151372421235700216130ustar00rootroot000000000000003.0 (native) python-canonicaljson-1.4.0/debian/source/options000066400000000000000000000000371372421235700220220ustar00rootroot00000000000000extend-diff-ignore="\.egg-info"python-canonicaljson-1.4.0/releasing.md000066400000000000000000000022021372421235700201510ustar00rootroot00000000000000Releasing python-canonicaljson ============================== * bump version in `canonicaljson.py` * update changelog * update debian changelog: * Add new entry: `dch -v ` * Mark as released: `dch --distribution stable -r` * Build and upload to pypi: * `rm -r dist` * `python setup.py sdist bdist_wheel` * `twine upload -s dist/*` * `git tag -s v` * `git push` * `git push --tags` * Follow instructions below to release debian packaging. Prerequisites for debian packaging ---------------------------------- ``` sudo apt-get install sbuild sudo apt-get install ubuntu-dev-tools # for mk-sbuild sudo sbuild-adduser $LOGNAME newgrp sbuild mk-sbuild stretch ``` If your kernel doesn't support `aufs`, you'll need to set `union-type=overlay` in `/etc/schroot/chroot.d/sbuild-stretch-amd64`. Debian release -------------- ``` # We need to build from a pristine copy of the repo (otherwise you end up with # your whole working copy in the source tarball), so: git clone git@github.com:matrix-org/python-canonicaljson.git -b v python-canonicaljson-clean cd python-canonicaljson-clean sbuild -s --arch-all -d stretch debsign ``` python-canonicaljson-1.4.0/setup.cfg000066400000000000000000000002761372421235700175100ustar00rootroot00000000000000[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-1.4.0/setup.py000077500000000000000000000043721372421235700174050ustar00rootroot00000000000000#!/usr/bin/env python # Copyright 2015 OpenMarket Ltd # Copyright 2018 New Vector Ltd # # 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 setuptools import setup from codecs import open import os here = os.path.abspath(os.path.dirname(__file__)) def read_file(path_segments): """Read a UTF-8 file from the package. Takes a list of strings to join to make the path""" file_path = os.path.join(here, *path_segments) with open(file_path, encoding="utf-8") as f: return f.read() def exec_file(path_segments, name): """Extract a constant from a python file by looking for a line defining the constant and executing it.""" result = {} code = read_file(path_segments) lines = [line for line in code.split("\n") if line.startswith(name)] exec("\n".join(lines), result) return result[name] setup( name="canonicaljson", version=exec_file(("canonicaljson.py",), "__version__"), py_modules=["canonicaljson"], description="Canonical JSON", install_requires=[ # simplerjson versions before 3.14.0 had a bug with some characters # (e.g. \u2028) if ensure_ascii was set to false. "simplejson>=3.14.0", "frozendict>=1.0", ], zip_safe=True, long_description=read_file(("README.rst",)), keywords="json", author="The Matrix.org Team", author_email="team@matrix.org", url="https://github.com/matrix-org/python-canonicaljson", license="Apache License, Version 2.0", python_requires="~=3.5", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", ], ) python-canonicaljson-1.4.0/test_canonicaljson.py000066400000000000000000000123521372421235700221170ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Copyright 2015 OpenMarket Ltd # Copyright 2018 New Vector Ltd # # 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 math import inf, nan from canonicaljson import ( encode_canonical_json, encode_pretty_printed_json, iterencode_canonical_json, iterencode_pretty_printed_json, set_json_library, ) from frozendict import frozendict import unittest from unittest import mock class TestCanonicalJson(unittest.TestCase): def test_encode_canonical(self): 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): """ 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: c = chr(c) self.assertEqual(encode_canonical_json(c), b'"' + c.encode("ascii") + b'"') def test_encode_pretty_printed(self): 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_frozen_dict(self): self.assertEqual( encode_canonical_json(frozendict({"a": 1})), b'{"a":1}', ) self.assertEqual( encode_pretty_printed_json(frozendict({"a": 1})), b'{\n "a": 1\n}' ) def test_unknown_type(self): 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): """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_set_json(self): """Ensure that changing the underlying JSON implementation works.""" mock_json = mock.Mock(spec=["JSONEncoder"]) mock_json.JSONEncoder.return_value.encode.return_value = "sentinel" try: set_json_library(mock_json) self.assertEqual(encode_canonical_json({}), b"sentinel") finally: # Reset the JSON library to whatever was originally set. from canonicaljson import json set_json_library(json) python-canonicaljson-1.4.0/tox.ini000066400000000000000000000007061372421235700172000ustar00rootroot00000000000000[tox] envlist = packaging, pep8, py35, py36, py37, py38, pypy3 [testenv] deps = coverage nose commands = coverage run --source canonicaljson -m nose coverage report -m --fail-under 100 [testenv:packaging] deps = check-manifest commands = check-manifest [testenv:pep8] basepython = python3.6 deps = flake8 commands = flake8 . [testenv:black] basepython = python3.6 deps = black commands = python -m black --check --diff .