/
test_parsers.py
73 lines (53 loc) · 2.13 KB
/
test_parsers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from __future__ import absolute_import, print_function, unicode_literals
import json
import unittest
from collections import OrderedDict
import six
from rest_framework import parsers
from drf_braces.parsers import SortedJSONParser, StrippingJSONParser
class TestSortedJSONParser(unittest.TestCase):
def setUp(self):
super(TestSortedJSONParser, self).setUp()
self.parser = SortedJSONParser()
def test_parser(self):
content = json.dumps({'hello': 'world'}).encode('utf-8')
stream = six.BytesIO(content)
actual_data = self.parser.parse(stream=stream)
self.assertEqual(actual_data, OrderedDict([('hello', 'world')]))
def test_parser_invalid_json(self):
content = (
json.dumps({'hello': 'world'})
.replace('"', "'")
.encode('utf-8')
)
stream = six.BytesIO(content)
with self.assertRaises(parsers.ParseError):
self.parser.parse(stream=stream)
class TestStrippingJSONParser(unittest.TestCase):
def setUp(self):
super(TestStrippingJSONParser, self).setUp()
self.parser = StrippingJSONParser()
def test_parser(self):
content = json.dumps({'root': {'hello': 'world'}}).encode('utf-8')
stream = six.BytesIO(content)
actual_data = self.parser.parse(
stream=stream,
parser_context={'parse_root': 'root'}
)
self.assertEqual(actual_data, OrderedDict([('hello', 'world')]))
def test_parser_no_root(self):
content = json.dumps({'root': {'hello': 'world'}}).encode('utf-8')
stream = six.BytesIO(content)
actual_data = self.parser.parse(
stream=stream,
parser_context={}
)
self.assertEqual(actual_data, {'root': {'hello': 'world'}})
def test_parser_different_root(self):
content = json.dumps({'root': {'hello': 'world'}}).encode('utf-8')
stream = six.BytesIO(content)
actual_data = self.parser.parse(
stream=stream,
parser_context={'parse_root': 'foo'}
)
self.assertEqual(actual_data, {'root': {'hello': 'world'}})