Debian Codegraph @

petl/test/io/test_jsonl.py

raw
1 # -*- coding: utf-8 -*-
2 from __future__ import absolute_import, print_function, division
3
4 from tempfile import NamedTemporaryFile
5 import json
6
7 from petl import fromjson, tojson
8 from petl.test.helpers import ieq
9
10
11 def test_fromjson_1():
12 f = NamedTemporaryFile(delete=False, mode='w')
13 data = '{"name": "Gilbert", "wins": [["straight", "7S"], ["one pair", "10H"]]}\n' \
14 '{"name": "Alexa", "wins": [["two pair", "4S"], ["two pair", "9S"]]}\n' \
15 '{"name": "May", "wins": []}\n' \
16 '{"name": "Deloise", "wins": [["three of a kind", "5S"]]}'
17
18 f.write(data)
19 f.close()
20
21 actual = fromjson(f.name, header=['name', 'wins'], lines=True)
22
23 expect = (('name', 'wins'),
24 ('Gilbert', [["straight", "7S"], ["one pair", "10H"]]),
25 ('Alexa', [["two pair", "4S"], ["two pair", "9S"]]),
26 ('May', []),
27 ('Deloise', [["three of a kind", "5S"]]))
28
29 ieq(expect, actual)
30 ieq(expect, actual) # verify can iterate twice
31
32
33 def test_fromjson_2():
34 f = NamedTemporaryFile(delete=False, mode='w')
35 data = '{"foo": "bar1", "baz": 1}\n' \
36 '{"foo": "bar2", "baz": 2}\n' \
37 '{"foo": "bar3", "baz": 3}\n' \
38 '{"foo": "bar4", "baz": 4}\n'
39
40 f.write(data)
41 f.close()
42
43 actual = fromjson(f.name, header=['foo', 'baz'], lines=True)
44
45 expect = (('foo', 'baz'),
46 ('bar1', 1),
47 ('bar2', 2),
48 ('bar3', 3),
49 ('bar4', 4))
50
51 ieq(expect, actual)
52 ieq(expect, actual) # verify can iterate twice
53
54
55 def test_tojson_1():
56 table = (('foo', 'bar'),
57 ('a', 1),
58 ('b', 2),
59 ('c', 2))
60 f = NamedTemporaryFile(delete=False, mode='r')
61 tojson(table, f.name, lines=True)
62 result = []
63 for line in f:
64 result.append(json.loads(line))
65 assert len(result) == 3
66 assert result[0]['foo'] == 'a'
67 assert result[0]['bar'] == 1
68 assert result[1]['foo'] == 'b'
69 assert result[1]['bar'] == 2
70 assert result[2]['foo'] == 'c'
71 assert result[2]['bar'] == 2
72
73
74 def test_tojson_2():
75 table = [['name', 'wins'],
76 ['Gilbert', [['straight', '7S'], ['one pair', '10H']]],
77 ['Alexa', [['two pair', '4S'], ['two pair', '9S']]],
78 ['May', []],
79 ['Deloise', [['three of a kind', '5S']]]]
80 f = NamedTemporaryFile(delete=False, mode='r')
81 tojson(table, f.name, lines=True)
82 result = []
83 for line in f:
84 result.append(json.loads(line))
85 assert len(result) == 4
86 assert result[0]['name'] == 'Gilbert'
87 assert result[0]['wins'] == [['straight', '7S'], ['one pair', '10H']]
88 assert result[1]['name'] == 'Alexa'
89 assert result[1]['wins'] == [['two pair', '4S'], ['two pair', '9S']]
90 assert result[2]['name'] == 'May'
91 assert result[2]['wins'] == []
92 assert result[3]['name'] == 'Deloise'
93 assert result[3]['wins'] == [['three of a kind', '5S']]