forked from core-api/python-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_document.py
More file actions
369 lines (255 loc) · 8.8 KB
/
test_document.py
File metadata and controls
369 lines (255 loc) · 8.8 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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# coding: utf-8
from coreapi import Client
from coreapi import Document, Object, Link, Error, Field
from coreapi.exceptions import LinkLookupError
import pytest
@pytest.fixture
def doc():
return Document(
url='http://example.org',
title='Example',
content={
'integer': 123,
'dict': {'key': 'value'},
'link': Link(
url='/',
action='post',
fields=['optional', Field('required', required=True, location='path')]
),
'nested': {'child': Link(url='/123')}
})
@pytest.fixture
def obj():
return Object({'key': 'value', 'nested': {'abc': 123}})
@pytest.fixture
def link():
return Link(
url='/',
action='post',
fields=[Field('required', required=True), 'optional']
)
@pytest.fixture
def error():
return Error(title='', content={'messages': ['failed']})
def _dedent(string):
"""
Convenience function for dedenting multiline strings,
for string comparison purposes.
"""
lines = string.splitlines()
if not lines[0].strip():
lines = lines[1:]
if not lines[-1].strip():
lines = lines[:-1]
leading_spaces = len(lines[0]) - len(lines[0].lstrip(' '))
return '\n'.join(line[leading_spaces:] for line in lines)
# Documents are immutable.
def test_document_does_not_support_key_assignment(doc):
with pytest.raises(TypeError):
doc['integer'] = 456
def test_document_does_not_support_property_assignment(doc):
with pytest.raises(TypeError):
doc.integer = 456
def test_document_does_not_support_key_deletion(doc):
with pytest.raises(TypeError):
del doc['integer']
# Objects are immutable.
def test_object_does_not_support_key_assignment(obj):
with pytest.raises(TypeError):
obj['key'] = 456
def test_object_does_not_support_property_assignment(obj):
with pytest.raises(TypeError):
obj.integer = 456
def test_object_does_not_support_key_deletion(obj):
with pytest.raises(TypeError):
del obj['key']
# Links are immutable.
def test_link_does_not_support_property_assignment():
link = Link()
with pytest.raises(TypeError):
link.integer = 456
# Errors are immutable.
def test_error_does_not_support_property_assignment():
error = Error(content={'messages': ['failed']})
with pytest.raises(TypeError):
error.integer = 456
# Children in documents are immutable primitives.
def test_document_dictionaries_coerced_to_objects(doc):
assert isinstance(doc['dict'], Object)
# The `delete` and `set` methods return new instances.
def test_document_delete(doc):
new = doc.delete('integer')
assert doc is not new
assert set(new.keys()) == set(doc.keys()) - set(['integer'])
for key in new.keys():
assert doc[key] is new[key]
def test_document_set(doc):
new = doc.set('integer', 456)
assert doc is not new
assert set(new.keys()) == set(doc.keys())
for key in set(new.keys()) - set(['integer']):
assert doc[key] is new[key]
def test_object_delete(obj):
new = obj.delete('key')
assert obj is not new
assert set(new.keys()) == set(obj.keys()) - set(['key'])
for key in new.keys():
assert obj[key] is new[key]
def test_object_set(obj):
new = obj.set('key', 456)
assert obj is not new
assert set(new.keys()) == set(obj.keys())
for key in set(new.keys()) - set(['key']):
assert obj[key] is new[key]
# Container types have a uniquely identifying representation.
def test_document_repr(doc):
assert repr(doc) == (
"Document(url='http://example.org', title='Example', content={"
"'dict': {'key': 'value'}, "
"'integer': 123, "
"'nested': {'child': Link(url='/123')}, "
"'link': Link(url='/', action='post', "
"fields=['optional', Field('required', required=True, location='path')])"
"})"
)
assert eval(repr(doc)) == doc
def test_object_repr(obj):
assert repr(obj) == "Object({'key': 'value', 'nested': {'abc': 123}})"
assert eval(repr(obj)) == obj
def test_link_repr(link):
assert repr(link) == "Link(url='/', action='post', fields=[Field('required', required=True), 'optional'])"
assert eval(repr(link)) == link
def test_error_repr(error):
assert repr(error) == "Error(title='', content={'messages': ['failed']})"
assert eval(repr(error)) == error
# Container types have a convenient string representation.
def test_document_str(doc):
assert str(doc) == _dedent("""
<Example "http://example.org">
dict: {
key: "value"
}
integer: 123
nested: {
child()
}
link(required, [optional])
""")
def test_newline_str():
doc = Document(content={'foo': '1\n2'})
assert str(doc) == _dedent("""
<Document "">
foo: "1
2"
""")
def test_object_str(obj):
assert str(obj) == _dedent("""
{
key: "value"
nested: {
abc: 123
}
}
""")
def test_link_str(link):
assert str(link) == "link(required, [optional])"
def test_error_str(error):
assert str(error) == _dedent("""
<Error>
messages: ["failed"]
""")
def test_document_urls():
doc = Document(url='http://example.org/', title='Example', content={
'a': Document(title='Full', url='http://example.com/123'),
'b': Document(title='Path', url='http://example.org/123'),
'c': Document(title='None', url='http://example.org/')
})
assert str(doc) == _dedent("""
<Example "http://example.org/">
a: <Full "http://example.com/123">
b: <Path "http://example.org/123">
c: <None "http://example.org/">
""")
# Container types support equality functions.
def test_document_equality(doc):
assert doc == {
'integer': 123,
'dict': {'key': 'value'},
'link': Link(
url='/',
action='post',
fields=['optional', Field('required', required=True, location='path')]
),
'nested': {'child': Link(url='/123')}
}
def test_object_equality(obj):
assert obj == {'key': 'value', 'nested': {'abc': 123}}
# Container types support len.
def test_document_len(doc):
assert len(doc) == 4
def test_object_len(obj):
assert len(obj) == 2
# Documents meet the Core API constraints.
def test_document_url_must_be_string():
with pytest.raises(TypeError):
Document(url=123)
def test_document_title_must_be_string():
with pytest.raises(TypeError):
Document(title=123)
def test_document_content_must_be_dict():
with pytest.raises(TypeError):
Document(content=123)
def test_document_keys_must_be_strings():
with pytest.raises(TypeError):
Document(content={0: 123})
def test_object_keys_must_be_strings():
with pytest.raises(TypeError):
Object(content={0: 123})
def test_error_title_must_be_string():
with pytest.raises(TypeError):
Error(title=123)
def test_error_content_must_be_dict():
with pytest.raises(TypeError):
Error(content=123)
def test_error_keys_must_be_strings():
with pytest.raises(TypeError):
Error(content={0: 123})
# Link arguments must be valid.
def test_link_url_must_be_string():
with pytest.raises(TypeError):
Link(url=123)
def test_link_action_must_be_string():
with pytest.raises(TypeError):
Link(action=123)
def test_link_fields_must_be_list():
with pytest.raises(TypeError):
Link(fields=123)
def test_link_field_items_must_be_valid():
with pytest.raises(TypeError):
Link(fields=[123])
# Invalid calls to '.action()' should error.
def test_keys_should_be_a_list_or_string(doc):
client = Client()
with pytest.raises(TypeError):
client.action(doc, True)
def test_keys_should_be_a_list_of_strings_or_ints(doc):
client = Client()
with pytest.raises(TypeError):
client.action(doc, ['nested', {}])
def test_keys_should_be_valid_indexes(doc):
client = Client()
with pytest.raises(LinkLookupError):
client.action(doc, 'dummy')
def test_keys_should_access_a_link(doc):
client = Client()
with pytest.raises(LinkLookupError):
client.action(doc, 'dict')
# Documents and Objects have `.data` and `.links` attributes
def test_document_data_and_links_properties():
doc = Document(content={'a': 1, 'b': 2, 'c': Link(), 'd': Link()})
assert sorted(list(doc.data.keys())) == ['a', 'b']
assert sorted(list(doc.links.keys())) == ['c', 'd']
def test_object_data_and_links_properties():
obj = Object({'a': 1, 'b': 2, 'c': Link(), 'd': Link()})
assert sorted(list(obj.data.keys())) == ['a', 'b']
assert sorted(list(obj.links.keys())) == ['c', 'd']