Example #1
0
        def wrap(*args, **kw):
            start = datetime.utcnow()

            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:
                    fmt = '{0}() takes no arguments'
                err = text_type(e)
                if fmt.format(func.__name__) in err:
                    func(*args, **kw)
                else:
                    exc.append(traceback.format_exc())

            except Exception as e:
                exc.append(traceback.format_exc())

            end = datetime.utcnow()
            delta = (end - start)
            took = convert_to(delta.microseconds)
            print(took, timeout)
            assert took < timeout, \
                   '%s did not run within %s %s' % (func.__name__, word, unit)
            if exc:
                raise AssertionError(exc.pop(0))
Example #2
0
def test_that_checking_each_matches():
    "that(iterable).in_each('').equals('value')"

    class animal(object):
        def __init__(self, kind):
            self.attributes = {"class": "mammal", "kind": kind}

    animals = [animal("dog"), animal("cat"), animal("cow"), animal("cow"), animal("cow")]

    assert animals[0].attributes["kind"] != "cow"
    assert animals[1].attributes["kind"] != "cow"

    assert animals[2].attributes["kind"] == "cow"
    assert animals[3].attributes["kind"] == "cow"
    assert animals[4].attributes["kind"] == "cow"

    assert animals[0].attributes["class"] == "mammal"
    assert animals[1].attributes["class"] == "mammal"
    assert animals[2].attributes["class"] == "mammal"
    assert animals[3].attributes["class"] == "mammal"
    assert animals[4].attributes["class"] == "mammal"

    assert that(animals).in_each("attributes['class']").matches("mammal")
    assert that(animals).in_each("attributes['class']").matches(["mammal", "mammal", "mammal", "mammal", "mammal"])

    assert that(animals).in_each("attributes['kind']").matches(["dog", "cat", "cow", "cow", "cow"])

    try:
        assert that(animals).in_each("attributes['kind']").matches(["dog"])
        assert False, "should not reach here"
    except AssertionError as e:
        assert that(text_type(e)).equals(
            "%r has 5 items, but the matching list has 1: %r" % (["dog", "cat", "cow", "cow", "cow"], ["dog"])
        )
Example #3
0
        def wrap(*args, **kw):
            start = datetime.utcnow()

            try:
                func(start, *args, **kw)
            except TypeError as e:
                if PY3:
                    # PY3 has different error message
                    fmt = u'{0}() takes 0 positional arguments but 1 was given'
                else:
                    fmt = u'{0}() takes no arguments'
                err = text_type(e)
                if fmt.format(func.__name__) in err:
                    func(*args, **kw)
                else:
                    exc.append(traceback.format_exc())

            except Exception as e:
                exc.append(traceback.format_exc())

            end = datetime.utcnow()
            delta = (end - start)
            took = convert_to(delta.microseconds)
            print(took, timeout)
            assert took < timeout, \
                   '%s did not run within %s %s' % (func.__name__, word, unit)
            if exc:
                raise AssertionError(exc.pop(0))
Example #4
0
def test_that_none_contains_string():
    "that(None).contains('bungalow')"

    try:
        assert that(None).contains("bungalow")
        assert False, "should not reach here"
    except Exception as e:
        assert_equals(text_type(e), "argument of type 'NoneType' is not iterable")
