Exemple #1
0
def test_reduce_not_too_fat():
    # do not save instance dictionary if not needed
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    od = OrderedDict(pairs)
    assert od.__reduce__()[2] is None
    od.x = 10
    assert od.__reduce__()[2] is not None
def test_pickle_recursive():
    od = OrderedDict()
    od['x'] = od
    rec = pickle.loads(pickle.dumps(od))
    assert list(od.keys()) == list(rec.keys())
    assert od is not rec
    assert rec['x'] is rec
Exemple #3
0
def test_clear():
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    assert len(od) == len(pairs)
    od.clear()
    assert len(od) == 0
def test_reduce_not_too_fat():
    # do not save instance dictionary if not needed
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    od = OrderedDict(pairs)
    assert od.__reduce__()[2] is None
    od.x = 10
    assert od.__reduce__()[2] is not None
def test_clear():
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    assert len(od) == len(pairs)
    od.clear()
    assert len(od) == 0
Exemple #6
0
def test_pickle_recursive():
    od = OrderedDict()
    od['x'] = od
    rec = pickle.loads(pickle.dumps(od))
    assert list(od.keys()) == list(rec.keys())
    assert od is not rec
    assert rec['x'] is rec
Exemple #7
0
def test_iterators(f):
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    assert list(f(od)) == [t[0] for t in f(pairs)]
    assert list(f(od.keys())) == [t[0] for t in f(pairs)]
    assert list(f(od.values())) == [t[1] for t in f(pairs)]
    assert list(f(od.items())) == list(f(pairs))
Exemple #8
0
def test_yaml_linkage():
    # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.
    # In yaml, lists are native but tuples are not.
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    od = OrderedDict(pairs)
    # yaml.dump(od) -->
    # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n  - [b, 2]\n'
    assert all(type(pair) == list for pair in od.__reduce__()[1][0])
def test_yaml_linkage():
    # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.
    # In yaml, lists are native but tuples are not.
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    od = OrderedDict(pairs)
    # yaml.dump(od) -->
    # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n  - [b, 2]\n'
    assert all(type(pair)==list for pair in od.__reduce__()[1][0])
def test_iterators(f):
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    assert list(f(od)) == [t[0] for t in f(pairs)]
    assert list(f(od.keys())) == [t[0] for t in f(pairs)]
    assert list(f(od.values())) == [t[1] for t in f(pairs)]
    assert list(f(od.items())) == list(f(pairs))
def test_delitem():
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    od = OrderedDict(pairs)
    del od['a']
    assert 'a' not in od
    with pytest.raises(KeyError):
        del od['a']
    assert list(od.items()) == pairs[:2] + pairs[3:]
Exemple #12
0
def test_delitem():
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    od = OrderedDict(pairs)
    del od['a']
    assert 'a' not in od
    with pytest.raises(KeyError):
        del od['a']
    assert list(od.items()) == pairs[:2] + pairs[3:]
Exemple #13
0
def test_repr():
    od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5),
                      ('f', 6)])
    assert (
        repr(od) ==
        "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])"
    )
    assert eval(repr(od)) == od
    assert repr(OrderedDict()) == "OrderedDict()"
def test_reinsert():
    # Given insert a, insert b, delete a, re-insert a,
    # verify that a is now later than b.
    od = OrderedDict()
    od['a'] = 1
    od['b'] = 2
    del od['a']
    od['a'] = 1
    assert list(od.items()) == [('b', 2), ('a', 1)]
def test_popitem():
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    while pairs:
        assert od.popitem() == pairs.pop()
    with pytest.raises(KeyError):
        od.popitem()
    assert len(od) == 0
Exemple #16
0
def test_reinsert():
    # Given insert a, insert b, delete a, re-insert a,
    # verify that a is now later than b.
    od = OrderedDict()
    od['a'] = 1
    od['b'] = 2
    del od['a']
    od['a'] = 1
    assert list(od.items()) == [('b', 2), ('a', 1)]
Exemple #17
0
def test_popitem():
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    while pairs:
        assert od.popitem() == pairs.pop()
    with pytest.raises(KeyError):
        od.popitem()
    assert len(od) == 0
Exemple #18
0
def test_od_deepcopy():
    lst = [1, 2, 3]
    od = OrderedDict(a=lst)
    new_od = deepcopy(od)
    new_od['a'].append(4)

    assert od['a'] is lst
    assert lst == [1, 2, 3]
    assert new_od['a'] == [1, 2, 3, 4]
    assert od.keys() == new_od.keys()
