Esempio n. 1
0
 def test_error_call(self):
     """tests that a cleanup generator catches exceptions raised by an iterator and cleans up afterwards"""
     class MyFailingIterator(object):
         def __init__(self):
             self.n = 0
         def __iter__(self):
             return self
         def next(self):
             self.n += 1
             if self.n == 3:
                 raise ValueError("self.n is %s" % self.n)
             return self.n
     i = MyFailingIterator()
     def cleanup():
         cleanup.cleanup_called = True
     cleanup.cleanup_called = False
     g = CleanupIterator.CleanupIterator(i, cleanup)
     def receive(g):
         receive.result = []
         for item in g:
             receive.result.append(item)
     assert raises(ValueError, receive, g)
     assert cleanup.cleanup_called
     assert receive.result == [1, 2]
     # make sure that we do not allow the iterator to continue after an exception has been raised
     assert raises(StopIteration, g.next)
Esempio n. 2
0
    def test_error_call(self):
        """tests that a cleanup generator catches exceptions raised by an iterator and cleans up afterwards"""
        class MyFailingIterator(object):
            def __init__(self):
                self.n = 0

            def __iter__(self):
                return self

            def next(self):
                self.n += 1
                if self.n == 3:
                    raise ValueError("self.n is %s" % self.n)
                return self.n

        i = MyFailingIterator()

        def cleanup():
            cleanup.cleanup_called = True

        cleanup.cleanup_called = False
        g = CleanupIterator.CleanupIterator(i, cleanup)

        def receive(g):
            receive.result = []
            for item in g:
                receive.result.append(item)

        assert raises(ValueError, receive, g)
        assert cleanup.cleanup_called
        assert receive.result == [1, 2]
        # make sure that we do not allow the iterator to continue after an exception has been raised
        assert raises(StopIteration, g.next)
Esempio n. 3
0
 def test_missing_attr(self):
     d = DictUtils.setattrdict()
     d.VaLuE = 5
     assert "HeGeMoNy" not in d.keys()
     assert d.get("HeGeMoNy", 5) == 5
     assert raises(KeyError, d.__getitem__, "HeGeMoNy")
     assert getattr(d, "HeGeMoNy", 9) == 9
     assert raises(AttributeError, getattr, d, "HeGeMoNy")
def test_temperature_converter():
    temp_conv = Converters.TemperatureConverter()
    assert temp_conv.string_to_units(
        'degC') == Converters.TemperatureConverter.CELSIUS
    assert temp_conv.convert_from(32, temp_conv.string_to_units('degF')) == 0
    assert temp_conv.convert_to(0, temp_conv.string_to_units('degF')) == 32

    assert raises(NotImplementedError, temp_conv.convert_from, 32, 'degF')
    assert raises(NotImplementedError, temp_conv.convert_to, 0, 'degC')
Esempio n. 5
0
 def test_decorator_calling_frame_arg(self):
     """tests that a decorated function can get the frame of the calling function"""
     frames_so_far = len(getattr(self.g, "call_frames", []))
     callf_decorator = Decorators.decorator(self.callfdec, ['y', ('z', 3)], calling_frame_arg="calling_frame")
     callf_g = callf_decorator(self.g)
     assert callf_g(100, 4) == 100 + 12 + 25
     assert len(self.g.call_frames) == frames_so_far + 1
     call_frame = self.g.call_frames[-1]
     assert call_frame
     assert call_frame.f_code.co_name == "test_decorator_calling_frame_arg"
     # check that calling_frame can't be overridden
     some_frame = Decorators.inspect.currentframe()
     raises(TypeError, callf_g, 100, 4, calling_frame=some_frame)
     raises(TypeError, callf_g, 100, 4, some_frame)
Esempio n. 6
0
 def test_decorator_lambda_calling_frame_arg(self):
     """tests that a decorated function can get the frame of the calling function when a lambda is being decorated"""
     l = lambda x: x + 21
     frames_so_far = len(getattr(l, "call_frames", []))
     callf_decorator = Decorators.decorator(self.callfdec, ['y', ('z', 3)], calling_frame_arg="calling_frame")
     callf_l = callf_decorator(l)
     assert callf_l(100, 4) == 100 + 12 + 21
     assert len(l.call_frames) == frames_so_far + 1
     call_frame = l.call_frames[-1]
     assert call_frame
     assert call_frame.f_code.co_name == "test_decorator_lambda_calling_frame_arg"
     # check that calling_frame can't be overridden
     some_frame = Decorators.inspect.currentframe()
     raises(TypeError, callf_l, 100, 4, calling_frame=some_frame)
     raises(TypeError, callf_l, 100, 4, some_frame)
