Skip to content

Commit

Permalink
Merge pull request #122 from timofurrer/bugfix/treat-python2-special
Browse files Browse the repository at this point in the history
Treat Python 2 as special case and not Python 3
  • Loading branch information
timofurrer committed Jun 22, 2016
2 parents b15857f + de0994e commit dfceb6b
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 58 deletions.
8 changes: 4 additions & 4 deletions OLD_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ a assertion toolbox that works fine with [nose](http://code.google.com/p/python-

```python
from sure.deprecated import that
from six import PY3
from six import PY2

if PY3:
assert that("something").is_a(str)
else:
if PY2:
assert that(b"something").is_a(str)
else:
assert that("something").is_a(str)
assert that("something").like("some")
assert "thing" in that("something")

Expand Down
14 changes: 7 additions & 7 deletions sure/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from functools import wraps, partial
from datetime import datetime

from six import string_types, text_type, PY3, get_function_code
from six import string_types, text_type, PY2, get_function_code
from six.moves import reduce

from sure.old import AssertionHelper
Expand All @@ -45,7 +45,7 @@
from sure.registry import context as _registry


if PY3:
if not PY2:
basestring = str

version = '1.3.0'
Expand Down Expand Up @@ -185,11 +185,11 @@ def wrap(*args, **kw):
try:
func(start, *args, **kw)
except TypeError as e:
if PY3:
# PY3 has different error message
fmt = '{0}() takes 0 positional arguments but 1 was given'
else:
if PY2:
# PY2 has different error message
fmt = '{0}() takes no arguments'
else:
fmt = '{0}() takes 0 positional arguments but 1 was given'
err = text_type(e)
if fmt.format(func.__name__) in err:
func(*args, **kw)
Expand Down Expand Up @@ -387,7 +387,7 @@ def wrapper(self, *args, **kw):
", ".join(map(safe_repr, args)),
", ".join(["{0}={1}".format(k, safe_repr(kw[k])) for k in kw]),
)
if not PY3:
if PY2:
msg = text_type(msg)

assert value, msg
Expand Down
18 changes: 9 additions & 9 deletions sure/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@
from sure.terminal import red, green, yellow


if six.PY3:
def compat_repr(object_repr):
return object_repr
else:
if six.PY2:
def compat_repr(object_repr):
# compat_repr is designed to return all reprs with leading 'u's
# inserted to make all strings look like unicode strings.
Expand All @@ -33,6 +30,9 @@ def compat_repr(object_repr):
in_quote = True
result += char
return result
else:
def compat_repr(object_repr):
return object_repr

# FIXME: move FakeOrderedDict to another module since it
# does not have anything todo with compat.
Expand All @@ -51,18 +51,18 @@ def __unicode__(self):
key_values = []
for key, value in self.items():
key, value = repr(key), repr(value)
if isinstance(value, six.binary_type) and not six.PY3:
if isinstance(value, six.binary_type) and six.PY2:
value = value.decode("utf-8")
key_values.append("{0}: {1}".format(key, value))
res = "{{{0}}}".format(", ".join(key_values))
return res

if six.PY3:
if six.PY2:
def __repr__(self):
return self.__unicode__()
return self.__unicode__().encode('utf-8')
else:
def __repr__(self):
return self.__unicode__().encode('utf-8')
return self.__unicode__()


def _obj_with_safe_repr(obj):
Expand All @@ -89,7 +89,7 @@ def safe_repr(val):
# significantly easier
val = _obj_with_safe_repr(val)
ret = repr(val)
if not six.PY3:
if six.PY2:
ret = ret.decode('utf-8')
except UnicodeEncodeError:
ret = red('a %r that cannot be represented' % type(val))
Expand Down
56 changes: 28 additions & 28 deletions tests/test_assertion_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

from datetime import datetime, timedelta
from sure import this, these, those, it, expect, anything, AssertionBuilder
from six import PY3
from six import PY2
from sure.compat import compat_repr


Expand Down Expand Up @@ -464,11 +464,11 @@ def __init__(self, x):
self.x = x

def __repr__(self):
if PY3:
# PY3K should return the regular (unicode) string
return self.x
else:
if PY2:
# PY2 should return the regular (unicode) string
return self.x.encode('utf-8')
else:
return self.x

def __eq__(self, other):
return self.x == other.x
Expand All @@ -494,11 +494,11 @@ def __init__(self, x):
self.x = x

def __repr__(self):
if PY3:
# PY3K should return the regular (unicode) string
return self.x
else:
if PY2:
# PY2 should return the regular (unicode) string
return self.x.encode('utf-8')
else:
return self.x

def __eq__(self, other):
return self.x == other.x
Expand Down Expand Up @@ -577,20 +577,20 @@ def opposite_not():
assert this("some string").should_not.contain(r"string")

expect(opposite).when.called.to.throw(AssertionError)
if PY3:
if PY2:
expect(opposite).when.called.to.throw(
"'bar' should be in 'some string'")
"u'bar' should be in u'some string'")
else:
expect(opposite).when.called.to.throw(
"u'bar' should be in u'some string'")
"'bar' should be in 'some string'")

expect(opposite_not).when.called.to.throw(AssertionError)
if PY3:
if PY2:
expect(opposite_not).when.called.to.throw(
"'string' should NOT be in 'some string'")
"u'string' should NOT be in u'some string'")
else:
expect(opposite_not).when.called.to.throw(
"u'string' should NOT be in u'some string'")
"'string' should NOT be in 'some string'")


def test_catching_exceptions():
Expand Down Expand Up @@ -650,19 +650,19 @@ def blah(num):
raise RuntimeError('should not have reached here')

except AssertionError as e:
if PY3:
expect(str(e)).to.equal("When calling b'blah [tests/test_assertion_builder.py line 635]' the exception message does not match. Expected to match regex: 'invalid regex'\n against:\n 'this message'")
else:
if PY2:
expect(str(e)).to.equal("When calling 'blah [tests/test_assertion_builder.py line 635]' the exception message does not match. Expected to match regex: u'invalid regex'\n against:\n u'this message'")
else:
expect(str(e)).to.equal("When calling b'blah [tests/test_assertion_builder.py line 635]' the exception message does not match. Expected to match regex: 'invalid regex'\n against:\n 'this message'")

try:
expect(blah).when.called_with(1).should.throw(ValueError, re.compile(r'invalid regex'))
raise RuntimeError('should not have reached here')
except AssertionError as e:
if PY3:
expect(str(e)).to.equal("When calling b'blah [tests/test_assertion_builder.py line 635]' the exception message does not match. Expected to match regex: 'invalid regex'\n against:\n 'this message'")
else:
if PY2:
expect(str(e)).to.equal("When calling 'blah [tests/test_assertion_builder.py line 635]' the exception message does not match. Expected to match regex: u'invalid regex'\n against:\n u'this message'")
else:
expect(str(e)).to.equal("When calling b'blah [tests/test_assertion_builder.py line 635]' the exception message does not match. Expected to match regex: 'invalid regex'\n against:\n 'this message'")

def test_should_not_be_different():
("'something'.should_not.be.different('SOMETHING'.lower())")
Expand Down Expand Up @@ -782,18 +782,18 @@ def test_ordereddict_comparison():
expect(result).should.equal(expectation)
raise RuntimeError("should not have reached here")
except AssertionError as error:
if PY3:
expect(str(error)).should.be.equal("""given
X = {'children': {}, 'fields': {'age': '22', 'name': 'John'}}
and
Y = {'children': {}, 'fields': {'age': '22', 'name': 'John'}}
X['fields'] and Y['fields'] are in a different order""")
else:
if PY2:
expect(str(error)).should.be.equal("""given
X = {u'children': {}, u'fields': {u'age': u'22', u'name': u'John'}}
and
Y = {u'children': {}, u'fields': {u'age': u'22', u'name': u'John'}}
X[u'fields'] and Y[u'fields'] are in a different order""")
else:
expect(str(error)).should.be.equal("""given
X = {'children': {}, 'fields': {'age': '22', 'name': 'John'}}
and
Y = {'children': {}, 'fields': {'age': '22', 'name': 'John'}}
X['fields'] and Y['fields'] are in a different order""")


def test_equals_anything():
Expand Down
8 changes: 4 additions & 4 deletions tests/test_old_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals

from six import text_type, PY3
from six import text_type, PY2
from six.moves import xrange

import sure
Expand Down Expand Up @@ -545,7 +545,7 @@ def test_that_contains_none():

def assertions():
# We can't use unicode in Py2, otherwise it will try to coerce
assert that('foobar' if PY3 else b'foobar').contains(None)
assert that(b'foobar' if PY2 else 'foobar').contains(None)

error_msg = "'in <string>' requires string as left operand, not NoneType" if is_cpython else "'NoneType' does not have the buffer interface"

Expand Down Expand Up @@ -605,8 +605,8 @@ def test_that_something_iterable_matches_another():
"that(something_iterable).matches(another_iterable)"

# types must be unicode in py3, bute bytestrings in py2
KlassOne = type('KlassOne' if PY3 else b'KlassOne', (object,), {})
KlassTwo = type('KlassTwo' if PY3 else b'KlassTwo', (object,), {})
KlassOne = type(b'KlassOne' if PY2 else 'KlassOne', (object,), {})
KlassTwo = type(b'KlassTwo' if PY2 else 'KlassTwo', (object,), {})
one = [
("/1", KlassOne),
("/2", KlassTwo),
Expand Down
12 changes: 6 additions & 6 deletions tests/test_safe_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from __future__ import unicode_literals

from six import PY3
from six import PY2

from sure import expect
from sure.core import safe_repr
Expand Down Expand Up @@ -41,11 +41,11 @@ def __init__(self, x):
self.x = x

def __repr__(self):
if PY3:
# PY3K should return the regular (unicode) string
return self.x
else:
if PY2:
# PY2 should return the regular (unicode) string
return self.x.encode('utf-8')
else:
return self.x

def __eq__(self, other):
return self.x == other.x
Expand All @@ -55,7 +55,7 @@ def __eq__(self, other):
'b': Y('Gabriel Falcão'),
'c': 'Foo',
}
name = 'Gabriel Falcão' if PY3 else 'Gabriel Falc\xe3o'
name = 'Gabriel Falc\xe3o' if PY2 else 'Gabriel Falcão'

expect(safe_repr(y1)).should.equal(compat_repr(
"{'a': 2, 'b': %s, 'c': 'Foo'}" % name
Expand Down

0 comments on commit dfceb6b

Please sign in to comment.