Exemple #19
0
def test_od_create():
    od = OrderedDict()
    assert od.keys() == []

    od = OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])
    assert od.keys() == ['a', 'c', 'foo']

    od = OrderedDict(a='b', c='d', foo='bar')
    assert set(od.keys()) == set(['a', 'c', 'foo'])
Exemple #20
0
def test_equality():
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od1 = OrderedDict(pairs)
    od2 = OrderedDict(pairs)
    assert od1 == od2  # same order implies equality
    pairs = pairs[2:] + pairs[:2]
    od2 = OrderedDict(pairs)
    assert od1 != od2  # different order implies inequality
    # comparison to regular dict is not order sensitive
    assert od1 == dict(od2)
    assert dict(od2) == od1
    # different length implied inequality
    assert od1 != OrderedDict(pairs[:-1])
Exemple #21
0
def test_expand_with_both_empty_list_and_values():
    different_orderings = [
        [
            ("categories", '[]'),
            ("categories.0", 'basketball'),
            ("categories.1", '0'),
            ("categories.2", '2'),
        ],
        [
            ("categories.0", 'basketball'),
            ("categories", '[]'),
            ("categories.1", '0'),
            ("categories.2", '2'),
        ],
        [
            ("categories.0", 'basketball'),
            ("categories.1", '0'),
            ("categories.2", '2'),
            ("categories", '[]'),
        ]
    ]
    for ordering in different_orderings:
        flat_data = OrderedDict(ordering)

        expanded = expand(flat_data)
        assert expanded == {
            "categories": {
                "0": "basketball",
                "1": "0",
                "2": "2",
            }
        }
Exemple #22
0
def test_expand_with_both_empty_dict_and_values():
    different_orderings = [
        [
            ("categories", '{}'),
            ("categories.basketball.category_slug", 'basketball'),
            ("categories.basketball.total_draws", '0'),
            ("categories.basketball.total_losses", '2'),
        ],
        [
            ("categories.basketball.category_slug", 'basketball'),
            ("categories", '{}'),
            ("categories.basketball.total_draws", '0'),
            ("categories.basketball.total_losses", '2'),
        ],
        [
            ("categories.basketball.category_slug", 'basketball'),
            ("categories.basketball.total_draws", '0'),
            ("categories.basketball.total_losses", '2'),
            ("categories", '{}'),
        ]
    ]

    for ordering in different_orderings:
        flat_data = OrderedDict(ordering)

        expanded = expand(flat_data)
        assert expanded == {
            "categories": {
                "basketball": {
                    "category_slug": "basketball",
                    "total_draws": "0",
                    "total_losses": "2",
                }
            }
        }
Exemple #23
0
def test_od_reduce():
    od = OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])
    serialized = pickle.dumps(od)
    new_od = pickle.loads(serialized)

    assert od == new_od
    assert isinstance(new_od, OrderedDict)
Exemple #24
0
def test_repr_recursive():
    # See issue #9826
    od = OrderedDict.fromkeys('abc')
    od['x'] = od
    assert repr(
        od
    ) == "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])"
Exemple #25
0
def test_od_popitem():
    od = OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])

    assert od.popitem() == ('a', 'b')
    assert 'a' not in od
    assert od.keys() == ['c', 'foo']

    assert od.popitem() == ('c', 'd')
    assert 'c' not in od
    assert od.keys() == ['foo']

    assert od.popitem() == ('foo', 'bar')
    assert 'foo' not in od
    assert od.keys() == []

    with pytest.raises(KeyError):
        od.popitem()
def test_copying():
    # Check that ordered dicts are copyable, deepcopyable, picklable,
    # and have a repr/eval round-trip
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    od = OrderedDict(pairs)
    def check(dup):
        assert dup is not od
        assert dup == od
    check(od.copy())
    check(copy.copy(od))
    check(copy.deepcopy(od))
    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
        check(pickle.loads(pickle.dumps(od, proto)))
    check(eval(repr(od)))
    update_test = OrderedDict()
    update_test.update(od)
    check(update_test)
    check(OrderedDict(od))
Exemple #27
0
def test_list_coercion():
    field = ListType(StringType)
    assert field(('foobar', )) == ['foobar']
    assert field({-2: 'bar', -1: 'baz', -3: 'foo'}) == ['foo', 'bar', 'baz']
    assert field(OrderedDict([(-2, 'bar'), (-1, 'baz'),
                              (-3, 'foo')])) == ['bar', 'baz', 'foo']
    assert field(set(('foobar', ))) == ['foobar']
    with pytest.raises(ConversionError):
        field('foobar')
    with pytest.raises(ConversionError):
        field(None)