Example #5
0
    def raises(self, exc, msg=None):
        if not callable(self._src):
            raise TypeError('%r is not callable' % self._src)

        try:
            self._src(*self._callable_args, **self._callable_kw)
        except BaseException as e:
            if isinstance(exc, string_types):
                msg = exc
                exc = type(e)
            
            err = text_type(e)

            if isinstance(exc, type) and issubclass(exc, BaseException):
                if not isinstance(e, exc):
                    raise AssertionError(
                        '%r should raise %r, but raised %r' % (
                            self._src, exc, e.__class__))

                if isinstance(msg, string_types) and msg not in err:
                    raise AssertionError('''
                    %r raised %s, but the exception message does not
                    match.\n\nEXPECTED:\n%s\n\nGOT:\n%s'''.strip() % (
                            self._src,
                            type(e).__name__,
                            msg, err))

            elif isinstance(msg, string_types) and msg not in err:
                raise AssertionError(
                    'When calling %r the exception message does not match. ' \
                    'Expected: %r\n got:\n %r' % (self._src, msg, err))

            else:
                raise e
        else:
            if inspect.isbuiltin(self._src):
                _src_filename = '<built-in function>'
            else:
                _src_filename = _get_file_name(self._src)

            if inspect.isfunction(self._src):
                _src_lineno = _get_line_number(self._src)
                raise AssertionError(
                    'calling function %s(%s at line: "%d") with args %r and kwargs %r did not raise %r' % (
                        self._src.__name__,
                        _src_filename, _src_lineno,
                        self._callable_args,
                        self._callable_kw, exc))
            else:
                raise AssertionError(
                    'at %s:\ncalling %s() with args %r and kwargs %r did not raise %r' % (
                        _src_filename,
                        self._src.__name__,
                        self._callable_args,
                        self._callable_kw, exc))

        return True
Example #6
0
def test_that_none_contains_string():
    "that(None).contains('bungalow')"

    try:
        assert that(None).contains('bungalow')
        assert False, 'should not reach here'
    except Exception as e:
        assert_equals(
            text_type(e),
            u"argument of type 'NoneType' is not iterable",
        )
Example #7
0
def test_word_to_number_fail():
    failed = False
    try:
        sure.word_to_number("twenty")
    except AssertionError as e:
        failed = True
        assert_equals(
            text_type(e), "sure supports only literal numbers from one " 'to twelve, you tried the word "twenty"'
        )

    assert failed, "should raise assertion error"
Example #8
0
def test_word_to_number_fail():
    failed = False
    try:
        sure.word_to_number('twenty')
    except AssertionError as e:
        failed = True
        assert_equals(
            text_type(e),
            'sure supports only literal numbers from one ' \
            'to twelve, you tried the word "twenty"')

    assert failed, 'should raise assertion error'
Example #9
0
    def wrapper(self, *args, **kw):
        value = func(self, *args, **kw)
        msg = "{0}({1}) failed".format(
            func.__name__,
            ", ".join(map(safe_repr, args)),
            ", ".join(["{0}={1}".format(k, safe_repr(kw[k])) for k in kw]),
        )
        if not PY3:
            msg = text_type(msg)

        assert value, msg
        return value
Example #10
0
    def wrapper(self, *args, **kw):
        value = func(self, *args, **kw)
        msg = "{0}({1}) failed".format(
            func.__name__,
            ", ".join(map(safe_repr, args)),
            ", ".join(["{0}={1}".format(k, safe_repr(kw[k])) for k in kw]),
        )
        if not PY3:
            msg = text_type(msg)

        assert value, msg
        return value
