File: test_context.py

package info (click to toggle)
python-formencode 2.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,852 kB
  • sloc: python: 6,772; makefile: 130; sh: 96; javascript: 61
file content (68 lines) | stat: -rw-r--r-- 1,508 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import pytest

from formencode.context import Context, ContextRestoreError

c1 = Context(default=None)
c2 = Context()


def test_one():
    state = c1.set(foo=1)
    assert_is(c1, 'foo', 1)
    state.restore()
    assert_is(c1, 'foo', None)
    state = c1.set(foo=2)
    state2 = c2.set(foo='test')
    assert_is(c1, 'foo', 2)
    assert_is(c2, 'foo', 'test')
    change_state(c1, assert_is, c1, 'foo', 3, foo=3)
    assert_is(c1, 'foo', 2)
    state.restore()
    state2.restore()


def change_state(context, func, *args, **change):
    state = context.set(**change)
    try:
        return func(*args)
    finally:
        state.restore()


def test_fail():
    c3 = Context()
    res1 = c3.set(a=1)
    res2 = c3.set(b=2)
    with pytest.raises(ContextRestoreError):
        res1.restore()
    assert c3.b == 2
    assert c3.a == 1
    res2.restore()
    res1.restore()


def assert_is(ob, attr, value):
    assert getattr(ob, attr) == value


def test_default():
    con = Context()
    res = con.set(a=2)
    con.set_default(a=4, b=1)
    assert con.b == 1
    assert con.a == 2
    res.restore()
    assert con.a == 4


def test_context_manager():
    with c1.set(foo=1):
        assert_is(c1, 'foo', 1)
    assert_is(c1, 'foo', None)
    with c1.set(foo=2), c2.set(foo='test'):
        assert_is(c1, 'foo', 2)
        assert_is(c2, 'foo', 'test')
        change_state(c1, assert_is, c1, 'foo', 3, foo=3)
        assert_is(c1, 'foo', 2)
    assert_is(c1, 'foo', None)
    assert not hasattr(c2, 'foo')