8000 Version 3 by tomchristie · Pull Request #156 · core-api/python-client · GitHub
[go: up one dir, main page]

Skip to content
This repository was archived by the owner on Mar 18, 2019. It is now read-only.

Version 3 #156

Open
wants to merge 61 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
61 commits
Select commit Hold shift + click to select a range
9bc4fbb
Drop 'transform', and remove 'inplace' transformations.
tomchristie Jan 29, 2018
30e4cb1
Merge branch 'master' into remove-transform
tomchristie Jan 30, 2018
b9f9dd7
Drop action= and encoding= parameters on client, in favor of override
tomchristie Jan 30, 2018
4fb5e88
Drop HTTPTransport 'credentials' in favor of 'auth'
tomchristie Jan 30, 2018
b0eb95c
Drop HTTP request_callback and response_callback in favor of custom s…
tomchristie Jan 30, 2018
ad00b0a
Drop unused import
tomchristie Jan 30, 2018
15dcdc9
Removing data from documents. Drop 'Array'.
tomchristie Jan 30, 2018
f3c8dde
Drop CallbackAdapater. We don't use it anywhere. Could later farm it …
tomchristie Jan 31, 2018
7d06d93
Drop DomainCredentials, now that we have proper auth classes
tomchristie Jan 31, 2018
ced53cf
Refactor to use session.request
tomchristie Jan 31, 2018
93946cd
Drop unneccessary default parameters
tomchristie Jan 31, 2018
e99f71b
Move _guess_extension out of utils and into codes/download
tomchristie Jan 31, 2018
61d4198
Drop 'Document.clone'
tomchristie Feb 13, 2018
bc6aa9e
Add typesys. Add OpenAPI, JSONSchema.
tomchristie Feb 14, 2018
df86966
.errors always a classmethod
tomchristie Feb 14, 2018
f106bd0
Create absolute URLs for Links from OpenAPI
tomchristie Feb 14, 2018
6b3296a
Drop coreschema
tomchristie Feb 14, 2018
8644689
Ordered schema representations. Support OpenAPI encoding.
tomchristie Feb 14, 2018
325d032
Include yaml in requirements
tomchristie Feb 14, 2018
5984a33
Drop coreschema
tomchristie Feb 14, 2018
9444bc0
Preserve ordering of OpenAPI 'paths' across python versions
tomchristie Feb 14, 2018
b3fa5c2
Default to JSON-flavoured OpenAPI
tomchristie Feb 15, 2018
235f50e
Schemas in tests should be bytestrings
tomchristie Feb 15, 2018
dc4edea
Ensure OpenAPI.encode returns bytestrings
tomchristie Feb 15, 2018
c85818c
dict is ordered in Python 3.6
tomchristie Feb 15, 2018
566abbe
Force ordering of document using in test case
tomchristie Feb 15, 2018
6530dc2
Enforced ordering in Object
tomchristie Feb 20, 2018
09518cd
Drop commented-out YAML code
tomchristie Feb 20, 2018
73c5015
Drop itypes from transports/codecs/client
tomchristie Feb 20, 2018
2d6e0bc
Drop BaseCodec dump/load/supports
tomchristie Feb 20, 2018
48784f4
Add document.version
tomchristie Feb 20, 2018
5e19106
Drop itypes from Error
tomchristie Feb 20, 2018
d1c006f
Drop itypes from Link
tomchristie Feb 20, 2018
b52553e
Drop itypes
tomchristie Feb 20, 2018
b1e3418
Drop client.reload
tomchristie Feb 20, 2018
7b0cf7d
_to_immutable -> _to_objects
tomchristie Feb 20, 2018
e663b9f
Drop reload from tests
tomchristie Feb 20, 2018
f09ca74
'enum' defined on types
tomchristie Feb 20, 2018
93482e9
Add openapi codec to setup
tomchristie Feb 20, 2018
54199e3
Add Field.title
tomchristie Feb 20, 2018
8c1748e
Use Link.method. Put .action towards deprecation.
tomchristie Feb 20, 2018
ae79ef5
Plain old classes for typesys
tomchristie Feb 21, 2018
01a0a51
Add typesys.Ref
tomchristie Feb 21, 2018
46a9559
assert types on __init__
tomchristie Feb 21, 2018
f772992
Tests and refinements to typesys
tomchristie Feb 21, 2018
a50e0e3
exact_items validation for Array
tomchristie Feb 21, 2018
b56b1d6
Add allow_null to typesys
tomchristie Feb 21, 2018
c58ad81
Work on JSON Schema and typesys
tomchristie Mar 1, 2018
15f24dc
Work on Union and JSONSchema
tomchristie Mar 1, 2018
cb8e273
Cleanups on typesys
tomchristie Mar 1, 2018
f19c680
Uniqueness checking always that always uses set()
tomchristie Mar 5, 2018
a87f66a
Add Section, Add Link.id
tomchristie Mar 5, 2018
382eef8
Slugify tag names to get section ids
tomchristie Mar 5, 2018
4a5993a
Add path_links and query_links to Section
tomchristie Mar 6, 2018
5e3de6c
Add path_fields and query_fields to Link
tomchristie Mar 6, 2018
1d7a121
Tweak
tomchristie Mar 6, 2018
58ec296
Fix 'security' in OpenAPI
tomchristie Mar 6, 2018
947e03b
If no operationId then use summary for Link.id
tomchristie Mar 6, 2018
7486932
Building out OpenAPI v3 spec
tomchristie Mar 6, 2018
69a5a69
First pass at parsing OpenAPI requestBody schemas
tomchristie Mar 6, 2018
3a793b9
Add initial requestBody schema support
tomchristie Mar 6, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Tests and refinements to typesys
  • Loading branch information