Example #11
0
    def raises(self, exc, msg=None):
        if not callable(self._src):
            raise TypeError('%r is not callable' % self._src)

        try:
            self._src(*self._callable_args, **self._callable_kw)
        except BaseException as e:
            if isinstance(exc, string_types):
                msg = exc
                exc = type(e)

            err = text_type(e)

            if isinstance(exc, type) and issubclass(exc, BaseException):
                if not isinstance(e, exc):
                    raise AssertionError(
                        '%r should raise %r, but raised %r:\nORIGINAL EXCEPTION:\n\n%s'
                        %
                        (self._src, exc, e.__class__, traceback.format_exc(e)))

                if isinstance(msg, string_types) and msg not in err:
                    raise AssertionError(
                        '''
                    %r raised %s, but the exception message does not
                    match.\n\nEXPECTED:\n%s\n\nGOT:\n%s'''.strip() %
                        (self._src, type(e).__name__, msg, err))

            elif isinstance(msg, string_types) and msg not in err:
                raise AssertionError(
                    'When calling %r the exception message does not match. ' \
                    'Expected: %r\n got:\n %r' % (self._src, msg, err))

            else:
                raise e
        else:
            if inspect.isbuiltin(self._src):
                _src_filename = '<built-in function>'
            else:
                _src_filename = _get_file_name(self._src)

            if inspect.isfunction(self._src):
                _src_lineno = _get_line_number(self._src)
                raise AssertionError(
                    'calling function %s(%s at line: "%d") with args %r and kwargs %r did not raise %r'
                    % (self._src.__name__, _src_filename, _src_lineno,
                       self._callable_args, self._callable_kw, exc))
            else:
                raise AssertionError(
                    'at %s:\ncalling %s() with args %r and kwargs %r did not raise %r'
                    % (_src_filename, self._src.__name__, self._callable_args,
                       self._callable_kw, exc))

        return True
Example #12
0
def test_raises_with_string():
    "that(callable).raises('message') should compare the message"

    def it_fails():
        assert False, 'should fail with this exception'

    try:
        that(it_fails).raises('wrong msg')
        raise RuntimeError('should not reach here')
    except AssertionError as e:
        assert that(text_type(e)).contains('''EXPECTED:
wrong msg

GOT:
should fail with this exception''')
def test_raises_with_string():
    "that(callable).raises('message') should compare the message"

    def it_fails():
        assert False, 'should fail with this exception'

    try:
        that(it_fails).raises('wrong msg')
        raise RuntimeError('should not reach here')
    except AssertionError as e:
        assert that(text_type(e)).contains('''EXPECTED:
wrong msg

GOT:
should fail with this exception''')
Example #14
0
def test_that_checking_each_matches():
    "that(iterable).in_each('').equals('value')"

    class animal(object):
        def __init__(self, kind):
            self.attributes = {
                'class': 'mammal',
                'kind': kind,
            }

    animals = [
        animal('dog'),
        animal('cat'),
        animal('cow'),
        animal('cow'),
        animal('cow'),
    ]

    assert animals[0].attributes['kind'] != 'cow'
    assert animals[1].attributes['kind'] != 'cow'

    assert animals[2].attributes['kind'] == 'cow'
    assert animals[3].attributes['kind'] == 'cow'
    assert animals[4].attributes['kind'] == 'cow'

    assert animals[0].attributes['class'] == 'mammal'
    assert animals[1].attributes['class'] == 'mammal'
    assert animals[2].attributes['class'] == 'mammal'
    assert animals[3].attributes['class'] == 'mammal'
    assert animals[4].attributes['class'] == 'mammal'

    assert that(animals).in_each("attributes['class']").matches('mammal')
    assert that(animals).in_each("attributes['class']"). \
           matches(['mammal','mammal','mammal','mammal','mammal'])

    assert that(animals).in_each("attributes['kind']"). \
           matches(['dog','cat','cow','cow','cow'])

    try:
        assert that(animals).in_each("attributes['kind']").matches(['dog'])
        assert False, 'should not reach here'
    except AssertionError as e:
        assert that(text_type(e)).equals(
            '%r has 5 items, but the matching list has 1: %r' % (
                ['dog', 'cat', 'cow', 'cow', 'cow'],
                ['dog'],
            ))
