8000 Added test for custom object serializer. Loggers are unique for each … · madzak/python-json-logger@83b847a · GitHub
[go: up one dir, main page]

Skip to content
This repository was archived by the owner on Dec 21, 2024. It is now read-only.

Commit 83b847a

Browse files
committed
Added test for custom object serializer. Loggers are unique for each test
1 parent 41a763d commit 83b847a

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

tests/tests.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import json
55
import sys
66
import traceback
7+
import random
78

89
try:
910
import xmlrunner
@@ -23,7 +24,7 @@
2324

2425
class TestJsonLogger(unittest.TestCase):
2526
def setUp(self):
26-
self.logger = logging.getLogger('logging-test')
27+
self.logger = logging.getLogger("logging-test-{}".format(random.randint(1, 101)))
2728
self.logger.setLevel(logging.DEBUG)
2829
self.buffer = StringIO()
2930

@@ -188,7 +189,26 @@ def testEnsureAsciiFalse(self):
188189
msg = self.buffer.getvalue().split('"message": "', 1)[1].split('"', 1)[0]
189190
self.assertEqual(msg, "Привет")
190191

191-
192+
def testCustomObjectSerialization(self):
193+
def encode_complex(z):
194+
if isinstance(z, complex):
195+
return (z.real, z.imag)
196+
else:
197+
type_name = z.__class__.__name__
198+
raise TypeError(f"Object of type '{type_name}' is no JSON serializable")
199+
200+
formatter = jsonlogger.JsonFormatter(json_default=encode_complex,
201+
json_encoder=json.JSONEncoder)
202+
self.logHandler.setFormatter(formatter)
203+
204+
value = {
205+
"special": complex(3, 8),
206+
"run": 12
207+
}
208+
209+
self.logger.info(" message", extra=value)
210+
msg = self.buffer.getvalue()
211+
self.assertEqual(msg, "{\"message\": \" message\", \"special\": [3.0, 8.0], \"run\": 12}\n")
192212

193213
if __name__ == '__main__':
194214
if len(sys.argv[1:]) > 0:

0 commit comments

Comments
 (0)
0