Esempio n. 7
0
 def test_decorator_calling_frame_arg(self):
     """tests that a decorated function can get the frame of the calling function"""
     frames_so_far = len(getattr(self.g, "call_frames", []))
     callf_decorator = Decorators.decorator(
         self.callfdec, ['y', ('z', 3)], calling_frame_arg="calling_frame")
     callf_g = callf_decorator(self.g)
     assert callf_g(100, 4) == 100 + 12 + 25
     assert len(self.g.call_frames) == frames_so_far + 1
     call_frame = self.g.call_frames[-1]
     assert call_frame
     assert call_frame.f_code.co_name == "test_decorator_calling_frame_arg"
     # check that calling_frame can't be overridden
     some_frame = Decorators.inspect.currentframe()
     raises(TypeError, callf_g, 100, 4, calling_frame=some_frame)
     raises(TypeError, callf_g, 100, 4, some_frame)
Esempio n. 8
0
 def test_purge(self):
     d = TimeCache.timecache(1)
     d[0] = datetime.datetime.now()
     d[1] = datetime.datetime.now()
     assert d.get(0)
     assert len(d) == 2
     time.sleep(2)
     assert d.get(0) is None
     assert raises(KeyError, lambda: d[0])
     assert not d.has_key(1)
     assert len(d) == 0
     d[2] = datetime.datetime.now()
     assert list(d) == [2]
     assert list(d.keys()) == [2]
     assert None not in d.values()
     assert d.size() == 1
     assert list(d.items())[0][0] == 2
     assert list(d.keys()) == [2]
     assert list(d.values())
     time.sleep(1)
     assert list(d) == []
     d[3] = datetime.datetime.now()
     assert d.popitem()[0] == 3
     d.update({3: 4, 5: 6})
     assert d.setdefault(3, 7) == 4
Esempio n. 9
0
 def test_decorator_lambda_calling_frame_arg(self):
     """tests that a decorated function can get the frame of the calling function when a lambda is being decorated"""
     l = lambda x: x + 21
     frames_so_far = len(getattr(l, "call_frames", []))
     callf_decorator = Decorators.decorator(
         self.callfdec, ['y', ('z', 3)], calling_frame_arg="calling_frame")
     callf_l = callf_decorator(l)
     assert callf_l(100, 4) == 100 + 12 + 21
     assert len(l.call_frames) == frames_so_far + 1
     call_frame = l.call_frames[-1]
     assert call_frame
     assert call_frame.f_code.co_name == "test_decorator_lambda_calling_frame_arg"
     # check that calling_frame can't be overridden
     some_frame = Decorators.inspect.currentframe()
     raises(TypeError, callf_l, 100, 4, calling_frame=some_frame)
     raises(TypeError, callf_l, 100, 4, some_frame)
Esempio n. 10
0
 def test_default_attr(self):
     d = DictUtils.attrdict()
     d.VaLuE = 5
     d.set_default_value(32)
     assert "HeGeMoNy" not in d.keys()
     assert d.get("HeGeMoNy", 5) == 5
     assert raises(KeyError, d.__getitem__, "HeGeMoNy")
     assert getattr(d, "HeGeMoNy") == 32
     assert getattr(d, "HeGeMoNy", 9) == 32
Esempio n. 11
0
 def test_simple_call(self):
     """tests that a cleanup generator runs through an iterator and calls the cleanup at the end"""
     i = iter([1,2,3,4,5])
     def cleanup():
         assert raises(StopIteration, i.next)
         cleanup.cleanup_called = True
     cleanup.cleanup_called = False
     g = CleanupIterator.CleanupIterator(i, cleanup)
     l = list(g)
     assert l == [1,2,3,4,5]
     assert cleanup.cleanup_called
     assert raises(StopIteration, i.next)
Esempio n. 12
0
    def test_dict(self):
        # Make an empty one
        cleand = DictUtils.ordereddict()

        # Make one from another
        k = [5, 1, 2, 3, 7, 6]
        v = ["a", "b", "c", "d", "e", "f"]
        d = DictUtils.ordereddict(DictUtils.ordereddict(list(zip(k, v))))

        def bad_dict():
            d = DictUtils.ordereddict(*k)

        d.setdefault(5, "g")
        assert d.get(5, None) == "a"
        d.update(t="g")
        assert d["t"] == "g"
        d.update([(7, "g")])
        assert d[7] == "g"
        d.update({8: "h"})
        assert d[8] == "h"
        assert raises(TypeError, bad_dict)

        del d[1]
        assert d.keys() == [5, 2, 3, 7, 6, "t", 8]
        copyd = d.copy()

        assert list(copyd.keys()) == [5, 2, 3, 7, 6, "t", 8]
        assert list(copyd.values()) == ["a", "c", "d", "g", "f", "g", "h"]

        assert list(copyd.items())

        assert raises(KeyError, cleand.popitem)
        assert copyd.popitem() == (8, "h")
        assert copyd.pop(9, "default") == "default"
        assert copyd.pop(3) == "d"

        assert copyd.keys() == [5, 2, 7, 6, "t"]
        copyd.clear()
        assert copyd.keys() == []
    def test_empty_call(self):
        """tests that a cleanup generator runs through an empty iterator and calls the cleanup at the end"""
        i = iter([])

        def cleanup():
            assert raises(StopIteration, partial(next, i))
            cleanup.cleanup_called = True

        cleanup.cleanup_called = False
        g = CleanupIterator.CleanupIterator(i, cleanup)
        l = list(g)
        assert l == []
        assert cleanup.cleanup_called
        assert raises(StopIteration, partial(next, i))