def test_that_checking_each_matches():
    "that(iterable).in_each('').equals('value')"
    class animal(object):
        def __init__(self, kind):
            self.attributes = {
                'class': 'mammal',
                'kind': kind,
            }

    animals = [
        animal('dog'),
        animal('cat'),
        animal('cow'),
        animal('cow'),
        animal('cow'),
    ]

    assert animals[0].attributes['kind'] != 'cow'
    assert animals[1].attributes['kind'] != 'cow'

    assert animals[2].attributes['kind'] == 'cow'
    assert animals[3].attributes['kind'] == 'cow'
    assert animals[4].attributes['kind'] == 'cow'

    assert animals[0].attributes['class'] == 'mammal'
    assert animals[1].attributes['class'] == 'mammal'
    assert animals[2].attributes['class'] == 'mammal'
    assert animals[3].attributes['class'] == 'mammal'
    assert animals[4].attributes['class'] == 'mammal'

    assert that(animals).in_each("attributes['class']").matches('mammal')
    assert that(animals).in_each("attributes['class']"). \
           matches(['mammal','mammal','mammal','mammal','mammal'])

    assert that(animals).in_each("attributes['kind']"). \
           matches(['dog','cat','cow','cow','cow'])

    try:
        assert that(animals).in_each("attributes['kind']").matches(['dog'])
        assert False, 'should not reach here'
    except AssertionError as e:
        assert that(text_type(e)).equals(
            '%r has 5 items, but the matching list has 1: %r' % (
                ['dog','cat','cow','cow','cow'], ['dog'],
            )
        )
Example #16
0
    def an(self, klass):
        if isinstance(klass, type):
            class_name = klass.__name__
        elif isinstance(klass, string_types):
            class_name = klass.strip()
        else:
            class_name = text_type(klass)

        is_vowel = class_name[0] in 'aeiou'

        if isinstance(klass, string_types):
            if '.' in klass:
                items = klass.split('.')
                first = items.pop(0)
                if not items:
                    items = [first]
                    first = '_abcoll'
            else:
                if sys.version_info <= (3, 0, 0):
                    first = u'__builtin__'
                else:
                    first = u'builtins'
                items = [klass]

            klass = reduce(getattr, items, __import__(first))

        suffix = is_vowel and "n" or ""

        if self.negative:
            assert not isinstance(
                self.obj, klass), ('expected `{0}` to not be a{1} {2}'.format(
                    self.obj, suffix, class_name))

        else:
            assert isinstance(self.obj,
                              klass), ('expected `{0}` to be a{1} {2}'.format(
                                  self.obj, suffix, class_name))
        return True
Example #17
0
    def an(self, klass):
        if isinstance(klass, type):
            class_name = klass.__name__
        elif isinstance(klass, string_types):
            class_name = klass.strip()
        else:
            class_name = text_type(klass)

        is_vowel = class_name[0] in 'aeiou'

        if isinstance(klass, string_types):
            if '.' in klass:
                items = klass.split('.')
                first = items.pop(0)
                if not items:
                    items = [first]
                    first = '_abcoll'
            else:
                if sys.version_info <= (3, 0, 0):
                    first = '__builtin__'
                else:
                    first = 'builtins'
                items = [klass]

            klass = reduce(getattr, items, __import__(first))

        suffix = is_vowel and "n" or ""

        if self.negative:
            assert not isinstance(self.obj, klass), (
                'expected `{0}` to not be a{1} {2}'.format(
                    self.obj, suffix, class_name))

        else:
            assert isinstance(self.obj, klass), (
                'expected `{0}` to be a{1} {2}'.format(
                    self.obj, suffix, class_name))
        return True
Example #18
0
def test_that_raises():
    "that(callable, with_args=[arg1], and_kwargs={'arg2': 'value'}).raises(SomeException)"
    global called

    called = False

    def function(arg1=None, arg2=None):
        global called
        called = True
        if arg1 == 1 and arg2 == 2:
            raise RuntimeError('yeah, it failed')

        return "OK"

    try:
        function(1, 2)
        assert False, 'should not reach here'

    except RuntimeError as e:
        assert text_type(e) == 'yeah, it failed'

    except Exception:
        assert False, 'should not reach here'

    finally:
        assert called
        called = False

    assert_raises(RuntimeError, function, 1, 2)

    called = False
    assert_equals(function(3, 5), 'OK')
    assert called

    called = False
    assert that(function, with_args=[1], and_kwargs={'arg2': 2}). \
           raises(RuntimeError)
    assert called

    called = False
    assert that(function, with_args=[1], and_kwargs={'arg2': 2}). \
           raises(RuntimeError, 'yeah, it failed')
    assert called

    called = False
    assert that(function, with_args=[1], and_kwargs={'arg2': 2}). \
           raises('yeah, it failed')
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises(RuntimeError)
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises(RuntimeError, 'yeah, it failed')
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises('yeah, it failed')
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises(r'it fail')
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises(RuntimeError, r'it fail')
    assert called
