Пример #1
0
    def setUp(self):
        unittest.TestCase.setUp(self)

        # Create the contexts
        self.context = AdaptedDataContext(subcontext=DataContext())
        self.raw_context = self.context.subcontext

        # Add data (before creating the adapter)
        self.context.update(fun=1, bar=2, baz=3, not_mapped=4)

        # Add an adapter
        self.adapter = NameAdapter(map={"foo": "fun", "bar": "baz"})
        self.context.push_adapter(self.adapter)
def test_name_adapter_get_set():

    obj1 = object()
    obj2 = object()
    obj3 = object()

    subcx = DataContext(subcontext=dict(a1=obj1, a2=obj2))

    name_map1 = {
        'b1': 'a1',
        'b2': 'a2',
        'b3': 'a3'  # nonexistent
    }
    name_map2 = {
        'c1': 'b1',
        'c2': 'b2',
        'c3': 'b3',  # eventually nonexistent
    }

    name_adapter1 = NameAdapter(map=name_map1)
    name_adapter2 = NameAdapter(map=name_map2)
    # unit adapter won't do anything, just ensure doesn't block flow or choke.
    unit_adapter = UnitConversionAdapter()
    context = AdaptedDataContext(subcontext=subcx)

    # Note that the adapters are pushed with those closest to the context first.
    # b->a, then c->b. (FIFO, not LIFO)
    context.push_adapter(name_adapter1)
    context.push_adapter(unit_adapter)
    context.push_adapter(name_adapter2)

    # getitem
    assert_equal(context['a1'], obj1)
    assert_equal(context['b1'], obj1)
    assert_equal(context['c1'], obj1)

    assert_equal(context['a2'], obj2)
    assert_equal(context['b2'], obj2)
    assert_equal(context['c2'], obj2)

    # setitem
    context['c2'] = obj3
    assert_equal(context['c2'], obj3)
    assert_equal(context['b2'], obj3)
    assert_equal(context['a2'], obj3)

    assert_equal(context['a1'], obj1)
    assert_equal(context['b1'], obj1)
    assert_equal(context['c1'], obj1)

    # IterableAdaptedDataContext
    context2 = IterableAdaptedDataContext(subcontext=subcx)
    context2.push_adapter(name_adapter1)
    context2.push_adapter(unit_adapter)
    context2.push_adapter(name_adapter2)

    assert_equal(set(context2.keys()), set('a1 a2 b1 b2 c1 c2'.split()))
    assert_equal(set([k for k in context2]), set(context2.keys()))
    for key in context2:
        assert_(key in context2)
    assert_('b3' not in context2)
    assert_('c3' not in context2)