Ejemplo n.º 1
0
def setdefault_t(session):
    session2 = get_session()
    keyid = key('test_sortedset_setdefault_t')
    set_ = session.set(keyid, {'h': 1, 'o': 2, 'n': 3, 'g': 4}, SortedSet)
    set2 = session2.get(keyid, SortedSet)
    with Transaction(session, [keyid]):
        len(set_)
        val = set_.setdefault('h')
        assert 1 == val
        assert {'h': 1, 'o': 2, 'n': 3, 'g': 4} == dict(set2)
    assert {'h': 1, 'o': 2, 'n': 3, 'g': 4} == dict(set_) == dict(set2)
    with Transaction(session, [keyid]):
        len(set_)
        val = set_.setdefault('h', 123)
        assert 1 == val
        assert {'h': 1, 'o': 2, 'n': 3, 'g': 4} == dict(set2)
    assert {'h': 1, 'o': 2, 'n': 3, 'g': 4} == dict(set_) == dict(set2)
    with Transaction(session, [keyid]):
        len(set_)
        val = set_.setdefault('m')
        assert 1 == val
        assert {'h': 1, 'o': 2, 'n': 3, 'g': 4} == dict(set2)
        with raises(CommitError):
            len(set_)
    assert {'h': 1, 'o': 2, 'n': 3, 'g': 4, 'm': 1} == dict(set_) == dict(set2)
    with Transaction(session, [keyid]):
        len(set_)
        val = set_.setdefault('i', 123)
        assert 123 == val
        assert {'h': 1, 'o': 2, 'n': 3, 'g': 4, 'm': 1} == dict(set2)
        with raises(CommitError):
            len(set_)
    assert ({'h': 1, 'o': 2, 'n': 3, 'g': 4, 'm': 1, 'i': 123}
            == dict(set_) == dict(set2))
Ejemplo n.º 2
0
def setdefault(session):
    set_ = session.set(key('test_sortedset_setdefault'),
                       {'h': 1, 'o': 2, 'n': 3, 'g': 4},
                       SortedSet)
    assert 1 == set_.setdefault('h')
    assert {'h': 1, 'o': 2, 'n': 3, 'g': 4} == dict(set_)
    assert 1 == set_.setdefault('h', 123)
    assert {'h': 1, 'o': 2, 'n': 3, 'g': 4} == dict(set_)
    assert 1 == set_.setdefault('m')
    assert {'h': 1, 'o': 2, 'n': 3, 'g': 4, 'm': 1} == dict(set_)
    assert 123 == set_.setdefault('i', 123)
    assert {'h': 1, 'o': 2, 'n': 3, 'g': 4, 'm': 1, 'i': 123} == dict(set_)
    with raises(TypeError):
        set_.setdefault('e', None)
    with raises(TypeError):
        set_.setdefault('e', '123')
    setx = session.set(key('test_sortedsetx_setdefault'),
                       {100: 1, 200: 2, 300: 3, 400: 4},
                       IntSet)
    assert 1 == setx.setdefault(100)
    assert {100: 1, 200: 2, 300: 3, 400: 4} == dict(setx)
    assert 1 == setx.setdefault(100, 123)
    assert {100: 1, 200: 2, 300: 3, 400: 4} == dict(setx)
    assert 1 == setx.setdefault(500)
    assert {100: 1, 200: 2, 300: 3, 400: 4, 500: 1} == dict(setx)
    assert 123 == setx.setdefault(600, 123)
    assert {100: 1, 200: 2, 300: 3, 400: 4, 500: 1, 600: 123} == dict(setx)
    with raises(TypeError):
        setx.setdefault(700, None)
    with raises(TypeError):
        setx.setdefault(700, '123')
Ejemplo n.º 3
0
def getitem(session):
    set_ = session.set(key('test_sortedset_getitem'), S('abc'), SortedSet)
    assert set_['a'] == 1
    assert set_['b'] == 1
    assert set_['c'] == 1
    with raises(KeyError):
        set_['d']
    with raises(TypeError):
        set_[123]
    set_.update(a=2.1, c=-2)
    assert set_['a'] == 3.1
    assert set_['b'] == 1
    assert set_['c'] == -1
    setx = session.set(key('test_sortedsetx_getitem'), S([1, 2, 3]), IntSet)
    assert setx[1] == 1
    assert setx[2] == 1
    assert setx[3] == 1
    with raises(KeyError):
        setx[4]
    with raises(TypeError):
        setx['a']
    setx.update({1: 2.1, 3: -2})
    assert setx[1] == 3.1
    assert setx[2] == 1
    assert setx[3] == -1
Ejemplo n.º 4
0
def discard_t(session):
    session2 = get_session()
    keyid = key('test_sortedset_discard_t')
    set_ = session.set(keyid, S('abc'), SortedSet)
    set2 = session2.get(keyid, SortedSet)
    with Transaction(session, [keyid]):
        len(set_)
        set_.discard('a')
        assert dict(set2) == {'a': 1, 'b': 1, 'c': 1}
        with raises(CommitError):
            len(set_)
    assert dict(set_) == dict(set2) == {'b': 1, 'c': 1}
    with Transaction(session, [keyid]):
        len(set_)
        set_.discard('d')
        assert dict(set2) == {'b': 1, 'c': 1}
    assert dict(set_) == dict(set2) == {'b': 1, 'c': 1}
    with Transaction(session, [keyid]):
        len(set_)
        set_.discard('b', score=0.5)
        assert dict(set2) == {'b': 1, 'c': 1}
        with raises(CommitError):
            len(set_)
    assert dict(set_) == dict(set2) == {'b': 0.5, 'c': 1}
    with Transaction(session, [keyid]):
        len(set_)
        set_.discard('b', score=0.5, remove=-1)
        assert dict(set2) == {'b': 0.5, 'c': 1}
        with raises(CommitError):
            len(set_)
    assert dict(set_) == dict(set2) == {'b': 0, 'c': 1}