Esempio n. 14
0
    def test_simple_call(self):
        """tests that a cleanup generator runs through an iterator and calls the cleanup at the end"""
        i = iter([1, 2, 3, 4, 5])

        def cleanup():
            assert raises(StopIteration, i.next)
            cleanup.cleanup_called = True

        cleanup.cleanup_called = False
        g = CleanupIterator.CleanupIterator(i, cleanup)
        l = list(g)
        assert l == [1, 2, 3, 4, 5]
        assert cleanup.cleanup_called
        assert raises(StopIteration, i.next)
Esempio n. 15
0
 def test_global_disable(self):
     d = TimeCache.timecache(10)
     d[1] = "test"
     assert 1 in d
     TimeCache.GLOBAL_CACHE_DISABLED = True
     assert 1 not in d
     d[2] = "missing"
     assert not list(d.items())
     assert not list(d)
     assert not d.has_key(2)
     assert d.get(2) is None
     assert d.keys() == []
     assert d.values() == []
     d.update({3: 4, 5: 6})
     assert raises(KeyError, lambda: d.popitem())
     assert repr(d) == "<GLOBAL_CACHE_DISABLED>"
     TimeCache.GLOBAL_CACHE_DISABLED = False
     assert d[1] == "test"
     assert 2 not in d
     assert repr(d) != "<GLOBAL_CACHE_DISABLED>"
Esempio n. 16
0
 def test_local_disable(self):
     d = TimeCache.timecache(10)
     e = TimeCache.timecache(10)
     d.LOCAL_CACHE = True
     d[1] = "test"
     e[1] = "test"
     assert 1 in d
     assert 1 in e
     TimeCache.LOCAL_CACHE_DISABLED = True
     assert 1 not in d
     assert 1 in e
     d[2] = "missing"
     e[2] = "missing"
     assert not list(d.items())
     assert sorted(e.items()) == [(1, "test"), (2, "missing")]
     assert raises(KeyError, lambda: d[1])
     TimeCache.LOCAL_CACHE_DISABLED = False
     assert d[1] == "test"
     assert 2 not in d
     assert sorted(e.items()) == [(1, "test"), (2, "missing")]
Esempio n. 17
0
    def test_dict(self):
        """tests the normal dict functions, with thecidict peculiarities"""
        d = DictUtils.cidict({'VaLuE': 5})

        def setvalue(k, v):
            d[k] = v

        def delvalue(k):
            del d[k]

        def invalue(k):
            return k in d

        assert raises(TypeError, lambda: d[5])
        assert raises(IndexError, lambda: d['5'])
        assert raises(TypeError, setvalue, 5, 5)

        d['value'] = 6
        assert d['VaLuE'] == 6

        d.update(vaLue=7)
        assert d['VaLuE'] == 7
        d.update([('VALUE', 8)])
        assert d['VaLuE'] == 8
        d.update({'VAlue': 9})
        assert d['VaLuE'] == 9

        assert raises(TypeError, delvalue, 5)
        assert raises(IndexError, delvalue, '5')
        d['5'] = 5
        del d['5']
        assert d.get('5', None) is None

        assert raises(TypeError, invalue, 5)
        assert 'VALuE' in d
        assert d.has_key('vALUE')
        assert d.get('vaLUE') == 9
Esempio n. 18
0
 def cleanup():
     assert raises(StopIteration, i.next)
     cleanup.cleanup_called = True
Esempio n. 19
0
 def dbonly_test_C(self,db):
     print("C", db)
     if db != 3:
         assert raises(AssertionError, self.checkdb, db)
     else:
         self.checkdb(db)
 def cleanup():
     assert raises(StopIteration, partial(next, i))
     cleanup.cleanup_called = True
Esempio n. 21
0
 def cleanup():
     assert raises(StopIteration, i.next)
     cleanup.cleanup_called = True
Esempio n. 22
0
    def test_assert_dicts_not_equal(self):
        d1 = {1: 2, 3: 4}
        d2 = {1: 2, 3: 4}

        assert raises(AssertionError, DictUtils.assert_dicts_not_equal, d1, d2)
Esempio n. 23
0
 def dbonly_test_C(self, db):
     print("C", db)
     if db != 3:
         assert raises(AssertionError, self.checkdb, db)
     else:
         self.checkdb(db)