This repository was archived by the owner on Mar 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathtest_codecs.py
More file actions
303 lines (224 loc) · 8.37 KB
/
test_codecs.py
File metadata and controls
303 lines (224 loc) · 8.37 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
# coding: utf-8
from coreapi import negotiate_decoder, negotiate_encoder
from coreapi.codecs import CoreJSONCodec, CoreHTMLCodec
from coreapi.codecs.corejson import _document_to_primative, _primative_to_document
from coreapi.document import Document, Link, Error, Field
from coreapi.exceptions import ParseError, UnsupportedContentType, NotAcceptable
import pytest
@pytest.fixture
def json_codec():
return CoreJSONCodec()
@pytest.fixture
def html_codec():
return CoreHTMLCodec()
@pytest.fixture
def doc():
return Document(
url='http://example.org/',
title='Example',
content={
'integer': 123,
'dict': {'key': 'value'},
'list': [1, 2, 3],
'link': Link(url='http://example.org/', fields=[Field(name='example')]),
'nested': {'child': Link(url='http://example.org/123')},
'_type': 'needs escaping'
})
# Documents have a mapping to python primatives in JSON style.
def test_document_to_primative(doc):
data = _document_to_primative(doc)
assert data == {
'_type': 'document',
'_meta': {
'url': 'http://example.org/',
'title': 'Example'
},
'integer': 123,
'dict': {'key': 'value'},
'list': [1, 2, 3],
'link': {'_type': 'link', 'fields': [{'name': 'example'}]},
'nested': {'child': {'_type': 'link', 'url': '/123'}},
'__type': 'needs escaping'
}
def test_primative_to_document(doc):
data = {
'_type': 'document',
'_meta': {
'url': 'http://example.org/',
'title': 'Example'
},
'integer': 123,
'dict': {'key': 'value'},
'list': [1, 2, 3],
'link': {'_type': 'link', 'url': 'http://example.org/', 'fields': [{'name': 'example'}]},
'nested': {'child': {'_type': 'link', 'url': 'http://example.org/123'}},
'__type': 'needs escaping'
}
assert _primative_to_document(data) == doc
def test_error_to_primative():
error = Error(title='Failure', content={'messages': ['failed']})
data = {
'_type': 'error',
'_meta': {'title': 'Failure'},
'messages': ['failed']
}
assert _document_to_primative(error) == data
def test_primative_to_error():
error = Error(title='Failure', content={'messages': ['failed']})
data = {
'_type': 'error',
'_meta': {'title': 'Failure'},
'messages': ['failed']
}
assert _primative_to_document(data) == error
# Codecs can load a document successfully.
def test_minimal_document(json_codec):
"""
Ensure we can load the smallest possible valid JSON encoding.
"""
doc = json_codec.load(b'{"_type":"document"}')
assert isinstance(doc, Document)
assert doc.url == ''
assert doc.title == ''
assert doc == {}
def test_minimal_error(json_codec):
"""
Ensure we can load a minimal error message encoding.
"""
error = json_codec.load(b'{"_type":"error","_meta":{"title":"Failure"},"messages":["failed"]}')
assert error == Error(title="Failure", content={'messages': ['failed']})
# Parse errors should be raised for invalid encodings.
def test_malformed_json(json_codec):
"""
Invalid JSON should raise a ParseError.
"""
with pytest.raises(ParseError):
json_codec.load(b'_')
def test_not_a_document(json_codec):
"""
Valid JSON that does not return a document as the top level element
should raise a ParseError.
"""
with pytest.raises(ParseError):
json_codec.load(b'{}')
# Encodings may have a verbose and a compact style.
def test_compact_style(json_codec):
doc = Document(content={'a': 123, 'b': 456})
bytes = json_codec.dump(doc)
assert bytes == b'{"_type":"document","a":123,"b":456}'
def test_verbose_style(json_codec):
doc = Document(content={'a': 123, 'b': 456})
bytes = json_codec.dump(doc, indent=True)
assert bytes == b"""{
"_type": "document",
"a": 123,
"b": 456
}"""
# Links should use compact format for optional fields, verbose for required.
def test_link_encodings(json_codec):
doc = Document(content={
'link': Link(
action='post',
inplace=True,
fields=['optional', Field('required', required=True, location='path')]
)
})
bytes = json_codec.dump(doc, indent=True)
assert bytes == b"""{
"_type": "document",
"link": {
"_type": "link",
"action": "post",
"inplace": true,
"fields": [
{
"name": "optional"
},
{
"name": "required",
"required": true,
"location": "path"
}
]
}
}"""
# Tests for graceful omissions.
def test_invalid_document_meta_ignored(json_codec):
doc = json_codec.load(b'{"_type": "document", "_meta": 1, "a": 1}')
assert doc == Document(content={"a": 1})
def test_invalid_document_url_ignored(json_codec):
doc = json_codec.load(b'{"_type": "document", "_meta": {"url": 1}, "a": 1}')
assert doc == Document(content={"a": 1})
def test_invalid_document_title_ignored(json_codec):
doc = json_codec.load(b'{"_type": "document", "_meta": {"title": 1}, "a": 1}')
assert doc == Document(content={"a": 1})
def test_invalid_link_url_ignored(json_codec):
doc = json_codec.load(b'{"_type": "document", "link": {"_type": "link", "url": 1}}')
assert doc == Document(content={"link": Link()})
def test_invalid_link_fields_ignored(json_codec):
doc = json_codec.load(b'{"_type": "document", "link": {"_type": "link", "fields": 1}}')
assert doc == Document(content={"link": Link()})
# Tests for 'Content-Type' header lookup.
def test_get_default_decoder():
assert isinstance(negotiate_decoder(), CoreJSONCodec)
def test_get_supported_decoder():
assert isinstance(negotiate_decoder('application/vnd.coreapi+json'), CoreJSONCodec)
def test_get_supported_decoder_with_parameters():
assert isinstance(negotiate_decoder('application/vnd.coreapi+json; verison=1.0'), CoreJSONCodec)
def test_get_unsupported_decoder():
with pytest.raises(UnsupportedContentType):
negotiate_decoder('application/csv')
def test_get_render_only_decoder():
with pytest.raises(UnsupportedContentType):
negotiate_decoder('text/html')
# Tests for 'Accept' header lookup.
def test_get_default_encoder():
codec = negotiate_encoder()
assert isinstance(codec, CoreJSONCodec)
def test_encoder_preference():
codec = negotiate_encoder(
accept='text/html; q=1.0, application/vnd.coreapi+json; q=1.0'
)
assert isinstance(codec, CoreJSONCodec)
def test_get_accepted_encoder():
codec = negotiate_encoder(accept='application/vnd.coreapi+json')
assert isinstance(codec, CoreJSONCodec)
def test_get_underspecified_encoder():
codec = negotiate_encoder(accept='text/*')
assert isinstance(codec, CoreHTMLCodec)
def test_get_unsupported_encoder():
with pytest.raises(NotAcceptable):
negotiate_encoder('application/csv')
def test_get_unsupported_encoder_with_fallback():
codec = negotiate_encoder(accept='application/csv, */*')
assert isinstance(codec, CoreJSONCodec)
# Tests for HTML rendering
def test_html_document_rendering(html_codec):
doc = Document(content={'string': 'abc', 'int': 123, 'bool': True})
content = html_codec.dump(doc)
assert 'coreapi-document' in content
assert '<span>abc</span>' in content
assert '<code>123</code>' in content
assert '<code>true</code>' in content
def test_html_object_rendering(html_codec):
doc = Document(content={'object': {'a': 1, 'b': 2}})
content = html_codec.dump(doc)
assert 'coreapi-object' in content
assert '<th>a</th>' in content
assert '<th>b</th>' in content
def test_html_array_rendering(html_codec):
doc = Document(content={'array': [1, 2]})
content = html_codec.dump(doc)
assert 'coreapi-array' in content
assert '<th>0</th>' in content
assert '<th>1</th>' in content
def test_html_link_rendering(html_codec):
doc = Document(content={'link': Link(url='/test/')})
content = html_codec.dump(doc)
assert 'coreapi-link' in content
assert 'href="/test/"' in content
def test_html_error_rendering(html_codec):
doc = Error(content={'message': ['something failed']})
content = html_codec.dump(doc)
assert 'coreapi-error' in content
assert 'something failed' in content