-
Notifications
You must be signed in to change notification settings - Fork 15
Add an 'extra' optional, orjson to experiment with rust speedups
#64
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
realtyem
wants to merge
10
commits into
matrix-org:main
Choose a base branch
from
realtyem:jason/orjson
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
93e4f29
testing: the preserialization callback stuff is not used with orjson.…
realtyem a532ae5
testing: add a test for 'inf' variants and 'nan' nested inside the js…
realtyem f8528e4
setup: add the extra for 'orjson'
realtyem 46df0b0
chore: hookup orjson to provide the encoding
realtyem 68733a4
testing: orjson's pretty print indentation is hard coded to a value o…
realtyem 2a5bd8c
fix: enforce that 'inf' variants and 'nan' are not allowed when using…
realtyem 64c3c5b
testing: adjust the mypy test run to include the typing for orjson
realtyem b27f2c7
testing: try and work up a matrix to test both with and without the n…
realtyem 7b61d0d
fix: remove python version 3.7 support(and add in newer versions)
realtyem f26d970
fix: use _preprocess_for_serialisation() for orjson too, this solves …
realtyem File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,8 +15,11 @@ | |
| # limitations under the License. | ||
| import unittest | ||
| from math import inf, nan | ||
| from typing import Any, Union | ||
| from unittest.mock import Mock | ||
|
|
||
| from immutabledict import immutabledict | ||
|
|
||
| from canonicaljson import ( | ||
| encode_canonical_json, | ||
| encode_pretty_printed_json, | ||
|
|
@@ -25,6 +28,12 @@ | |
| register_preserialisation_callback, | ||
| ) | ||
|
|
||
| try: | ||
| import orjson | ||
|
|
||
| except ImportError: | ||
| orjson = None # type: ignore [assignment] | ||
|
|
||
|
|
||
| class TestCanonicalJson(unittest.TestCase): | ||
| def test_encode_canonical(self) -> None: | ||
|
|
@@ -98,10 +107,16 @@ def test_encode_pretty_printed(self) -> None: | |
| self.assertEqual(encode_pretty_printed_json({}), b"{}") | ||
| self.assertEqual(list(iterencode_pretty_printed_json({})), [b"{}"]) | ||
|
|
||
| if orjson is not None: | ||
| # orjson's pretty print style is a flag option and is hardcoded to "2", | ||
| # so this will be slightly different. | ||
| comparison = b'{\n "la merde amus\xc3\xa9e": "\xF0\x9F\x92\xA9"\n}' | ||
| else: | ||
| comparison = b'{\n "la merde amus\xc3\xa9e": "\xF0\x9F\x92\xA9"\n}' | ||
| # non-ascii should come out utf8-encoded. | ||
| self.assertEqual( | ||
| encode_pretty_printed_json({"la merde amusée": "💩"}), | ||
| b'{\n "la merde amus\xc3\xa9e": "\xF0\x9F\x92\xA9"\n}', | ||
| comparison, | ||
| ) | ||
|
|
||
| def test_unknown_type(self) -> None: | ||
|
|
@@ -136,6 +151,68 @@ def test_invalid_float_values(self) -> None: | |
| with self.assertRaises(ValueError): | ||
| encode_pretty_printed_json(nan) | ||
|
|
||
| def test_invalid_nested_float_values(self) -> None: | ||
| """Infinity/-Infinity/NaN are not allowed in canonicaljson.""" | ||
| data_with_inf = {"a": 1, "b": float("inf")} | ||
| data_with_neg_inf = {"a": 1, "b": -float("inf")} | ||
| data_with_nan = {"a": 1, "b": float("nan")} | ||
| list_with_inf = {"a": [1, float("inf")]} | ||
| list_with_neg_inf = {"a": [1, -float("inf")]} | ||
| list_with_nan = {"a": [1, float("nan")]} | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_canonical_json(data_with_inf) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_pretty_printed_json(data_with_inf) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_canonical_json(data_with_neg_inf) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_pretty_printed_json(data_with_neg_inf) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_canonical_json(data_with_nan) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_pretty_printed_json(data_with_nan) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_canonical_json(list_with_inf) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_pretty_printed_json(list_with_inf) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_canonical_json(list_with_neg_inf) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_pretty_printed_json(list_with_neg_inf) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_canonical_json(list_with_nan) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| encode_pretty_printed_json(list_with_nan) | ||
|
Comment on lines
+156
to
+197
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This would be more readable if the test cases were looped over, i.e.: test_cases = {
"data_with_inf": {"a": 1, "b": float("inf")},
...
}
for name, test_case in test_cases.items():
with self.assertRaises(ValueError, f"Passing test case '{name}' to encode_canonical_json failed to raise a ValueError"):
encode_canonical_json(test_case)
with self.assertRaises(ValueError, f"Passing test case '{name}' to encode_pretty_printed_json failed to raise a ValueError"):
encode_pretty_printed_json(test_case)
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh, I like that. Yes, will do 🫡 |
||
|
|
||
| def test_immutable_dict_handling(self) -> None: | ||
| im_d: immutabledict[str, Union[str, int]] = immutabledict( | ||
| {"key1": "value1", "key2": 42} | ||
| ) | ||
|
|
||
| # Lifted from Synapse's __init__.py | ||
| def _immutabledict_cb(d: immutabledict[str, Any]) -> Any: | ||
| try: | ||
| return d._dict | ||
| except Exception: | ||
| # Paranoia: fall back to a `dict()` call, in case a future version of | ||
| # immutabledict removes `_dict` from the implementation. | ||
| return dict(d) | ||
|
|
||
| register_preserialisation_callback(immutabledict, _immutabledict_cb) | ||
| encode_canonical_json(im_d) | ||
|
|
||
| def test_encode_unknown_class_raises(self) -> None: | ||
| class C: | ||
| pass | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It might be worth proposing an
OPT_INDENT_4to upstream?It's not ideal that we'll be changing the output of
encode_pretty_printed_json(in case it breaks downstream test cases), but it's possible with a version bump/note in the changelog.