Skip to content

Commit a3bee37

Browse files
committed
chore: reformat code with black
1 parent dd26891 commit a3bee37

File tree

6 files changed

+127
-35
lines changed

6 files changed

+127
-35
lines changed

kw/json/__init__.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,19 @@
22

33
from ._compat import _load as load
44
from ._compat import _loads as loads
5-
from .encode import KiwiJSONEncoder, MaskedJSONEncoder, default_encoder, dump, dumps, raw_encoder
5+
from .encode import (
6+
KiwiJSONEncoder,
7+
MaskedJSONEncoder,
8+
default_encoder,
9+
dump,
10+
dumps,
11+
raw_encoder,
12+
)
613
from .flask import JSONExtension
7-
from .utils import DEFAULT_BLACKLIST, DEFAULT_PLACEHOLDER, DEFAULT_WHITELIST, mask_dict, mask_dict_factory
14+
from .utils import (
15+
DEFAULT_BLACKLIST,
16+
DEFAULT_PLACEHOLDER,
17+
DEFAULT_WHITELIST,
18+
mask_dict,
19+
mask_dict_factory,
20+
)

kw/json/_compat.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
enum = None
99

1010
try:
11-
from simplejson.encoder import JSONEncoder as BaseJSONEncoder # pylint: disable=W0611
11+
from simplejson.encoder import ( # pylint: disable=W0611
12+
JSONEncoder as BaseJSONEncoder,
13+
)
1214
from simplejson import dumps as json_dumps # pylint: disable=W0611
1315
from simplejson import dump as json_dump # pylint: disable=W0611
1416
from simplejson import loads as json_loads # pylint: disable=W0611
@@ -51,7 +53,10 @@ def wrapper(*args, **kwargs):
5153
try:
5254
result = func(*args, **kwargs)
5355
except TypeError as err:
54-
if str(err) == "__init__() got an unexpected keyword argument 'use_decimal'":
56+
if (
57+
str(err)
58+
== "__init__() got an unexpected keyword argument 'use_decimal'"
59+
):
5560
raise KiwiJsonError(__use_decimal_error_message)
5661
raise
5762
return result

kw/json/encode.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99

1010

1111
def _fail(obj, *args, **kwargs):
12-
raise TypeError("Object of type {} is not JSON serializable".format(obj.__class__.__name__))
12+
raise TypeError(
13+
"Object of type {} is not JSON serializable".format(obj.__class__.__name__)
14+
)
1315

1416

1517
try:
@@ -23,7 +25,9 @@ def _fail(obj, *args, **kwargs):
2325
dc_asdict = _fail
2426

2527

26-
def default_encoder(obj, dict_factory=dict, date_as_unix_time=False): # Ignore RadonBear
28+
def default_encoder(
29+
obj, dict_factory=dict, date_as_unix_time=False
30+
): # Ignore RadonBear
2731
if hasattr(obj, "isoformat"): # date, datetime, arrow
2832
if date_as_unix_time:
2933
if obj.__class__.__name__ == "Arrow":
@@ -41,7 +45,10 @@ def default_encoder(obj, dict_factory=dict, date_as_unix_time=False): # Ignore
4145
return obj.name
4246

4347
# Second option is for `iteritems()` on Python 2
44-
if isinstance(obj, ItemsView) or obj.__class__.__name__ == "dictionary-itemiterator":
48+
if (
49+
isinstance(obj, ItemsView)
50+
or obj.__class__.__name__ == "dictionary-itemiterator"
51+
):
4552
return dict_factory(obj)
4653

4754
if hasattr(obj, "asdict"): # dictablemodel
@@ -68,7 +75,9 @@ def default_encoder(obj, dict_factory=dict, date_as_unix_time=False): # Ignore
6875
def raw_encoder(obj, date_as_unix_time=False):
6976
"""Return representation of values that are not encodable instead of encoding them."""
7077
try:
71-
return default_encoder(obj, dict_factory=mask_dict, date_as_unix_time=date_as_unix_time)
78+
return default_encoder(
79+
obj, dict_factory=mask_dict, date_as_unix_time=date_as_unix_time
80+
)
7281
except TypeError:
7382
return repr(obj)
7483

