/
components.txt
executable file
·70 lines (52 loc) · 2.04 KB
/
components.txt
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
69
70
Testing with zope.component
===========================
.. invisible-code-block: python
from nose.plugins.skip import SkipTest
try:
from zope.component import getSiteManager
except ImportError:
raise SkipTest('zope.component unavailable')
from testfixtures.components import TestComponents
.. currentmodule:: testfixtures
`zope.component`__ is a fantastic aspect-oriented library for Python,
however its unit testing support is somewhat convoluted. If you need
to test code that registers adapters, utilities and the like then you
may need to provide a sterile component registry. For historical
reasons, component registries are known as `Site Managers` in
:mod:`zope.component`.
__ http://pypi.python.org/pypi/zope.component
TestFixtures provides the a :class:`~components.TestComponents` helper
which provides just such a sterile registry. It should be instantiated
in your :class:`TestCase`'s :meth:`setUp` method. It's
:meth:`uninstall` method should be called in the test's
:meth:`tearDown` method.
Normally, :meth:`zope.component.getSiteManager` returns whatever
the current registry is. This may be influenced by frameworks that use
:mod:`zope.component` which can means that unit tests have no
baseline to start with:
>>> original = getSiteManager()
>>> print(original)
<BaseGlobalComponents base>
Once we've got a :class:`TestComponents` in place, we know what
we're getting:
>>> components = TestComponents()
>>> getSiteManager()
<Components Testing>
The registry that :func:`getSiteManager` returns is now also
available as an attribute of the :class:`TestComponents`
instance:
>>> getSiteManager() is components.registry
True
It's also empty:
>>> tuple(components.registry.registeredUtilities())
()
>>> tuple(components.registry.registeredAdapters())
()
>>> tuple(components.registry.registeredHandlers())
()
You can do whatever you like with this registry. When you're done,
just call the :meth:`uninstall` method:
>>> components.uninstall()
Now you'll have the original registy back in place:
>>> getSiteManager() is original
True