示例#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))
示例#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')
示例#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
示例#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}
示例#5
0
文件: hash.py 项目: yoloseem/sider
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)
示例#6
0
文件: utils.py 项目: sublee/attest
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"))
示例#7
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)
示例#8
0
文件: list.py 项目: yoloseem/sider
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]
示例#9
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")
示例#10
0
文件: utils.py 项目: JNRowe/attest
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'))
示例#11
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')
示例#12
0
文件: image.py 项目: 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)
示例#13
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']
示例#14
0
文件: hash.py 项目: yoloseem/sider
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'
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')
示例#16
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 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()))
示例#19
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')
示例#20
0
文件: utils.py 项目: sublee/attest
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
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)
示例#22
0
文件: utils.py 项目: JNRowe/attest
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
示例#23
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) == []
示例#24
0
文件: image.py 项目: 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'))
示例#25
0
文件: types.py 项目: yoloseem/sider
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)
示例#26
0
文件: image.py 项目: 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)
示例#27
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
示例#28
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()',)
示例#29
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)
示例#30
0
文件: image.py 项目: wronglink/wand
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