Ejemplo n.º 5
0
def iter_mods():
    core = ["attest"] + [
        "attest." + mod
        for mod in """ast codegen collectors contexts deprecated hook __main__
               reporters run statistics utils pygments""".split()
    ]
    tests = ["attest.tests"] + [
        "attest.tests." + mod
        for mod in """asserts classy collectors contexts hook _meta reporters utils
               dummy dummy.foo""".split()
    ]

    found = list(utils.deep_iter_modules("attest"))
    expected = core + tests
    assert set(expected) == set(found)
    assert len(expected) == len(found)

    found = list(utils.deep_iter_modules("attest.tests"))
    expected = tests
    assert set(expected) == set(found)
    assert len(expected) == len(found)

    found = list(utils.deep_iter_modules("attest.ast"))
    assert found == ["attest.ast"]

    with raises(AttributeError):
        list(utils.deep_iter_modules("attest._nil"))

    with disable_imports("attest"):
        with raises(ImportError):
            list(utils.deep_iter_modules("attest"))
Ejemplo n.º 6
0
def add(session):
    set_ = session.set(key('test_sortedset_add'), S('abc'), SortedSet)
    set_.add('d')
    assert dict(set_) == {'a': 1, 'b': 1, 'c': 1, 'd': 1}
    set_.add('e', score=1.5)
    assert dict(set_) == {'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1.5}
    set_.add('c')
    assert dict(set_) == {'a': 1, 'b': 1, 'c': 2, 'd': 1, 'e': 1.5}
    set_.add('c', score=1.5)
    assert dict(set_) == {'a': 1, 'b': 1, 'c': 3.5, 'd': 1, 'e': 1.5}
    with raises(TypeError):
        set_.add(123)
    with raises(TypeError):
        set_.add('a', score='1.5')
    setx = session.set(key('test_sortedsetx_add'), S([1, 2, 3]), IntSet)
    setx.add(4)
    assert dict(setx) == {1: 1, 2: 1, 3: 1, 4: 1}
    setx.add(5, score=1.5)
    assert dict(setx) == {1: 1, 2: 1, 3: 1, 4: 1, 5: 1.5}
    setx.add(3)
    assert dict(setx) == {1: 1, 2: 1, 3: 2, 4: 1, 5: 1.5}
    setx.add(3, score=1.5)
    assert dict(setx) == {1: 1, 2: 1, 3: 3.5, 4: 1, 5: 1.5}
    with raises(TypeError):
        setx.add('a')
    with raises(TypeError):
        setx.add(1, score='1.5')
Ejemplo n.º 7
0
def delete(session):
    list_ = session.set(key('test_list_delete'), 'abcdefg', List)
    del list_[0]
    assert list('bcdefg') == list(list_)
    del list_[-1]
    assert list('bcdef') == list(list_)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        del list_[2]
        assert len(w) == 1
        assert issubclass(w[0].category, PerformanceWarning)
    assert list('bcef') == list(list_)
    del list_[:]
    with raises(IndexError):
        del list_[-1]
    with raises(IndexError):
        del list_[0]
    listx = session.set(key('test_listx_delete'), range(1, 8), List(NInt))
    del listx[0]
    assert range(2, 8) == list(listx)
    del listx[-1]
    assert range(2, 7) == list(listx)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        del listx[2]
        assert len(w) == 1
        assert issubclass(w[0].category, PerformanceWarning)
    assert [2, 3, 5, 6] == list(listx)
    del listx[:]
    with raises(IndexError):
        del listx[-1]
    with raises(IndexError):
        del listx[0]
Ejemplo n.º 8
0
def pagination():
    class BookTable(tables.Table):
        name = tables.Column()

    # create some sample data
    data = []
    for i in range(100):
        data.append({"name": "Book No. %d" % i})
    books = BookTable(data)

    # external paginator
    paginator = Paginator(books.rows, 10)
    assert paginator.num_pages == 10
    page = paginator.page(1)
    assert page.has_previous() is False
    assert page.has_next() is True

    # integrated paginator
    books.paginate(page=1)
    assert hasattr(books, "page") is True

    books.paginate(page=1, per_page=10)
    assert len(list(books.page.object_list)) == 10

    # new attributes
    assert books.paginator.num_pages == 10
    assert books.page.has_previous() is False
    assert books.page.has_next() is True

    # accessing a non-existant page raises 404
    with raises(EmptyPage):
        books.paginate(Paginator, page=9999, per_page=10)

    with raises(PageNotAnInteger):
        books.paginate(Paginator, page='abc', per_page=10)
def mixed_rules():
    """Keep multiple rules."""

    # Note that if a graph is acyclic, it does not contains interlinks!

    # dry & acyclic
    with empty_relationchecker(relation=u'next_to', dry=True, acyclic=True) as relchkr:
        relchkr.add(u'Tokushima', u'Kouchi')
        with raises(relationprovider.RedundantRelation):
            relchkr.add(u'Tokushima', u'Kouchi')
    with empty_relationchecker(relation=u'next_to', dry=True, acyclic=True) as relchkr:
        relchkr.add(u'Tokushima', u'Kouchi')
        relchkr.add(u'Kouchi', u'Ehime')
        with raises(relationprovider.Cyclic):
            relchkr.add(u'Ehime', u'Tokushima')

    # dry & no interlinks
    with empty_relationchecker(relation=u'next_to', dry=True, nointerlinks=True) as relchkr:
        relchkr.add(u'Shimane', u'Yamaguchi')
        with raises(relationprovider.RedundantRelation):
            relchkr.add(u'Shimane', u'Yamaguchi')
    with empty_relationchecker(relation=u'next_to', dry=True, nointerlinks=True) as relchkr:
        relchkr.add(u'Shimane', u'Yamaguchi')
        relchkr.add(u'Hiroshima', u'Yamaguchi')
        with raises(relationprovider.InterLink):
            relchkr.add(u'Yamaguchi', u'Hiroshima')
Ejemplo n.º 10
0
def test_attributes():
    assert repr(c.foo) == "Attribute[Context[0], 'foo']"
    with attest.raises(AttributeError):
        c.foo = 4
    assert_value(literal({'foo': 12}).foo, 12)
    with attest.raises(KeyError):
        execute(literal({'foo': 12}).bar)
Ejemplo n.º 11
0
def iter_mods():
    core = ['attest.' + mod for mod in
            '''ast codegen collectors contexts deprecated hook __main__ reporters
               run statistics utils pygments'''.split()] + ['attest']
    tests = ['attest.tests.' + mod for mod in
              '''asserts classy collectors contexts hook _meta reporters
                 utils'''.split()] + ['attest.tests']

    found = list(utils.deep_iter_modules('attest'))
    expected = core + tests
    assert set(expected) == set(found)
    assert len(expected) == len(found)

    found = list(utils.deep_iter_modules('attest.tests'))
    expected = tests
    assert set(expected) == set(found)
    assert len(expected) == len(found)

    found = list(utils.deep_iter_modules('attest.ast'))
    assert found == ['attest.ast']

    with raises(AttributeError):
        list(utils.deep_iter_modules('attest._nil'))

    with disable_imports('attest'):
        with raises(ImportError):
            list(utils.deep_iter_modules('attest'))
Ejemplo n.º 12
0
def warns():
    with attest.warns(UserWarning) as captured:
        warnings.warn("foo")
        warnings.warn("bar", DeprecationWarning)

    assert len(captured) == 1
    assert unicode(captured[0]) == "foo"

    with attest.raises(AssertionError):
        with attest.warns(UserWarning):
            pass

    with attest.raises(AssertionError):
        with attest.warns(UserWarning, DeprecationWarning):
            warnings.warn("foo")

    with attest.warns(UserWarning, DeprecationWarning, any=True):
        warnings.warn("foo")

    if hasattr(warnings, "catch_warnings"):  # not available in Python 2.5
        with warnings.catch_warnings():
            warnings.simplefilter("error", UserWarning)
            with attest.warns(UserWarning):
                warnings.warn("foo")
            with attest.raises(UserWarning):
                warnings.warn("bar")
Ejemplo n.º 13
0
Archivo: image.py Proyecto: jokull/wand
def crop_error():
    """Crop errors."""
    with Image(filename=asset('croptest.png')) as img:
        with raises(TypeError):
            img.crop(right=1, width=2)
        with raises(TypeError):
            img.crop(bottom=1, height=2)
def add_nodes():
    """(.*)NodeProvider.add."""

    with empty_rdflib_nodeprovider() as provider:

        # additions & returned values
        for name in Fixtures.simple_nodenames.formalized_map:
            ret = provider.add(name)
            formalized_name = Fixtures.simple_nodenames.formalized_map[name]
            assert isinstance(ret, provider.classes['bnode'])
            assert getattr(provider.ns, formalized_name) == ret
            assert formalized_name in provider.ns
            assert (
                (ret, rdflib.RDFS.label, rdflib.Literal(name))
                in list(provider.graph.triples((None, None, None)))
            )
            assert provider.get(name) == ret
            # reverse lookup
            assert provider.get_identifier_from(ret) == formalized_name
            assert provider.get_origin_name_from(ret) == name

        # avoiding name conflicts
        with raises(nodeprovider.InvalidName):
            provider.add(Fixtures.simple_nodenames.invalid_name)

        # reference error
        with raises(nodeprovider.NameNotRegistered):
            provider.get(Fixtures.simple_nodenames.invalid_name)

        with raises(nodeprovider.NodeNotRegistered):
            provider.get_identifier_from(rdflib.BNode())
        with raises(nodeprovider.NodeNotRegistered):
            provider.get_origin_name_from(rdflib.BNode())
def handle_kana_name_addition():
    """
    NameProvider with romanize=True accepts kanji/kana names.
    """
    with empty_nameprovider(romanize=True) as provider:

        # additions & returned values
        for name in Fixtures.kana_kanji_names.formalized_map:
            ret = provider.add(name)
            expected_formalized = Fixtures.kana_kanji_names.formalized_map[name]
            assert ret == expected_formalized

        # avoiding name conflicts
        for name in Fixtures.kana_kanji_names.formalized_map:
            formalized_name = Fixtures.kana_kanji_names.formalized_map[name]
            with raises(nodeprovider.NameConflict):
                provider.add(name)
            with raises(nodeprovider.NameConflict):
                provider.add(formalized_name)

        # namespace & reverse lookup
        namespace = provider.ns
        for name in Fixtures.kana_kanji_names.formalized_map:
            formalized_name = Fixtures.kana_kanji_names.formalized_map[name]
            assert getattr(namespace, formalized_name) == name
            assert provider.get_ns_identifier(name) == formalized_name

        # reference error
        with raises(nodeprovider.NameNotRegistered):
            provider.get_ns_identifier(Fixtures.kana_kanji_names.not_added)

        # property for source texts
        assert (set(provider.origin_names) ==
                set(Fixtures.kana_kanji_names.formalized_map.keys()))
Ejemplo n.º 16
0
def bound_row():
    class SimpleTable(tables.Table):
        name = tables.Column()
        occupation = tables.Column()
        age = tables.Column()

    record = {'name': 'Bradley', 'age': 20, 'occupation': 'programmer'}

    table = SimpleTable([record])
    row = table.rows[0]

    # integer indexing into a row
    assert row[0] == record['name']
    assert row[1] == record['occupation']
    assert row[2] == record['age']

    with raises(IndexError):
        row[3]

    # column name indexing into a row
    assert row['name'] == record['name']
    assert row['occupation'] == record['occupation']
    assert row['age'] == record['age']

    with raises(KeyError):
        row['gamma']
Ejemplo n.º 17
0
def crop_error():
    """Crop errors."""
    with Image(filename=asset('croptest.png')) as img:
        with raises(TypeError):
            img.crop(right=1, width=2)
        with raises(TypeError):
            img.crop(bottom=1, height=2)
Ejemplo n.º 18
0
def discard(session):
    set_ = session.set(key('test_sortedset_discard'), S('abc'), SortedSet)
    set_.discard('a')
    assert dict(set_) == {'b': 1, 'c': 1}
    set_.discard('d')
    assert dict(set_) == {'b': 1, 'c': 1}
    set_.discard('b', score=0.5)
    assert dict(set_) == {'b': 0.5, 'c': 1}
    set_.discard('b', score=0.5, remove=-1)
    assert dict(set_) == {'b': 0, 'c': 1}
    with raises(TypeError):
        set_.discard(123)
    with raises(TypeError):
        set_.discard('a', score='1.5')
    setx = session.set(key('test_sortedsetx_discard'), S([1, 2, 3]), IntSet)
    setx.discard(1)
    assert dict(setx) == {2: 1, 3: 1}
    setx.discard(4)
    assert dict(setx) == {2: 1, 3: 1}
    setx.discard(2, score=0.5)
    assert dict(setx) == {2: 0.5, 3: 1}
    setx.discard(2, score=0.5, remove=-1)
    assert dict(setx) == {2: 0, 3: 1}
    with raises(TypeError):
        setx.discard('a')
    with raises(TypeError):
        setx.discard(1, score='1.5')
Ejemplo n.º 19
0
def warns():
    with attest.warns(UserWarning) as captured:
        warnings.warn("foo")
        warnings.warn("bar", DeprecationWarning)

    assert len(captured) == 1
    assert unicode(captured[0]) == "foo"

    with attest.raises(AssertionError):
        with attest.warns(UserWarning):
            pass

    with attest.raises(AssertionError):
        with attest.warns(UserWarning, DeprecationWarning):
            warnings.warn("foo")

    with attest.warns(UserWarning, DeprecationWarning, any=True):
        warnings.warn("foo")

    if hasattr(warnings, "catch_warnings"):  # not available in Python 2.5
        with warnings.catch_warnings():
            warnings.simplefilter("error", UserWarning)
            with attest.warns(UserWarning):
                warnings.warn("foo")
            with attest.raises(UserWarning):
                warnings.warn("bar")
Ejemplo n.º 20
0
def bound_row():
    class SimpleTable(tables.Table):
        name = tables.Column()
        occupation = tables.Column()
        age = tables.Column()

    record = {'name': 'Bradley', 'age': 20, 'occupation': 'programmer'}

    table = SimpleTable([record])
    row = table.rows[0]

    # integer indexing into a row
    assert row[0] == record['name']
    assert row[1] == record['occupation']
    assert row[2] == record['age']

    with raises(IndexError):
        row[3]

    # column name indexing into a row
    assert row['name']       == record['name']
    assert row['occupation'] == record['occupation']
    assert row['age']        == record['age']

    with raises(KeyError):
        row['gamma']
Ejemplo n.º 21
0
def iter_mods():
    core = ['attest'] + [
        'attest.' + mod
        for mod in '''ast codegen collectors contexts deprecated hook __main__
               reporters run statistics utils pygments'''.split()
    ]
    tests = ['attest.tests'] + [
        'attest.tests.' + mod for mod in
        '''asserts classy collectors contexts hook _meta reporters utils
               dummy dummy.foo'''.split()
    ]

    found = list(utils.deep_iter_modules('attest'))
    expected = core + tests
    assert set(expected) == set(found)
    assert len(expected) == len(found)

    found = list(utils.deep_iter_modules('attest.tests'))
    expected = tests
    assert set(expected) == set(found)
    assert len(expected) == len(found)

    found = list(utils.deep_iter_modules('attest.ast'))
    assert found == ['attest.ast']

    with raises(AttributeError):
        list(utils.deep_iter_modules('attest._nil'))

    with disable_imports('attest'):
        with raises(ImportError):
            list(utils.deep_iter_modules('attest'))
Ejemplo n.º 22
0
def setdefault(session):
    hash_ = session.set(key('test_hash_setdefault'), fixture_a, Hash)
    curval = hash_.setdefault('a', 'would not get changed')
    assert curval == hash_['a'] == 'b'
    assert len(hash_) == 2
    curval = hash_.setdefault('added', 'default value')
    assert len(hash_) == 3
    assert 'added' in hash_
    assert curval == hash_['added'] == 'default value'
    with raises(TypeError):
        hash_.setdefault(1, 'default')
    with raises(TypeError):
        hash_.setdefault('key', 1234)
    hashx = session.set(key('test_hashx_setdefault'), fixture_b, Hash(NInt))
    curval = hashx.setdefault(1, 'would not get changed')
    assert curval == hashx[1] == 'a'
    assert len(hashx) == 2
    curval = hashx.setdefault(1234, 'default value')
    assert len(hashx) == 3
    assert 1234 in hashx
    assert curval == hashx[1234] == 'default value'
    with raises(TypeError):
        hashx.setdefault('invalid', 'default')
    with raises(TypeError):
        hashx.setdefault('key', 1234)
Ejemplo n.º 23
0
def setitem(session):
    hash_ = session.set(key('test_hash_setitem'), fixture_a, Hash)
    hash_['a'] = 'changed'
    assert len(hash_) == 2
    assert hash_['a'] == 'changed'
    assert 'a' in hash_.keys()
    hash_['new'] = 'added'
    assert len(hash_) == 3
    assert hash_['new'] == 'added'
    assert 'new' in hash_.keys()
    with raises(TypeError):
        hash_[1] = 'a'
    with raises(TypeError):
        hash_['abc'] = 1
    hashx = session.set(key('test_hashx_setitem'), fixture_b, Hash(NInt))
    hashx[1] = 'changed'
    assert len(hashx) == 2
    assert hashx[1] == 'changed'
    assert 1 in hashx.keys()
    hashx[1234] = 'added'
    assert len(hashx) == 3
    assert hashx[1234] == 'added'
    assert 1234 in hashx.keys()
    with raises(TypeError):
        hashx[1] = 1234
    with raises(TypeError):
        hashx['invalid'] = 'val'
Ejemplo n.º 24
0
def pagination():
    class BookTable(tables.Table):
        name = tables.Column()

    # create some sample data
    data = []
    for i in range(100):
        data.append({"name": "Book No. %d" % i})
    books = BookTable(data)

    # external paginator
    paginator = Paginator(books.rows, 10)
    assert paginator.num_pages == 10
    page = paginator.page(1)
    assert page.has_previous() is False
    assert page.has_next() is True

    # integrated paginator
    books.paginate(page=1)
    assert hasattr(books, "page") is True

    books.paginate(page=1, per_page=10)
    assert len(list(books.page.object_list)) == 10

    # new attributes
    assert books.paginator.num_pages == 10
    assert books.page.has_previous() is False
    assert books.page.has_next() is True

    # accessing a non-existant page raises 404
    with raises(EmptyPage):
        books.paginate(Paginator, page=9999, per_page=10)

    with raises(PageNotAnInteger):
        books.paginate(Paginator, page='abc', per_page=10)
Ejemplo n.º 25
0
def test_items(tempdir):
    """
    Test the :class:`Item` class.
    """
    binary = StructuredDirectory(tempdir, '{category}/{num}_{name}.bin')
    text = StructuredDirectory(tempdir, '{category}/{num}_{name}.txt')

    with assert_raises(ValueError, 'Missing properties'):
        text.create(category='lipsum')

    with assert_raises(ValueError, 'Unknown properties'):
        text.create(category='lipsum', num='4', name='foo', bang='bar')

    with assert_raises(TypeError, 'must be of type unicode'):
        text.create(category='lipsum', num=4, name='foo')

    with assert_raises(ValueError, 'can not contain a slash'):
        text.create(category='lipsum', num='4', name='foo/bar')

    values = dict(category='lipsum', num='4', name='foo')
    assert Item(binary, values).filename == 'lipsum/4_foo.bin'
    assert Item(text, values).filename == 'lipsum/4_foo.txt'

    # No file created yet
    assert os.listdir(tempdir) == []

    # Create a file directly
    os.mkdir(os.path.join(text.root_dir, 'lipsum'))
    open(os.path.join(text.root_dir, 'lipsum', '4_foo.txt'), 'wb').close()

    # Create a file from an Item
    text.create(category='lipsum', num='5', name='bar').write('BAR')

    item_foo, item_bar, = sorted(text.get_items(),
                                 key=lambda item: item['num'])
    assert len(item_foo) == 3
    assert dict(item_foo) == dict(category='lipsum', num='4', name='foo')
    assert item_foo.read() == ''

    assert len(item_bar) == 3
    assert dict(item_bar) == dict(category='lipsum', num='5', name='bar')
    assert item_bar.read() == 'BAR'

    content = u'Hello, Wörld!'
    with attest.raises(UnicodeError):
        item_foo.write(content)
    item_foo.write(content.encode('utf8'))
    assert item_foo.read().decode('utf8') == content
    item_foo.remove()
    with attest.raises(IOError):
        item_foo.read()
    with attest.raises(OSError):
        item_foo.remove()

    assert [i.filename for i in text.get_items()] == ['lipsum/5_bar.txt']
    item_bar.remove()
    assert [i.filename for i in text.get_items()] == []
    # The 'lipsum' directory was also removed
    assert os.listdir(tempdir) == []
def add_relations_with_rules():
    """(.*)RelationProvider.add / with some restrictions."""

    hyper = rdflib.RDF.type
    context = dict(
        relation=hyper,
        dry=True, acyclic=True, nointerlinks=True,
    )

    unique_nodes = [rdflib.BNode() for i in range(5)]

    # dry
    with empty_rdflib_relationprivider(**context) as provider:
        provider.add(unique_nodes[0], unique_nodes[1])
        with raises(relationprovider.RedundantRelation):
            provider.add(unique_nodes[0], unique_nodes[1])

    # no-interlinks
    with empty_rdflib_relationprivider(**context) as provider:
        provider.add(unique_nodes[0], unique_nodes[1])
        with raises(relationprovider.InterLink):
            provider.add(unique_nodes[1], unique_nodes[0])

    # acyclic
    with empty_rdflib_relationprivider(**context) as provider:
        provider.add(unique_nodes[0], unique_nodes[1])
        provider.add(unique_nodes[1], unique_nodes[4])
        provider.add(unique_nodes[4], unique_nodes[2])
        with raises(relationprovider.Cyclic):
            provider.add(unique_nodes[2], unique_nodes[0])

    # acyclic + identifier labels
    entries = [
        u'Kagoshima',
        u'Miyazaki',
        u'Ohita',
        u'Fukuoka',
        u'Kumamoto',
    ]
    data = {e: rdflib.BNode() for e in entries}
    with empty_rdflib_relationprivider(**context) as provider:
        for src, dest in zip(entries, entries[1:]):
            provider.add(
                data[src], data[dest],
                src_id=src, dest_id=dest,
            )

        kumamoto = u'Kumamoto'
        kagoshima = u'Kagoshima'
        with raises(relationprovider.Cyclic) as error:
            provider.add(
                data[kumamoto], data[kagoshima],
                src_id=kumamoto, dest_id=kagoshima,
            )

        error_prepend = u'cyclic path found on "{}": '.format(hyper)
        empty, error_prepend, path = error.custom_msg.partition(error_prepend)
        traced_path = path.split(u' -> ')
        assert set(traced_path) == set(entries)
Ejemplo n.º 27
0
def nesting_contexts():

    signals = []

    @contextmanager
    def one():
        signals.append("inner one")
        try:
            yield "one"
        finally:
            signals.append("outer one")

    @contextmanager
    def two():
        signals.append("inner two")
        try:
            yield "two"
        finally:
            signals.append("outer two")

    ctx = utils.nested([one, two])
    assert not signals

    with raises(ZeroDivisionError):
        with ctx as args:
            assert signals == ["inner one", "inner two"]
            assert args == ["one", "two"]
            1 / 0
    assert signals == ["inner one", "inner two", "outer two", "outer one"]

    args = None
    signals = []

    @contextmanager
    def one():
        signals.append("inner one")
        try:
            yield "one"
        finally:
            signals.append("outer one")

    @contextmanager
    def two():
        signals.append("inner two")
        1 / 0
        try:
            yield "two"
        finally:
            signals.append("outer two")

    ctx = utils.nested([one, two])
    assert not signals

    with raises(ZeroDivisionError):
        with ctx as args:
            pass

    assert signals == ["inner one", "inner two", "outer one"]
    assert args is None
Ejemplo n.º 28
0
def test_items(tempdir):
    """
    Test the :class:`Item` class.
    """
    binary = StructuredDirectory(tempdir, '{category}/{num}_{name}.bin')
    text = StructuredDirectory(tempdir, '{category}/{num}_{name}.txt')

    with assert_raises(ValueError, 'Missing properties'):
        Item(text, dict(category='lipsum'))

    with assert_raises(ValueError, 'Unknown properties'):
        Item(text, dict(category='lipsum', num='4', name='foo', bang='bar'))

    with assert_raises(TypeError, 'must be of type unicode'):
        Item(text, dict(category='lipsum', num=4, name='foo'))

    with assert_raises(ValueError, 'can not contain a slash'):
        Item(text, dict(category='lipsum', num='4', name='foo/bar'))

    values = dict(category='lipsum', num='4', name='foo')
    assert Item(binary, values).filename == 'lipsum/4_foo.bin'
    assert Item(text, values).filename == 'lipsum/4_foo.txt'

    # No file created yet
    assert os.listdir(tempdir) == []

    # Create a file directly
    os.mkdir(os.path.join(text.root_dir, 'lipsum'))
    open(os.path.join(text.root_dir, 'lipsum', '4_foo.txt'), 'wb').close()

    # Create a file from an Item
    Item(text, dict(category='lipsum', num='5', name='bar')).write(b'BAR')

    item_foo, item_bar, = sorted(text.get_items(),
                                 key=lambda item: item['num'])
    assert len(item_foo) == 3
    assert dict(item_foo) == dict(category='lipsum', num='4', name='foo')
    assert item_foo.read() == b''

    assert len(item_bar) == 3
    assert dict(item_bar) == dict(category='lipsum', num='5', name='bar')
    assert item_bar.read() == b'BAR'

    content = 'Hello, Wörld!'
    with attest.raises(UnicodeError, TypeError):
        item_foo.write(content)
    item_foo.write(content.encode('utf8'))
    assert item_foo.read().decode('utf8') == content
    item_foo.remove()
    with attest.raises(IOError):
        item_foo.read()
    with attest.raises(OSError):
        item_foo.remove()

    assert [i.filename for i in text.get_items()] == ['lipsum/5_bar.txt']
    item_bar.remove()
    assert [i.filename for i in text.get_items()] == []
    # The 'lipsum' directory was also removed
    assert os.listdir(tempdir) == []
Ejemplo n.º 29
0
def nesting_contexts():

    signals = []

    @contextmanager
    def one():
        signals.append('inner one')
        try:
            yield 'one'
        finally:
            signals.append('outer one')

    @contextmanager
    def two():
        signals.append('inner two')
        try:
            yield 'two'
        finally:
            signals.append('outer two')

    ctx = utils.nested([one, two])
    assert not signals

    with raises(ZeroDivisionError):
        with ctx as args:
            assert signals == ['inner one', 'inner two']
            assert args == ['one', 'two']
            1 / 0
    assert signals == ['inner one', 'inner two', 'outer two', 'outer one']

    args = None
    signals = []

    @contextmanager
    def one():
        signals.append('inner one')
        try:
            yield 'one'
        finally:
            signals.append('outer one')

    @contextmanager
    def two():
        signals.append('inner two')
        1 / 0
        try:
            yield 'two'
        finally:
            signals.append('outer two')

    ctx = utils.nested([one, two])
    assert not signals

    with raises(ZeroDivisionError):
        with ctx as args:
            pass

    assert signals == ['inner one', 'inner two', 'outer one']
    assert args is None
Ejemplo n.º 30
0
def nesting_contexts():

    signals = []

    @contextmanager
    def one():
        signals.append('inner one')
        try:
            yield 'one'
        finally:
            signals.append('outer one')

    @contextmanager
    def two():
        signals.append('inner two')
        try:
            yield 'two'
        finally:
            signals.append('outer two')

    ctx = utils.nested([one, two])
    assert not signals

    with raises(ZeroDivisionError):
        with ctx as args:
            assert signals == ['inner one', 'inner two']
            assert args == ['one', 'two']
            1/0
    assert signals == ['inner one', 'inner two', 'outer two', 'outer one']

    args = None
    signals = []

    @contextmanager
    def one():
        signals.append('inner one')
        try:
            yield 'one'
        finally:
            signals.append('outer one')

    @contextmanager
    def two():
        signals.append('inner two')
        1/0
        try:
            yield 'two'
        finally:
            signals.append('outer two')

    ctx = utils.nested([one, two])
    assert not signals

    with raises(ZeroDivisionError):
        with ctx as args:
            pass

    assert signals == ['inner one', 'inner two', 'outer one']
    assert args is None
Ejemplo n.º 31
0
def date(session):
    date = session.set(key('test_types_date'), datetime.date(1988, 8, 4), Date)
    assert date == datetime.date(1988, 8, 4)
    with raises(TypeError):
        session.set(key('test_types_date'), 1234, Date)
    session.set(key('test_types_date'), '19880804', ByteString)
    with raises(ValueError):
        session.get(key('test_types_date'), Date)
Ejemplo n.º 32
0
Archivo: image.py Proyecto: jokull/wand
def new_from_filename():
    """Opens an image through its filename."""
    with Image(filename=asset('mona-lisa.jpg')) as img:
        assert img.width == 402
    with raises(ClosedImageError):
        img.wand
    with raises(IOError):
        Image(filename=asset('not-exists.jpg'))
Ejemplo n.º 33
0
Archivo: image.py Proyecto: jokull/wand
def save_error():
    filename = os.path.join(tempfile.mkdtemp(), 'savetest.jpg')
    fileobj = StringIO.StringIO()
    with Image(filename=asset('mona-lisa.jpg')) as orig:
        with raises(TypeError):
            orig.save()
        with raises(TypeError):
            orig.save(filename=filename, file=fileobj)
Ejemplo n.º 34
0
def save_error():
    filename = os.path.join(tempfile.mkdtemp(), 'savetest.jpg')
    fileobj = StringIO.StringIO()
    with Image(filename=asset('mona-lisa.jpg')) as orig:
        with raises(TypeError):
            orig.save()
        with raises(TypeError):
            orig.save(filename=filename, file=fileobj)
Ejemplo n.º 35
0
def new_from_filename():
    """Opens an image through its filename."""
    with Image(filename=asset('mona-lisa.jpg')) as img:
        assert img.width == 402
    with raises(ClosedImageError):
        img.wand
    with raises(IOError):
        Image(filename=asset('not-exists.jpg'))
Ejemplo n.º 36
0
def nodes_cycle_test():
    with raises(TypeError):
        RedisReplication(1)
        RedisReplication([1])
    with raises(ValueError):
        RedisReplication([])
    r = RedisReplication([StrictRedis(), StrictRedis()])
    a, b, c, d = (r.get_node_by_rotation() for e in range(4))
    assert a == c and b == d and a != b
Ejemplo n.º 37
0
def test_one():
    assert_value(SOURCE.filter(c.toto == 'foo').map(c.price).one(), 10)

    with attest.raises(IndexError) as error:
        execute(SOURCE.filter(c.toto == 'fizzbuzz').one())
    assert error.args == ('.one() on an empty sequence',)

    with attest.raises(ValueError) as error:
        execute(SOURCE.filter(c.toto == 'bar').one())
    assert error.args == ('More than one element in .one()',)
Ejemplo n.º 38
0
def render_table_templatetag():
    # ensure it works with a multi-order-by
    request = build_request('/')
    table = CountryTable(MEMORY_DATA, order_by=('name', 'population'))
    RequestConfig(request).configure(table)
    template = Template('{% load django_tables2 %}{% render_table table %}')
    html = template.render(Context({'request': request, 'table': table}))

    root = parse(html)
    assert len(root.findall('.//thead/tr')) == 1
    assert len(root.findall('.//thead/tr/th')) == 4
    assert len(root.findall('.//tbody/tr')) == 4
    assert len(root.findall('.//tbody/tr/td')) == 16
    assert root.find(
        'ul[@class="pagination"]/li[@class="cardinality"]').text == '4 items'

    # no data with no empty_text
    table = CountryTable([])
    template = Template('{% load django_tables2 %}{% render_table table %}')
    html = template.render(
        Context({
            'request': build_request('/'),
            'table': table
        }))
    root = parse(html)
    assert len(root.findall('.//thead/tr')) == 1
    assert len(root.findall('.//thead/tr/th')) == 4
    assert len(root.findall('.//tbody/tr')) == 0

    # no data WITH empty_text
    request = build_request('/')
    table = CountryTable([], empty_text='this table is empty')
    RequestConfig(request).configure(table)
    template = Template('{% load django_tables2 %}{% render_table table %}')
    html = template.render(Context({'request': request, 'table': table}))
    root = parse(html)
    assert len(root.findall('.//thead/tr')) == 1
    assert len(root.findall('.//thead/tr/th')) == 4
    assert len(root.findall('.//tbody/tr')) == 1
    assert len(root.findall('.//tbody/tr/td')) == 1
    assert int(root.find('.//tbody/tr/td').attrib['colspan']) == len(
        root.findall('.//thead/tr/th'))
    assert root.find('.//tbody/tr/td').text == 'this table is empty'

    # variable that doesn't exist (issue #8)
    template = Template('{% load django_tables2 %}'
                        '{% render_table this_doesnt_exist %}')
    with raises(ValueError):
        settings.DEBUG = True
        template.render(Context())

    # Should still be noisy with debug off
    with raises(ValueError):
        settings.DEBUG = False
        template.render(Context())
Ejemplo n.º 39
0
def non_native_behave_like_native_frames():
    # Not the best scenario to test it since not all implementations actually
    # support the `level` argument. But the ones that do, raise `ValueError`.

    with raises(ValueError):
        frames._getframe(999)

    with raises(ValueError):
        import sys

        sys._getframe(999)
Ejemplo n.º 40
0
def non_native_behave_like_native_frames():
    # Not the best scenario to test it since not all implementations actually
    # support the `level` argument. But the ones that do, raise `ValueError`.

    with raises(ValueError):
        frames._getframe(999)

    with raises(ValueError):
        import sys

        sys._getframe(999)
Ejemplo n.º 41
0
def clone():
    """Clones the existing image."""
    funcs = (lambda img: Image(image=img), lambda img: img.clone())
    with Image(filename=asset('mona-lisa.jpg')) as img:
        for func in funcs:
            with func(img) as cloned:
                assert img.wand is not cloned.wand
                assert img.size == cloned.size
            with raises(ClosedImageError):
                cloned.wand
    with raises(ClosedImageError):
        img.wand
Ejemplo n.º 42
0
def blank_image():
    gray = Color('#ccc')
    transparent = Color('transparent')
    with raises(TypeError):
        Image(height=0, filename='/test.png')
    with raises(TypeError):
        Image(width=0, height=0)
    with Image(width=20, height=10) as img:
        assert img[10, 5] == transparent
    with Image(width=20, height=10, background=gray) as img:
        assert img.size == (20, 10)
        assert img[10, 5] == gray
Ejemplo n.º 43
0
def blank_image():
    gray = Color('#ccc')
    transparent = Color('transparent')
    with raises(TypeError):
        Image(height=0, filename='/test.png')
    with raises(TypeError):
        Image(width=0, height=0)
    with Image(width=20, height=10) as img:
        assert img[10, 5] == transparent
    with Image(width=20, height=10, background=gray) as img:
        assert img.size == (20, 10)
        assert img[10, 5] == gray
Ejemplo n.º 44
0
def transform_errors():
    """Tests errors raised by invalid parameters for transform."""
    with Image(filename=asset('mona-lisa.jpg')) as img:
        with raises(TypeError):
            img.transform(crop=500)
        with raises(TypeError):
            img.transform(resize=500)
        with raises(TypeError):
            img.transform(500, 500)
        with raises(ValueError):
            img.transform(crop=u'⚠ ')
        with raises(ValueError):
            img.transform(resize=u'⚠ ')
Ejemplo n.º 45
0
def save_to_filename():
    """Saves an image to the filename."""
    savefile = os.path.join(tempfile.mkdtemp(), 'savetest.jpg')
    with Image(filename=asset('mona-lisa.jpg')) as orig:
        orig.save(filename=savefile)
        with raises(IOError):
            orig.save(filename=os.path.join(savefile, 'invalid.jpg'))
        with raises(TypeError):
            orig.save(filename=1234)
    assert os.path.isfile(savefile)
    with Image(filename=savefile) as saved:
        assert saved.size == (402, 599)
    os.remove(savefile)
Ejemplo n.º 46
0
def convert():
    """Converts the image format."""
    with Image(filename=asset('mona-lisa.jpg')) as img:
        with img.convert('png') as converted:
            assert converted.format == 'PNG'
            strio = StringIO.StringIO()
            converted.save(file=strio)
            strio.seek(0)
            with Image(file=strio) as png:
                assert png.format == 'PNG'
        with raises(ValueError):
            img.convert('HONG')
        with raises(TypeError):
            img.convert(123)
Ejemplo n.º 47
0
    def system(self):

        examples = (
            (['echo', 'ham'], None, 'ham'),
            ('cat', 'foo', 'foo'),
        )
        for cmd, stdin, expected in examples:
            assert helpers.system(cmd, stdin) == expected

        with attest.raises(AcrylamidException):
            helpers.system('false')

        with attest.raises(OSError):
            helpers.system('foo', None)
Ejemplo n.º 48
0
def set_format():
    """Sets the image format."""
    with Image(filename=asset('mona-lisa.jpg')) as img:
        img.format = 'png'
        assert img.format == 'PNG'
        strio = StringIO.StringIO()
        img.save(file=strio)
        strio.seek(0)
        with Image(file=strio) as png:
            assert png.format == 'PNG'
        with raises(ValueError):
            img.format = 'HONG'
        with raises(TypeError):
            img.format = 123
Ejemplo n.º 49
0
def string_importing():
    assert import_dotted_name('attest') is attest
    assert import_dotted_name('attest.tests') is attest.tests
    assert import_dotted_name('attest.utils') is utils
    assert import_dotted_name('attest.utils:import_dotted_name') \
           is import_dotted_name
    assert import_dotted_name('attest.utils.import_dotted_name') \
           is import_dotted_name

    with raises(AttributeError):
        import_dotted_name('attest._nil')

    with raises(ImportError):
        with disable_imports('attest'):
            import_dotted_name('attest')
Ejemplo n.º 50
0
    def recognition(self):

        examples = ['bar', rss, atom]

        for value in examples:
            with attest.raises(imprt.InputError):
                imprt.wordpress(value)
Ejemplo n.º 51
0
def assert_raises(exception_class, message_part):
    """
    Check that an exception is raised and its message contains some string.
    """
    with attest.raises(exception_class) as exception:
        yield
    assert message_part.lower() in exception.args[0].lower()
Ejemplo n.º 52
0
def new_from_file():
    """Opens an image from the file object."""
    with open(asset('mona-lisa.jpg'), 'rb') as f:
        with Image(file=f) as img:
            assert img.width == 402
    with raises(ClosedImageError):
        img.wand
    with open(asset('mona-lisa.jpg'), 'rb') as f:
        strio = StringIO.StringIO(f.read())
    with Image(file=strio) as img:
        assert img.width == 402
    strio.close()
    with raises(ClosedImageError):
        img.wand
    with raises(TypeError):
        Image(file='not file object')
Ejemplo n.º 53
0
def raises():
    try:
        with attest.raises(RuntimeError):
            pass
    except AssertionError, e:
        assert type(e) is AssertionError
        assert str(e) == "didn't raise RuntimeError when expected"
Ejemplo n.º 54
0
def new_with_format():
    with open(asset('google.ico'), 'rb') as f:
        blob = f.read()
    with raises(Exception):
        Image(blob=blob)
    with Image(blob=blob, format='ico') as img:
        assert img.size == (16, 16)
Ejemplo n.º 55
0
def oauth2_requires_argument_sets():
    with raises(TypeError):
        OAuth2()

    # these should be fine
    OAuth2(access_token="foo", token_type="bar")
    OAuth2(client_id="foo", client_secret="bar", refresh_token="baz")
Ejemplo n.º 56
0
def new_from_blob():
    """Opens an image from blob."""
    with open(asset('mona-lisa.jpg'), 'rb') as f:
        blob = f.read()
    with Image(blob=blob) as img:
        assert img.width == 402
    with raises(ClosedImageError):
        img.wand
Ejemplo n.º 57
0
def render_table_templatetag():
    # ensure it works with a multi-order-by
    table = CountryTable(MEMORY_DATA, order_by=('name', 'population'))
    template = Template('{% load django_tables2 %}{% render_table table %}')
    html = template.render(Context({'request': HttpRequest(), 'table': table}))

    root = ET.fromstring(html)
    assert len(root.findall('.//thead/tr')) == 1
    assert len(root.findall('.//thead/tr/th')) == 4
    assert len(root.findall('.//tbody/tr')) == 4
    assert len(root.findall('.//tbody/tr/td')) == 16

    # no data with no empty_text
    table = CountryTable([])
    template = Template('{% load django_tables2 %}{% render_table table %}')
    html = template.render(Context({'request': HttpRequest(), 'table': table}))
    root = ET.fromstring(html)
    assert len(root.findall('.//thead/tr')) == 1
    assert len(root.findall('.//thead/tr/th')) == 4
    assert len(root.findall('.//tbody/tr')) == 0

    # no data WITH empty_text
    table = CountryTable([], empty_text='this table is empty')
    template = Template('{% load django_tables2 %}{% render_table table %}')
    html = template.render(Context({'request': HttpRequest(), 'table': table}))
    root = ET.fromstring(html)
    assert len(root.findall('.//thead/tr')) == 1
    assert len(root.findall('.//thead/tr/th')) == 4
    assert len(root.findall('.//tbody/tr')) == 1
    assert len(root.findall('.//tbody/tr/td')) == 1
    assert int(root.find('.//tbody/tr/td').attrib['colspan']) == len(
        root.findall('.//thead/tr/th'))
    assert root.find('.//tbody/tr/td').text == 'this table is empty'

    # variable that doesn't exist (issue #8)
    template = Template('{% load django_tables2 %}'
                        '{% render_table this_doesnt_exist %}')
    with raises(ValueError):
        settings.DEBUG = True
        template.render(Context())

    # Should still be noisy with debug off
    with raises(ValueError):
        settings.DEBUG = False
        template.render(Context())
Ejemplo n.º 58
0
def make_blob():
    """Makes a blob string."""
    with Image(filename=asset('mona-lisa.jpg')) as img:
        with Image(blob=img.make_blob('png')) as img2:
            assert img2.size == (402, 599)
            assert img2.format == 'PNG'
        assert img.format == 'JPEG'
        with raises(TypeError):
            img.make_blob(123)
Ejemplo n.º 59
0
def use_energy():
    energy = Energy(10, 1000)
    assert energy == 10
    energy.use()
    assert energy == 9
    energy.use(5)
    assert energy == 4
    with raises(ValueError):
        energy.use(5)
Ejemplo n.º 60
0
def save_to_file():
    """Saves an image to the Python file object."""
    buffer = StringIO.StringIO()
    with tempfile.TemporaryFile() as savefile:
        with Image(filename=asset('mona-lisa.jpg')) as orig:
            orig.save(file=savefile)
            orig.save(file=buffer)
            with raises(TypeError):
                orig.save(file='filename')
            with raises(TypeError):
                orig.save(file=1234)
        savefile.seek(0)
        with Image(file=savefile) as saved:
            assert saved.size == (402, 599)
        buffer.seek(0)
        with Image(file=buffer) as saved:
            assert saved.size == (402, 599)
    buffer.close()