def test_od_popitem():
    od = OrderedDict([("a", "b"), ("c", "d"), ("foo", "bar")])

    assert od.popitem() == ("a", "b")
    assert "a" not in od
    assert od.keys() == ["c", "foo"]

    assert od.popitem() == ("c", "d")
    assert "c" not in od
    assert od.keys() == ["foo"]

    assert od.popitem() == ("foo", "bar")
    assert "foo" not in od
    assert od.keys() == []

    with pytest.raises(KeyError):
        od.popitem()
def test_init():

    with pytest.raises(TypeError):
        OrderedDict([('a', 1), ('b', 2)], None)                                # too many args
    pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
    assert sorted(OrderedDict(dict(pairs)).items()) == pairs                   # dict input
    assert sorted(OrderedDict(**dict(pairs)).items()) == pairs                 # kwds input
    assert list(OrderedDict(pairs).items()) == pairs                           # pairs input
    assert list(OrderedDict(
        [('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5).items()) == pairs  # mixed input

    # make sure no positional args conflict with possible kwdargs
    if PY2 and sys.version_info >= (2, 7, 1) or PY3 and sys.version_info >= (3, 2):
        assert list(OrderedDict(self=42).items()) == [('self', 42)]
        assert list(OrderedDict(other=42).items()) == [('other', 42)]

    with pytest.raises(TypeError):
        OrderedDict(42)
    with pytest.raises(TypeError):
        OrderedDict((), ())
    with pytest.raises(TypeError):
        OrderedDict.__init__()

    # Make sure that direct calls to __init__ do not clear previous contents
    d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)])
    d.__init__([('e', 5), ('f', 6)], g=7, d=4)
    assert (list(d.items()) ==
                    [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
Exemple #30
0
def test_pop():

    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    shuffle(pairs)
    while pairs:
        k, v = pairs.pop()
        assert od.pop(k) == v
    with pytest.raises(KeyError):
        od.pop('xyz')
    assert len(od) == 0
    assert od.pop(k, 12345) == 12345

    # make sure pop still works when __missing__ is defined
    class Missing(OrderedDict):
        def __missing__(self, key):
            return 0

    m = Missing(a=1)
    assert m.pop('b', 5) == 5
    assert m.pop('a', 6) == 1
    assert m.pop('a', 6) == 6
    with pytest.raises(KeyError):
        m.pop('a')
Exemple #31
0
def test_od_pop():
    od = OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])

    assert od.pop('a') == 'b'
    assert 'a' not in od
    assert od.keys() == ['c', 'foo']

    assert od.pop('bar', 1) == 1

    with pytest.raises(KeyError):
        od.pop('bar')
Exemple #32
0
def test_move_to_end():
    od = OrderedDict.fromkeys('abcde')
    assert list(od) == list('abcde')
    od.move_to_end('c')
    assert list(od) == list('abdec')
    od.move_to_end('c', 0)
    assert list(od) == list('cabde')
    od.move_to_end('c', 0)
    assert list(od) == list('cabde')
    od.move_to_end('e')
    assert list(od) == list('cabde')
    with pytest.raises(KeyError):
        od.move_to_end('x')
Exemple #33
0
def test_od_setdefault():
    od = OrderedDict([('a', 'b')])

    assert od.setdefault('foo') is None
    assert od.keys() == ['a', 'foo']

    assert od.setdefault('bar', 'baz') == 'baz'
    assert od.keys() == ['a', 'foo', 'bar']

    assert od.setdefault('a') == 'b'
    assert od == {'a': 'b', 'foo': None, 'bar': 'baz'}
def test_move_to_end():
    od = OrderedDict.fromkeys('abcde')
    assert list(od) == list('abcde')
    od.move_to_end('c')
    assert list(od) == list('abdec')
    od.move_to_end('c', 0)
    assert list(od) == list('cabde')
    od.move_to_end('c', 0)
    assert list(od) == list('cabde')
    od.move_to_end('e')
    assert list(od) == list('cabde')
    with pytest.raises(KeyError):
        od.move_to_end('x')
def test_od_create():
    od = OrderedDict()
    assert od.keys() == []

    od = OrderedDict([("a", "b"), ("c", "d"), ("foo", "bar")])
    assert od.keys() == ["a", "c", "foo"]

    od = OrderedDict(a="b", c="d", foo="bar")
    assert set(od.keys()) == set(["a", "c", "foo"])
def test_pop():

    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    shuffle(pairs)
    while pairs:
        k, v = pairs.pop()
        assert od.pop(k) == v
    with pytest.raises(KeyError):
        od.pop('xyz')
    assert len(od) == 0
    assert od.pop(k, 12345) == 12345

    # make sure pop still works when __missing__ is defined
    class Missing(OrderedDict):
        def __missing__(self, key):
            return 0
    m = Missing(a=1)
    assert m.pop('b', 5) == 5
    assert m.pop('a', 6) == 1
    assert m.pop('a', 6) == 6
    with pytest.raises(KeyError):
        m.pop('a')
def test_od_setdefault():
    od = OrderedDict([("a", "b")])

    assert od.setdefault("foo") is None
    assert od.keys() == ["a", "foo"]

    assert od.setdefault("bar", "baz") == "baz"
    assert od.keys() == ["a", "foo", "bar"]

    assert od.setdefault("a") == "b"
    assert od == {"a": "b", "foo": None, "bar": "baz"}
def test_od_pop():
    od = OrderedDict([("a", "b"), ("c", "d"), ("foo", "bar")])

    assert od.pop("a") == "b"
    assert "a" not in od
    assert od.keys() == ["c", "foo"]

    assert od.pop("bar", 1) == 1

    with pytest.raises(KeyError):
        od.pop("bar")
Exemple #39
0
def test_copying():
    # Check that ordered dicts are copyable, deepcopyable, picklable,
    # and have a repr/eval round-trip
    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    od = OrderedDict(pairs)

    def check(dup):
        assert dup is not od
        assert dup == od

    check(od.copy())
    check(copy.copy(od))
    check(copy.deepcopy(od))
    for proto in range(pickle.HIGHEST_PROTOCOL + 1):
        check(pickle.loads(pickle.dumps(od, proto)))
    check(eval(repr(od)))
    update_test = OrderedDict()
    update_test.update(od)
    check(update_test)
    check(OrderedDict(od))
Exemple #40
0
def test_setdefault():

    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    pair_order = list(od.items())
    assert od.setdefault('a', 10) == 3
    # make sure order didn't change
    assert list(od.items()) == pair_order
    assert od.setdefault('x', 10) == 10
    # make sure 'x' is added to the end
    assert list(od.items())[-1] == ('x', 10)

    # make sure setdefault still works when __missing__ is defined
    class Missing(OrderedDict):
        def __missing__(self, key):
            return 0

    assert Missing().setdefault(5, 9) == 9
def test_setdefault():

    pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
    shuffle(pairs)
    od = OrderedDict(pairs)
    pair_order = list(od.items())
    assert od.setdefault('a', 10) == 3
    # make sure order didn't change
    assert list(od.items()) == pair_order
    assert od.setdefault('x', 10) == 10
    # make sure 'x' is added to the end
    assert list(od.items())[-1] == ('x', 10)

    # make sure setdefault still works when __missing__ is defined
    class Missing(OrderedDict):
        def __missing__(self, key):
            return 0
    assert Missing().setdefault(5, 9) == 9
Exemple #42
0
def test_od_clear():
    od = OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])
    od.clear()

    assert od == {}