tomchristie committed Feb 21, 2018
commit f7729921c0264ae748abdef8110be49b598fd42d
97 changes: 59 additions & 38 deletions coreapi/typesys.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ def __init__(self, max_length=None, min_length=None, pattern=None, enum=None, fo
self.format = format

def validate(self, value, definitions=None):
value = str(value)
if not isinstance(value, string_types):
self.error('type')

if self.enum is not None:
if value not in self.enum:
Expand Down Expand Up @@ -115,7 +116,7 @@ class NumericType(Validator):
"""
numeric_type = None # type: type
errors = {
'type': 'Must be a valid number.',
'type': 'Must be a number.',
'minimum': 'Must be greater than or equal to {minimum}.',
'exclusive_minimum': 'Must be greater than {minimum}.',
'maximum': 'Must be less than or equal to {maximum}.',
Expand Down Expand Up @@ -143,11 +144,11 @@ def __init__(self, minimum=None, maximum=None, exclusive_minimum=False, exclusiv
self.format = format

def validate(self, value, definitions=None):
try:
value = self.numeric_type(value)
except (TypeError, ValueError):
if not isinstance(value, (int, float)) or isinstance(value, bool):
self.error('type')

value = self.numeric_type(value)

if self.enum is not None:
if value not in self.enum:
if len(self.enum) == 1:
Expand Down Expand Up @@ -195,29 +196,23 @@ class Boolean(Validator):
}

def validate(self, value, definitions=None):
if isinstance(value, (int, float, bool)):
return bool(value)
elif isinstance(value, str):
try:
return {
'true': True,
'false': False,
'1': True,
'0': False
}[value.lower()]
except KeyError:
pass
self.error('type')
if not isinstance(value, bool):
self.error('type')
return value


class Object(Validator):
errors = {
'type': 'Must be an object.',
'invalid_key': 'Object keys must be strings.',
'required': 'This field is required.',
'no_additional_properties': 'Unknown properties are not allowed.',
'empty': 'Must not be empty.',
'max_properties': 'Must have no more than {max_properties} properties.',
'min_properties': 'Must have at least {min_properties} properties.',
}

def __init__(self, properties=None, pattern_properties=None, additional_properties=None, required=None, **kwargs):
def __init__(self, properties=None, pattern_properties=None, additional_properties=True, min_properties=None, max_properties=None, required=None, **kwargs):
super(Object, self).__init__(**kwargs)

properties = {} if (properties is None) else dict_type(properties)
Expand All @@ -229,35 +224,56 @@ def __init__(self, properties=None, pattern_properties=None, additional_properti
assert all(isinstance(v, Validator) for v in properties.values())
assert all(isinstance(k, string_types) for k in pattern_properties.keys())
assert all(isinstance(v, Validator) for v in pattern_properties.values())
assert additional_properties is None or isinstance(additional_properties, (bool, Validator))
assert min_properties is None or isinstance(min_properties, int)
assert max_properties is None or isinstance(max_properties, int)
assert all(isinstance(i, string_types) for i in required)

self.properties = properties
self.pattern_properties = pattern_properties
self.additional_properties = additional_properties
self.min_properties = min_properties
self.max_properties = max_properties
self.required = required

def validate(self, value, definitions=None):
if definitions is None:
definitions = dict(self.definitions)
definitions[''] = self

validated = dict_type()
try:
value = dict_type(value)
except TypeError:
if not isinstance(value, dict):
self.error('type')

validated = dict_type()
value = dict_type(value)

# Ensure all property keys are strings.
errors = {}
if any(not isinstance(key, string_types) for key in value.keys()):
self.error('invalid_key')

# Min/Max properties
if self.min_properties is not None:
if len(value) < self.min_properties:
if self.min_properties == 1:
self.error('empty')
else:
self.error('min_properties')
if self.max_properties is not None:
if len(value) > self.max_properties:
self.error('max_properties')

# Requried properties
for key in self.required:
if key not in value:
errors[key] = self.error_message('required')

# Properties
for key, child_schema in self.properties.items():
try:
item = value.pop(key)
except KeyError:
if key in self.required:
errors[key] = self.error_message('required')
pass
else:
try:
validated[key] = child_schema.validate(item, definitions=definitions)
Expand All @@ -276,7 +292,12 @@ def validate(self, value, definitions=None):
errors[key] = exc.detail

# Additional properties
if self.additional_properties is not None:
if self.additional_properties is True:
validated.update(value)
elif self.additional_properties is False:
for key in value.keys():
errors[key] = self.error_message('no_additional_properties')
elif self.additional_properties is not None:
child_schema = self.additional_properties
for key in list(value.keys()):
item = value.pop(key)
Expand All @@ -293,9 +314,12 @@ def validate(self, value, definitions=None):

class Array(Validator):
errors = {
'type': 'Must be a list.',
'min_items': 'Not enough items.',
'max_items': 'Too many items.',
'type': 'Must be an array.',
'empty': 'Must not be empty.',
'exact_items': 'Must have {min_items} items.',
'min_items': 'Must have at least {min_items} items.',
'max_items': 'Must have no more than {max_items} items.',
'additional_items': 'May not contain additional items.',
'unique_items': 'This item is not unique.',
}

Expand All @@ -321,22 +345,19 @@ def validate(self, value, definitions=None):
definitions = dict(self.definitions)
definitions[''] = self

validated = []
try:
value = list(value)
except TypeError:
if not isinstance(value, list):
self.error('type')

if isinstance(self.items, list) and len(self.items) > 1:
if len(value) < len(self.items):
self.error('min_items')
elif len(value) > len(self.items) and (self.additional_items is False):
self.error('max_items')
validated = []

if self.min_items is not None and len(value) < self.min_items:
if self.min_items == 1:
self.error('empty')
self.error('min_items')
elif self.max_items is not None and len(value) > self.max_items:
self.error('max_items')
elif isinstance(self.items, list) and (self.additional_items is False) and len(value) > len(self.items):
self.error('additional_items')

# Ensure all items are of the right type.
errors = {}
Expand Down
76 changes: 76 additions & 0 deletions tests/typesys/test_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
from coreapi.typesys import Array, String, Integer, ValidationError
import pytest


def test_array_type():
schema = Array()
assert schema.validate([]) == []
assert schema.validate(['a', 1]) == ['a', 1]
with pytest.raises(ValidationError) as exc:
schema.validate(1)
assert exc.value.detail == 'Must be an array.'


def test_array_items():
schema = Array(items=String())
assert schema.validate([]) == []
assert schema.validate(['a', 'b', 'c']) == ['a', 'b', 'c']
with pytest.raises(ValidationError) as exc:
schema.validate(['a', 'b', 123])
assert exc.value.detail == {2: 'Must be a string.'}


def test_array_items_as_list():
schema = Array(items=[String(), Integer()])
assert schema.validate([]) == []
assert schema.validate(['a', 123]) == ['a', 123]
with pytest.raises(ValidationError) as exc:
schema.validate(['a', 'b'])
assert exc.value.detail == {1: 'Must be a number.'}


def test_array_max_items():
schema = Array(max_items=2)
assert schema.validate([1, 2]) == [1, 2]
with pytest.raises(ValidationError) as exc:
schema.validate([1, 2, 3])
assert exc.value.detail == 'Must have no more than 2 items.'


def test_array_min_items():
schema = Array(min_items=2)
assert schema.validate([1, 2]) == [1, 2]
with pytest.raises(ValidationError) as exc:
schema.validate([1])
assert exc.value.detail == 'Must have at least 2 items.'


def test_array_empty():
schema = Array(min_items=1)
assert schema.validate([1]) == [1]
with pytest.raises(ValidationError) as exc:
schema.validate([])
assert exc.value.detail == 'Must not be empty.'


def test_array_unique_items():
schema = Array(unique_items=True)
assert schema.validate([1, 2, 3]) == [1, 2, 3]
with pytest.raises(ValidationError) as exc:
schema.validate([1, 2, 1])
assert exc.value.detail == {2: 'This item is not unique.'}


def test_array_additional_items_disallowed():
schema = Array(items=[String(), Integer()])
assert schema.validate(['a', 123, True]) == ['a', 123, True]

schema = Array(items=[String(), Integer()], additional_items=False)
with pytest.raises(ValidationError) as exc:
schema.validate(['a', 123, True])
assert exc.value.detail == 'May not contain additional items.'

schema = Array(items=[String(), Integer()], additional_items=Integer())
with pytest.raises(ValidationError) as exc:
schema.validate(['a', 123, 'c'])
assert exc.value.detail == {2: 'Must be a number.'}
81 changes: 81 additions & 0 deletions tests/typesys/test_object.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
from coreapi.typesys import Object, Integer, String, ValidationError
import pytest


def test_object_type():
schema = Object()
assert schema.validate({}) == {}
assert schema.validate({'a': 1}) == {'a': 1}
with pytest.raises(ValidationError) as exc:
schema.validate(1)
assert exc.value.detail == 'Must be an object.'


def test_object_keys():
schema = Object()
with pytest.raises(ValidationError) as exc:
schema.validate({1: 1})
assert exc.value.detail == 'Object keys must be strings.'


def test_object_properties():
schema = Object(properties={'num': Integer()})
with pytest.raises(ValidationError) as exc:
schema.validate({'num': 'abc'})
assert exc.value.detail == {'num': 'Must be a number.'}


def test_object_required():
schema = Object(required=['name'])
assert schema.validate({'name': 1}) == {'name': 1}
with pytest.raises(ValidationError) as exc:
schema.validate({})
assert exc.value.detail == {'name': 'This field is required.'}


def test_object_max_properties():
schema = Object(max_properties=2)
assert schema.validate({'a': 1, 'b': 2}) == {'a': 1, 'b': 2}
with pytest.raises(ValidationError) as exc:
schema.validate({'a': 1, 'b': 2, 'c': 3})
assert exc.value.detail == 'Must have no more than 2 properties.'


def test_object_min_properties():
schema = Object(min_properties=2)
assert schema.validate({'a': 1, 'b': 2}) == {'a': 1, 'b': 2}
with pytest.raises(ValidationError) as exc:
assert schema.validate({'a': 1})
assert exc.value.detail == 'Must have at least 2 properties.'


def test_object_empty():
schema = Object(min_properties=1)
assert schema.validate({'a': 1}) == {'a': 1}
with pytest.raises(ValidationError) as exc:
schema.validate({})
assert exc.value.detail == 'Must not be empty.'


def test_object_pattern_properties():
schema = Object(pattern_properties={'^x-': Integer()})
assert schema.validate({'x-foo': 123}) == {'x-foo': 123}
with pytest.raises(ValidationError) as exc:
schema.validate({'x-foo': 'abc'})
assert exc.value.detail == {'x-foo': 'Must be a number.'}


def test_object_additional_properties_as_boolean():
schema = Object(properties={'a': String()}, additional_properties=False)
assert schema.validate({'a': 'abc'}) == {'a': 'abc'}
with pytest.raises(ValidationError) as exc:
schema.validate({'b': 'abc'})
assert exc.value.detail == {'b': 'Unknown properties are not allowed.'}


def test_object_additional_properties_as_schema():
schema = Object(properties={'a': String()}, additional_properties=Integer())
assert schema.validate({'a': 'abc'}) == {'a': 'abc'}
with pytest.raises(ValidationError) as exc:
schema.validate({'b': 'abc'})
assert exc.value.detail == {'b': 'Must be a number.'}
0