Debian Codegraph @

src/lazr/delegates/tests/test_passthrough.py

raw symbols SCIP
1 # Copyright 2013-2015 Canonical Ltd. All rights reserved.
2 #
3 # This file is part of lazr.delegates.
4 #
5 # lazr.delegates is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, version 3 of the License.
8 #
9 # lazr.delegates is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
12 # License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with lazr.delegates. If not, see <http://www.gnu.org/licenses/>.
16
17 """Test the Passthrough implementation."""
18
19 import unittest
20
21 from lazr.delegates import Passthrough
22
23
24 class Base:
25 foo = "foo from Base"
26
27 @classmethod
28 def clsmethod(cls):
29 return cls.__name__
30
31
32 class TestPassthrough(unittest.TestCase):
33 def setUp(self):
34 self.p = Passthrough("foo", "mycontext")
35 self.p2 = Passthrough("clsmethod", "mycontext")
36
37 self.base = Base()
38
39 class Adapter:
40 mycontext = self.base
41
42 self.Adapter = Adapter
43 self.adapter = Adapter()
44
45 def test_get(self):
46 self.assertEqual(self.p.__get__(self.adapter), "foo from Base")
47 self.assertTrue(self.p.__get__(None, self.Adapter) is self.p)
48 self.assertEqual(self.p2.__get__(self.adapter)(), "Base")
49
50 def test_set(self):
51 self.p.__set__(self.adapter, "new value")
52 self.assertEqual(self.base.foo, "new value")
53
54 def test_no_delete(self):
55 self.assertRaises(NotImplementedError, self.p.__delete__, self.adapter)
56
57 def test_adaptation(self):
58 # Passthrough's third argument (adaptation) is optional and, when
59 # provided, should be a zope.interface.Interface subclass (although in
60 # practice any callable will do) to which the instance is adapted
61 # before getting/setting the delegated attribute.
62 class HasNoFoo:
63 _foo = 1
64
65 no_foo = HasNoFoo()
66 # ... but IHasFooAdapter uses HasNoFoo._foo to provide its own .foo,
67 # so it works like an adapter for HasNoFoo into some interface that
68 # provides a 'foo' attribute.
69
70 class IHasFooAdapter:
71 def __init__(self, inst):
72 self.inst = inst
73
74 @property
75 def foo(self):
76 return self.inst._foo
77
78 @foo.setter
79 def foo(self, value):
80 self.inst._foo = value
81
82 class Example:
83 context = no_foo
84
85 p = Passthrough("foo", "context", adaptation=IHasFooAdapter)
86 e = Example()
87
88 self.assertEqual(p.__get__(e), 1)
89 p.__set__(e, 2)
90 self.assertEqual(p.__get__(e), 2)