1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Tests for the streaming JSON writer.
14 from nominatim.utils.json_writer import JsonWriter
16 @pytest.mark.parametrize("inval,outstr", [(None, 'null'),
17 (True, 'true'), (False, 'false'),
18 (23, '23'), (0, '0'), (-1.3, '-1.3'),
19 ('g\nä', '"g\\nä"'), ('"', '"\\\""'),
20 ({}, '{}'), ([], '[]')])
21 def test_simple_value(inval, outstr):
25 assert writer() == outstr
29 def test_empty_array():
30 writer = JsonWriter().start_array().end_array()
32 assert writer() == '[]'
36 def test_array_with_single_value():
37 writer = JsonWriter().start_array().value(None).end_array()
39 assert writer() == '[null]'
43 @pytest.mark.parametrize("invals,outstr", [((1, ), '[1]'),
44 (('a', 'b'), '["a","b"]')])
45 def test_array_with_data(invals, outstr):
50 writer.value(ival).next()
53 assert writer() == outstr
57 def test_empty_object():
58 writer = JsonWriter().start_object().end_object()
60 assert writer() == '{}'
64 def test_object_single_entry():
65 writer = JsonWriter()\
71 assert writer() == '{"something":5}'
74 def test_object_many_values():
75 writer = JsonWriter()\
79 .keyval('baz', 'b\taz')\
82 assert writer() == '{"foo":null,"bar":{},"baz":"b\\taz"}'
85 def test_object_many_values_without_none():
86 writer = JsonWriter()\
88 .keyval_not_none('foo', 0)\
89 .keyval_not_none('bar', None)\
90 .keyval_not_none('baz', '')\
91 .keyval_not_none('eve', False,
92 transform = lambda v: 'yes' if v else 'no')\
95 assert writer() == '{"foo":0,"baz":"","eve":"no"}'
99 def test_raw_output():
100 writer = JsonWriter()\
102 .raw('{ "nicely": "formatted here" }').next()\
106 assert writer() == '[{ "nicely": "formatted here" },1]'