Example #19
0
def test_that_raises():
    "that(callable, with_args=[arg1], and_kwargs={'arg2': 'value'}).raises(SomeException)"

    called = False
    global called

    def function(arg1=None, arg2=None):
        global called
        called = True
        if arg1 == 1 and arg2 == 2:
            raise RuntimeError("yeah, it failed")

        return "OK"

    try:
        function(1, 2)
        assert False, "should not reach here"

    except RuntimeError as e:
        assert text_type(e) == "yeah, it failed"

    except Exception:
        assert False, "should not reach here"

    finally:
        assert called
        called = False

    assert_raises(RuntimeError, function, 1, 2)

    called = False
    assert_equals(function(3, 5), "OK")
    assert called

    called = False
    assert that(function, with_args=[1], and_kwargs={"arg2": 2}).raises(RuntimeError)
    assert called

    called = False
    assert that(function, with_args=[1], and_kwargs={"arg2": 2}).raises(RuntimeError, "yeah, it failed")
    assert called

    called = False
    assert that(function, with_args=[1], and_kwargs={"arg2": 2}).raises("yeah, it failed")
    assert called

    called = False
    assert that(function, with_kwargs={"arg1": 1, "arg2": 2}).raises(RuntimeError)
    assert called

    called = False
    assert that(function, with_kwargs={"arg1": 1, "arg2": 2}).raises(RuntimeError, "yeah, it failed")
    assert called

    called = False
    assert that(function, with_kwargs={"arg1": 1, "arg2": 2}).raises("yeah, it failed")
    assert called

    called = False
    assert that(function, with_kwargs={"arg1": 1, "arg2": 2}).raises(r"it fail")
    assert called

    called = False
    assert that(function, with_kwargs={"arg1": 1, "arg2": 2}).raises(RuntimeError, r"it fail")
    assert called
def test_that_raises():
    "that(callable, with_args=[arg1], and_kwargs={'arg2': 'value'}).raises(SomeException)"
    global called

    called = False

    def function(arg1=None, arg2=None):
        global called
        called = True
        if arg1 == 1 and arg2 == 2:
            raise RuntimeError('yeah, it failed')

        return "OK"

    try:
        function(1, 2)
        assert False, 'should not reach here'

    except RuntimeError as e:
        assert text_type(e) == 'yeah, it failed'

    except Exception:
        assert False, 'should not reach here'

    finally:
        assert called
        called = False

    assert_raises(RuntimeError, function, 1, 2)

    called = False
    assert_equals(function(3, 5), 'OK')
    assert called

    called = False
    assert that(function, with_args=[1], and_kwargs={'arg2': 2}). \
           raises(RuntimeError)
    assert called

    called = False
    assert that(function, with_args=[1], and_kwargs={'arg2': 2}). \
           raises(RuntimeError, 'yeah, it failed')
    assert called

    called = False
    assert that(function, with_args=[1], and_kwargs={'arg2': 2}). \
           raises('yeah, it failed')
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises(RuntimeError)
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises(RuntimeError, 'yeah, it failed')
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises('yeah, it failed')
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises(r'it fail')
    assert called

    called = False
    assert that(function, with_kwargs={'arg1': 1, 'arg2': 2}). \
           raises(RuntimeError, r'it fail')
    assert called