@@ -95,7 +104,9 @@ def modify_kwargs(kwargs):
95104
kwargs.setdefault("use_decimal", False)
96105
if "default" not in kwargs:
97106
date_as_unix_time = kwargs.pop("date_as_unix_time", False)
98-
kwargs["default"] = partial(default_encoder, date_as_unix_time=date_as_unix_time)
107+
kwargs["default"] = partial(
108+
default_encoder, date_as_unix_time=date_as_unix_time
109+
)
99110

100111

101112
def format_value(value, precision):
@@ -104,7 +115,10 @@ def format_value(value, precision):
104115
return round(value, precision)
105116
if isinstance(value, (list, set)):
106117
return traverse_iterable(value, precision)
107-
if isinstance(value, ItemsView) or value.__class__.__name__ == "dictionary-itemiterator":
118+
if (
119+
isinstance(value, ItemsView)
120+
or value.__class__.__name__ == "dictionary-itemiterator"
121+
):
108122
return traverse_dict(dict(value), precision)
109123
if isinstance(value, dict):
110124
return traverse_dict(value, precision)

kw/json/utils.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55

66
def mask_dict_factory(
7-
placeholder=DEFAULT_PLACEHOLDER, blacklist=DEFAULT_BLACKLIST, whitelist=DEFAULT_WHITELIST,
7+
placeholder=DEFAULT_PLACEHOLDER,
8+
blacklist=DEFAULT_BLACKLIST,
9+
whitelist=DEFAULT_WHITELIST,
810
):
911
def mask_dict(pairs):
1012
"""Return a dict with dangerous looking key/value pairs masked."""
@@ -19,7 +21,8 @@ def mask_dict(pairs):
1921
return {
2022
key: (
2123
placeholder
22-
if key.lower() not in whitelist and any(word in key.lower() for word in blacklist)
24+
if key.lower() not in whitelist
25+
and any(word in key.lower() for word in blacklist)
2326
else value
2427
)
2528
for key, value in items

test/test_decoder.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@
1111
simplejson_loads = None
1212

1313

14-
@pytest.mark.skipif(simplejson_loads is None, reason="Decimal encoding with simplejson only")
14+
@pytest.mark.skipif(
15+
simplejson_loads is None, reason="Decimal encoding with simplejson only"
16+
)
1517
@pytest.mark.parametrize(
1618
"value, expected",
1719
[

test/test_encoder.py

Lines changed: 77 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,14 @@
1818
from sqlalchemy.ext.declarative import declarative_base
1919
from sqlalchemy.orm import sessionmaker
2020

21-
from kw.json import KiwiJSONEncoder, MaskedJSONEncoder, default_encoder, dump, dumps, raw_encoder
21+
from kw.json import (
22+
KiwiJSONEncoder,
23+
MaskedJSONEncoder,
24+
default_encoder,
25+
dump,
26+
dumps,
27+
raw_encoder,
28+
)
2229
from kw.json._compat import DataclassItem, enum
2330
from kw.json.exceptions import KiwiJsonError
2431

@@ -100,10 +107,16 @@ def test_default_encoder(value, expected, date_as_unix_time):
100107
assert default_encoder(value, date_as_unix_time=date_as_unix_time) == expected
101108

102109

103-
@pytest.mark.skipif(simplejson_dumps is None, reason="Decimal encoding with simplejson only")
110+
@pytest.mark.skipif(
111+
simplejson_dumps is None, reason="Decimal encoding with simplejson only"
112+
)
104113
@pytest.mark.parametrize(
105114
"value, expected",
106-
((Decimal("1"), "1"), (Decimal("-1"), "-1"), (Decimal("0.123456789123456789"), "0.123456789123456789"),),
115+
(
116+
(Decimal("1"), "1"),
117+
(Decimal("-1"), "-1"),
118+
(Decimal("0.123456789123456789"), "0.123456789123456789"),
119+
),
107120
)
108121
def test_simplejson_encoder_with_decimal(value, expected):
109122
assert dumps(value, use_decimal=True) == expected
@@ -127,7 +140,11 @@ def test_default_encoder_defaults():
127140
(Decimal("1"), '"1"', False),
128141
(UUID, '"{}"'.format(str(UUID)), False),
129142
(datetime.datetime(2018, 1, 1), '"2018-01-01T00:00:00"', False),
130-
(datetime.datetime(2018, 1, 1, tzinfo=UTC), '"2018-01-01T00:00:00+00:00"', False,),
143+
(
144+
datetime.datetime(2018, 1, 1, tzinfo=UTC),
145+
'"2018-01-01T00:00:00+00:00"',
146+
False,
147+
),
131148
(arrow.get("2018-01-01"), '"2018-01-01T00:00:00+00:00"', False),
132149
(datetime.date(2018, 1, 1), '"2018-01-01"', False),
133150
(datetime.datetime(2018, 1, 1), "1514764800", True),
@@ -149,15 +166,22 @@ def test_dumps(value, expected, date_as_unix_time):
149166
(({1: 1.333}, {1: 1.333}), '{"1": 1.33}', 2),
150167
(([1.333, 2.333], [1.333, 2.333]), "[1.33, 2.33]", 2),
151168
(([1.333, {1: 1.333}], [1.333, {1: 1.333}]), '[1.33, {"1": 1.33}]', 2),
152-
(([1.333, {1: 1.333}, {1.333}], [1.333, {1: 1.333}, {1.333}]), '[1.33, {"1": 1.33}, [1.33]]', 2),
169+
(
170+
([1.333, {1: 1.333}, {1.333}], [1.333, {1: 1.333}, {1.333}]),
171+
'[1.33, {"1": 1.33}, [1.33]]',
172+
2,
173+
),
153174
((items_view_float, items_view_float), '{"foo": 1.33}', 2),
154175
((items_view_complex, items_view_complex), '{"1": 1.33, "2": {"2": 0.33}}', 2),
155176
((HTML(), None), '"foo"', 2),
156177
(([set()], [set()]), "[[]]", 2),
157178
(((1.3333, 2.3333), (1.3333, 2.3333)), "[1.33, 2.33]", 2),
158179
((({1: 1.33333}, 1.33333), ({1: 1.33333}, 1.33333)), '[{"1": 1.33}, 1.33]', 2),
159180
(
160-
([{1: 1.222, 2: [1.333, {1: 1.333}, {3: {3.333}}]}], [{1: 1.222, 2: [1.333, {1: 1.333}, {3: {3.333}}]}]),
181+
(
182+
[{1: 1.222, 2: [1.333, {1: 1.333}, {3: {3.333}}]}],
183+
[{1: 1.222, 2: [1.333, {1: 1.333}, {3: {3.333}}]}],
184+
),
161185
'[{"1": 1.22, "2": [1.33, {"1": 1.33}, {"3": [3.33]}]}]',
162186
2,
163187
),
@@ -174,10 +198,17 @@ def test_rounding(values, expected, precision):
174198
@pytest.mark.parametrize(
175199
"values, expected, precision",
176200
(
177-
((test_namedtuple, test_namedtuple), {"as_object": '{"a": 1.33, "b": 2.33}', "as_list": "[1.33, 2.33]"}, 2),
201+
(
202+
(test_namedtuple, test_namedtuple),
203+
{"as_object": '{"a": 1.33, "b": 2.33}', "as_list": "[1.33, 2.33]"},
204+
2,
205+
),
178206
(
179207
(test_namedtuple_complex, test_namedtuple_complex),
180-
{"as_object": '{"a": 1.33, "b": {"a": 1.33, "b": {"1": 1.33}}}', "as_list": '[1.33, [1.33, {"1": 1.33}]]',},
208+
{
209+
"as_object": '{"a": 1.33, "b": {"a": 1.33, "b": {"1": 1.33}}}',
210+
"as_list": '[1.33, [1.33, {"1": 1.33}]]',
211+
},
181212
2,
182213
),
183214
),
@@ -187,7 +218,10 @@ def test_rounding_tuples(values, expected, precision):
187218
if simplejson_dumps:
188219
# simplejson supports `namedtuple_as_object` param unlike json
189220
assert dumps(before, precision=precision) == expected["as_object"]
190-
assert dumps(before, precision=precision, namedtuple_as_object=False) == expected["as_list"]
221+
assert (
222+
dumps(before, precision=precision, namedtuple_as_object=False)
223+
== expected["as_list"]
224+
)
191225
else:
192226
assert dumps(before, precision=precision) == expected["as_list"]
193227
assert before == after
@@ -204,9 +238,9 @@ def __repr__(self):
204238
return "<Foo>"
205239

206240
# by default `raw_encoder` encodes dates as ISO
207-
assert dumps({"foo": Foo(), "bar": datetime.date(2018, 1, 1)}, default=raw_encoder) == dumps(
208-
{"foo": "<Foo>", "bar": "2018-01-01"}
209-
)
241+
assert dumps(
242+
{"foo": Foo(), "bar": datetime.date(2018, 1, 1)}, default=raw_encoder
243+
) == dumps({"foo": "<Foo>", "bar": "2018-01-01"})
210244

211245

212246
def test_dump_with_default():
@@ -275,7 +309,9 @@ def test_unknown_raises():
275309
class Foo(object):
276310
bar = True # pylint: disable=C0102
277311

278-
with pytest.raises(TypeError, match="^Object of type Foo is not JSON serializable$"):
312+
with pytest.raises(
313+
TypeError, match="^Object of type Foo is not JSON serializable$"
314+
):
279315
default_encoder(Foo())
280316

281317

@@ -305,23 +341,32 @@ def test_masked_json_encoders(value, expected):
305341
(partial(json_dumps, cls=MaskedJSONEncoder), '{"attrib": 1}'),
306342
),
307343
)
308-
@pytest.mark.skipif(DataclassItem is None, reason="Dataclasses are available only on Python 3.7+")
344+
@pytest.mark.skipif(
345+
DataclassItem is None, reason="Dataclasses are available only on Python 3.7+"
346+
)
309347
def test_dataclasses(dumper, expected):
310348
assert dumper(DataclassItem(attrib=1)) == expected # pylint: disable=not-callable
311349

312350

313351
@pytest.mark.parametrize(
314352
"dumper, expected",
315-
((default_encoder, {"attrib": 1}), (partial(json_dumps, default=default_encoder), '{"attrib": 1}'),),
353+
(
354+
(default_encoder, {"attrib": 1}),
355+
(partial(json_dumps, default=default_encoder), '{"attrib": 1}'),
356+
),
316357
)
317358
def test_attrs(dumper, expected):
318359
assert dumper(AttrsItem(attrib=1)) == expected
319360

320361

321-
@pytest.mark.skipif(sys.version_info[:2] >= (3, 7), reason="Dataclasses should not be available")
362+
@pytest.mark.skipif(
363+
sys.version_info[:2] >= (3, 7), reason="Dataclasses should not be available"
364+
)
322365
def test_missing_dependency():
323366
"""If we have a class that have the same attributes as attrs provide."""
324-
with pytest.raises(TypeError, match="Object of type NotDataclassesItem is not JSON serializable"):
367+
with pytest.raises(
368+
TypeError, match="Object of type NotDataclassesItem is not JSON serializable"
369+
):
325370
default_encoder(NotDataclassesItem())
326371

327372

@@ -354,22 +399,32 @@ def test_sqlalchemy_cursor_row(alchemy_session):
354399
assert_json(data, [{"id": 1, "name": "test"}])
355400

356401

357-
@pytest.mark.skipif(sys.version_info[0] == 2, reason="That trick doesn't work on Python 2")
402+
@pytest.mark.skipif(
403+
sys.version_info[0] == 2, reason="That trick doesn't work on Python 2"
404+
)
358405
def test_no_attrs():
359406
# Need to re-import
360407
del sys.modules["kw.json"]
361408
del sys.modules["kw.json.encode"]
362409
sys.modules["attr"] = None
363-
from kw.json import default_encoder # pylint: disable=reimported,import-outside-toplevel
410+
from kw.json import ( # pylint: disable=reimported,import-outside-toplevel
411+
default_encoder,
412+
)
364413

365-
with pytest.raises(TypeError, match="Object of type NotAttrsItem is not JSON serializable"):
414+
with pytest.raises(
415+
TypeError, match="Object of type NotAttrsItem is not JSON serializable"
416+
):
366417
default_encoder(NotAttrsItem())
367418

368419

369-
@pytest.mark.skipif(get_asyncpg_record is None, reason="Asyncpg is available only on Python 3.5+.")
420+
@pytest.mark.skipif(
421+
get_asyncpg_record is None, reason="Asyncpg is available only on Python 3.5+."
422+
)
370423
def test_asyncpg():
371424
import asyncio # pylint: disable=import-outside-toplevel
372425

373426
loop = asyncio.get_event_loop()
374-
result = loop.run_until_complete(get_asyncpg_record(os.getenv("DATABASE_URI"))) # pylint: disable=not-callable
427+
result = loop.run_until_complete(
428+
get_asyncpg_record(os.getenv("DATABASE_URI")) # pylint: disable=not-callable
429+
)
375430
assert json_dumps(result, default=default_encoder) == '[{"value": 1}]'

0 commit comments

Comments
 (0)