Imported Upstream version 1.1.2
[platform/upstream/python-nose.git] / functional_tests / doc_tests / test_addplugins / test_addplugins.rst
1 Using custom plugins without setuptools
2 ---------------------------------------
3
4 If you have one or more custom plugins that you'd like to use with nose, but
5 can't or don't want to register that plugin as a setuptools entrypoint, you
6 can use the ``addplugins`` keyword argument to :func:`nose.core.main` or
7 :func:`nose.core.run` to make the plugins available.
8
9 To do this you would construct a launcher script for nose, something like::
10
11   from nose import main
12   from yourpackage import YourPlugin, YourOtherPlugin
13
14   if __name__ == '__main__':
15       nose.main(addplugins=[YourPlugin(), YourOtherPlugin()])
16
17 Here's an example. Say that you don't like the fact that the collect-only
18 plugin outputs 'ok' for each test it finds; instead you want it to output
19 'maybe.' You could modify the plugin itself, or instead, create a Maybe plugin
20 that transforms the output into your desired shape.
21
22 Without the plugin, we get 'ok.'
23
24 >>> import os
25 >>> support = os.path.join(os.path.dirname(__file__), 'support')
26 >>> from nose.plugins.plugintest import run_buffered as run
27 >>> argv = [__file__, '-v', support] # --collect-only
28 >>> run(argv=argv)
29 test.test ... ok
30 <BLANKLINE>
31 ----------------------------------------------------------------------
32 Ran 1 test in ...s
33 <BLANKLINE>
34 OK
35
36 Without '-v', we get a dot.
37
38 >>> run(argv=[__file__, support])
39 .
40 ----------------------------------------------------------------------
41 Ran 1 test in ...s
42 <BLANKLINE>
43 OK
44
45 The plugin is simple. It captures and wraps the test result output stream and
46 replaces 'ok' with 'maybe' and '.' with '?'.
47
48 >>> from nose.plugins.base import Plugin
49 >>> class Maybe(Plugin):
50 ...     def setOutputStream(self, stream):
51 ...         self.stream = stream
52 ...         return self
53 ...     def flush(self):
54 ...         self.stream.flush()
55 ...     def writeln(self, out=""):
56 ...         self.write(out + "\n")
57 ...     def write(self, out):
58 ...         if out == "ok\n":
59 ...             out = "maybe\n"
60 ...         elif out == ".":
61 ...             out = "?"
62 ...         self.stream.write(out)
63
64 To activate the plugin, we pass an instance in the addplugins list.
65
66 >>> run(argv=argv + ['--with-maybe'], addplugins=[Maybe()])
67 test.test ... maybe
68 <BLANKLINE>
69 ----------------------------------------------------------------------
70 Ran 1 test in ...s
71 <BLANKLINE>
72 OK
73
74 >>> run(argv=[__file__, support, '--with-maybe'], addplugins=[Maybe()])
75 ?
76 ----------------------------------------------------------------------
77 Ran 1 test in ...s
78 <BLANKLINE>
79 OK
80