Skip to content

Commit

Permalink
Merge pull request #46 from cwacek/fix/8-string-representations
Browse files Browse the repository at this point in the history
Fix #8. Python 3 removes support for __cmp__.
  • Loading branch information
cwacek authored Jul 16, 2016
2 parents fadc781 + c946e84 commit ad1ce37
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 10 deletions.
19 changes: 10 additions & 9 deletions python_jsonschema_objects/classbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,9 @@ def __repr__(self):
str(self._value)
)

def __str__(self):
return str(self._value)

def validate(self):
info = self.propinfo('__literal__')

Expand All @@ -364,16 +367,14 @@ def validate(self):
if validator is not None:
validator(paramval, self._value, info)

def __eq__(self, other):
return self._value == other

def __hash__(self):
return hash(self._value)

def __cmp__(self, other):
if isinstance(other, six.integer_types):
return cmp(int(self), other)
elif isinstance(other, six.string_types):
return cmp(str(self), other)
elif isinstance(other, float):
return cmp(float(self), other)
else:
return cmp(id(self), id(other))
def __lt__(self, other):
return self._value < other

def __int__(self):
return int(self._value)
Expand Down
51 changes: 51 additions & 0 deletions test/test_regression_8.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import pytest

import python_jsonschema_objects as pjo


@pytest.fixture
def test_instance():
schema = {
'title': 'Example',
'properties': {
'stringProp': {'type': 'string'},
'arrayProp': {
'type': 'array',
'items': {
'type': 'string',
}
}
}
}

builder = pjo.ObjectBuilder(schema)
ns = builder.build_classes()
instance = ns.Example(
stringProp='This seems fine',
arrayProp=['these', 'are', 'problematic']
)
return instance


def test_string_properties_compare_to_strings(test_instance):
test = test_instance.stringProp == "This seems fine"
assert test


def test_arrays_of_strings_compare_to_strings(test_instance):
test = test_instance.arrayProp == ['these', 'are', 'problematic']
assert test


def test_array_elements_compare_to_types(test_instance):
elem = test_instance.arrayProp[0]
test = elem == 'these'
assert test

def test_repr_shows_property_values(test_instance):
expected = "<example/arrayProp_<anonymous_field> these>"
assert repr(test_instance.arrayProp[0]) == expected

def test_str_shows_just_strings(test_instance):
test = str(test_instance.arrayProp[0])
assert test == 'these'
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

[tox]
envlist = py27, py34
envlist = py27, py35

[testenv]
;install_command = pip install {opts} {packages}
Expand Down

0 comments on commit ad1ce37

Please sign in to comment.