|
2 | 2 | import orjson |
3 | 3 | import unittest |
4 | 4 | import dateutil |
| 5 | +import decimal |
| 6 | + |
| 7 | +from unittest.mock import MagicMock |
5 | 8 |
|
6 | 9 |
|
7 | 10 | class TestSinger(unittest.TestCase): |
@@ -206,6 +209,45 @@ def test_format_message(self): |
206 | 209 | self.assertEqual(b'{"type":"RECORD","stream":"users","record":{"name":"foo"}}\n', |
207 | 210 | singer.format_message(record_message, option=orjson.OPT_APPEND_NEWLINE)) |
208 | 211 |
|
| 212 | + def test_default_handler_decimal(self): |
| 213 | + """Test that decimal.Decimal is converted to a string.""" |
| 214 | + d = decimal.Decimal("10.50") |
| 215 | + result = singer.handler_for_decimal_object(d) |
| 216 | + self.assertEqual(result, 10.50) |
| 217 | + self.assertIsInstance(result, float) |
| 218 | + |
| 219 | + def test_default_handler_error(self): |
| 220 | + """Test that unsupported types still raise a TypeError.""" |
| 221 | + with self.assertRaises(TypeError): |
| 222 | + singer.handler_for_decimal_object(range(5)) |
| 223 | + |
| 224 | + def test_format_message_with_decimals(self): |
| 225 | + """Test that format_message correctly serializes a message containing decimals.""" |
| 226 | + # Mocking the message object |
| 227 | + mock_message = MagicMock() |
| 228 | + mock_message.asdict.return_value = { |
| 229 | + "id": 1, |
| 230 | + "price": decimal.Decimal("99.99"), |
| 231 | + "status": "active" |
| 232 | + } |
| 233 | + |
| 234 | + # We expect the Decimal to become a string in the resulting bytes |
| 235 | + expected_output = b'{"id":1,"price":99.99,"status":"active"}' |
| 236 | + |
| 237 | + result = singer.format_message(mock_message) |
| 238 | + self.assertEqual(result, expected_output) |
| 239 | + |
| 240 | + def test_format_message_options(self): |
| 241 | + """Test that orjson options (like appending a newline) work.""" |
| 242 | + mock_message = MagicMock() |
| 243 | + mock_message.asdict.return_value = {"key": "val"} |
| 244 | + |
| 245 | + # orjson.OPT_APPEND_NEWLINE is an integer bitmask |
| 246 | + result = singer.format_message(mock_message, option=orjson.OPT_APPEND_NEWLINE) |
| 247 | + |
| 248 | + # Should end with a newline byte (10) |
| 249 | + self.assertTrue(result.endswith(b'\n')) |
| 250 | + |
209 | 251 |
|
210 | 252 | if __name__ == '__main__': |
211 | 253 | unittest.main() |
0 commit comments