Exemple #43
0
def test_od_fromkeys():
    od = OrderedDict.fromkeys(['a', 'b', 'c'], 'foo')

    assert od == {'a': 'foo', 'b': 'foo', 'c': 'foo'}
Exemple #44
0
def test_od_reversed():
    od = OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])

    assert list(reversed(od)) == ['foo', 'c', 'a']
Exemple #45
0
def test_od_delete_key():
    od = OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])
    del od['c']
    assert od.keys() == ['a', 'foo']
def test_od_copy():
    od = OrderedDict([("a", "b"), ("c", "d"), ("foo", object())])
    new_od = od.copy()

    assert od == new_od
    assert od["foo"] is new_od["foo"]
Exemple #47
0
def test_od_copy():
    od = OrderedDict([('a', 'b'), ('c', 'd'), ('foo', object())])
    new_od = od.copy()

    assert od == new_od
    assert od['foo'] is new_od['foo']
Exemple #48
0
def test_repr():
    od = OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])

    assert repr(od) == "OrderedDict([('a', 'b'), ('c', 'd'), ('foo', 'bar')])"
def test_od_clear():
    od = OrderedDict([("a", "b"), ("c", "d"), ("foo", "bar")])
    od.clear()

    assert od == {}
def test_od_update():
    od = OrderedDict()
    with pytest.raises(TypeError):
        od.update([], [])
def test_sort():
    items = []
    for i in range(10):
        items.append((i, 9 - i))

    od = OrderedDict(items)
    od.sort(cmp=lambda x, y: cmp(x[1], y[1]))

    assert od.keys() == range(9, -1, -1)

    items = []
    for i in range(10):
        items.append((9 - i, 9 - i))

    od = OrderedDict(items)
    od.sort()

    assert od.keys() == range(10)

    od = OrderedDict(items)
    od.sort(reverse=True)

    assert od.keys() == range(9, -1, -1)