Skip to content

Commit fd894f7

Browse files
committed
Adds a custom encoder to serialize resources
1 parent 87dbc33 commit fd894f7

3 files changed

Lines changed: 50 additions & 1 deletion

File tree

src/userlist/client.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import json
22
import requests
3+
from .encoder import Encoder
34

45

56
class Client:
@@ -21,7 +22,11 @@ def _request(self, method, endpoint, payload=None):
2122
response = self.session.request(
2223
method,
2324
url,
24-
**({"data": json.dumps(payload)} if payload is not None else {}),
25+
**(
26+
{"data": json.dumps(payload, cls=Encoder)}
27+
if payload is not None
28+
else {}
29+
),
2530
timeout=self.timeout,
2631
)
2732
response.raise_for_status()

src/userlist/encoder.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from json import JSONEncoder
2+
from .resource import Resource
3+
4+
5+
class Encoder(JSONEncoder):
6+
def default(self, obj):
7+
if isinstance(obj, Resource):
8+
return obj.to_dict()
9+
10+
return super().default(obj)

tests/test_encoder.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import json
2+
import pytest
3+
from userlist.encoder import Encoder
4+
from userlist.resource import Resource
5+
6+
7+
def test_encoder_with_resource():
8+
class TestResource(Resource):
9+
pass
10+
11+
test_data = {"name": "test", "value": 123}
12+
resource = TestResource(test_data)
13+
encoded = json.dumps(resource, cls=Encoder)
14+
assert json.loads(encoded) == test_data
15+
16+
17+
def test_encoder_with_regular_types():
18+
test_data = {
19+
"string": "test",
20+
"number": 123,
21+
"boolean": True,
22+
"list": [1, 2, 3],
23+
"dict": {"key": "value"},
24+
}
25+
encoded = json.dumps(test_data, cls=Encoder)
26+
assert json.loads(encoded) == test_data
27+
28+
29+
def test_encoder_with_unsupported_type():
30+
class UnsupportedType:
31+
pass
32+
33+
with pytest.raises(TypeError):
34+
json.dumps(UnsupportedType(), cls=Encoder)

0 commit comments

Comments
 (0)