Debian Codegraph @

docs/user_guide/plugin_development/testing.rst

raw
1 Testing your plugins
2 ====================
3
4 Just as Errbot has tests that validates that it behaves correctly so should your plugin.
5 Errbot is tested using Python's py.test_ module and because we already provide some
6 utilities for that we highly advise you to use `py.test` too.
7
8 We're going to write a simple plugin named `myplugin.py` with a `MyPlugin` class.
9 It's tests will be stored in `test_myplugin.py` in the same directory.
10
11 Interacting with the bot
12 ------------------------
13
14 Lets go for an example, *myplugin.py*:
15
16 .. code-block:: python
17
18 from errbot import BotPlugin, botcmd
19
20 class MyPlugin(BotPlugin):
21 @botcmd
22 def mycommand(self, message, args):
23 return "This is my awesome command"
24
25 And *myplugin.plug*:
26
27 .. code-block:: ini
28
29 [Core]
30 Name = MyPlugin
31 Module = myplugin
32
33 [Documentation]
34 Description = my plugin
35
36
37 This does absolutely nothing shocking, but how do you test it?
38 We need to interact with the bot somehow, send it `!mycommand` and validate the reply.
39 Fortunately, Errbot provides some help.
40
41
42
43 Our test, *test_myplugin.py*:
44
45 .. code-block:: python
46
47 pytest_plugins = ["errbot.backends.test"]
48
49 extra_plugin_dir = '.'
50
51 def test_command(testbot):
52 testbot.push_message('!mycommand')
53 assert 'This is my awesome command' in testbot.pop_message()
54
55 Lets walk through this line for line. First of all, we specify our pytest fixture location :class:`~errbot.backends.test` in the backends tests, to allow us to spin up a bot for testing purposes and interact with the message queue. To avoid specifying the module in every test module, you can simply place this line in your conftest.py_.
56
57 Then we set `extra_plugin_dir` to `.`, the current directory so that the test bot will pick up on your plugin.
58
59 After that we define our first `test_` method which simply sends a command to the bot using :func:`~errbot.backends.test.TestBot.push_message` and then asserts that the response we expect, *"This is my awesome command"* is in the message we receive from the bot which we get by calling :func:`~errbot.backends.test.TestBot.pop_message`.
60
61 You can assert the response of a command using the method assertInCommand of the testbot. `testbot.assertInCommand('!mycommand', 'This is my awesome command')` to achieve the equivalent of pushing message and asserting the response in the popped message.`
62
63 Helper methods
64 --------------
65
66 Often enough you'll have methods in your plugins that do things for you that are not decorated with `@botcmd` since the user never calls out to these methods directly.
67
68 Such helper methods can be either instance methods, methods that take `self` as the first argument because they need access to data stored on the bot or class or static methods, decorated with either `@classmethod` or `@staticmethod`:
69
70 .. code-block:: python
71
72 class MyPlugin(BotPlugin):
73 @botcmd
74 def mycommand(self, message, args):
75 return self.mycommand_helper()
76
77 @staticmethod
78 def mycommand_helper():
79 return "This is my awesome command"
80
81 The `mycommand_helper` method does not need any information stored on the bot whatsoever or any other bot state. It can function standalone but it makes sense organisation-wise to have it be a member of the `MyPlugin` class.
82
83 Such methods can be tested very easily, without needing a bot:
84
85 .. code-block:: python
86
87 import myplugin
88
89 def test_mycommand_helper():
90 expected = "This is my awesome command"
91 result = myplugin.MyPlugin.mycommand_helper()
92 assert result == expected
93
94 Here we simply import `myplugin` and since it's a `@staticmethod` we can directly access it through `myplugin.MyPlugin.method()`.
95
96 Sometimes however a helper method needs information stored on the bot or manipulate some of that so you declare an instance method instead:
97
98 .. code-block:: python
99
100 class MyPlugin(BotPlugin):
101 @botcmd
102 def mycommand(self, message, args):
103 return self.mycommand_helper()
104
105 def mycommand_helper(self):
106 return "This is my awesome command"
107
108 Now what? We can't access the method directly anymore because we need an instance of the bot and the plugin and we can't just send `!mycommand_helper` to the bot, it's not a bot command (and if it were it would be `!mycommand helper` anyway).
109
110 What we need now is get access to the instance of our plugin itself. Fortunately for us, there's a method that can help us do just that:
111
112 .. code-block:: python
113
114 extra_plugin_dir = '.'
115
116 def test_mycommand_helper(testbot):
117 plugin = testbot._bot.plugin_manager.get_plugin_obj_by_name('MyPlugin')
118 expected = "This is my awesome command"
119 result = plugin.mycommand_helper()
120 assert result == expected
121
122 There we go, we first grab our plugin using a helper method on :mod:`~errbot.plugin_manager` and then simply execute the method and compare the result with the expected result. You can also access `@classmethod` or `@staticmethod` methods this way, but you don't have to.
123
124 Sometimes a helper method will be making HTTP or API requests which might not be possible to test directly. In that case, we need to mock that particular method and make it return the expected value without actually making the request.
125
126 .. code-block:: python
127
128 URL = 'http://errbot.io'
129
130 class MyPlugin(BotPlugin):
131 @botcmd
132 def mycommand(self, message, args):
133 return self.mycommand_helper()
134
135 def mycommand_helper(self):
136 return (requests.get(URL).status_code)
137
138 What we need now is to somehow replace the method making the request with our mock object and `inject_mocks` method comes in handy.
139
140 Refer `unittest.mock <https://docs.python.org/3/library/unittest.mock.html>`_ for more information about mock.
141
142 .. code-block:: python
143
144 from unittest.mock import MagicMock
145
146 extra_plugin_dir = '.'
147
148 def test_mycommand_helper(testbot):
149 helper_mock = MagicMock(return_value='200')
150 mock_dict = {'mycommand_helper': helper_mock}
151 testbot.inject_mocks('MyPlugin', mock_dict)
152 testbot.push_message('!mycommand')
153 expected = '200'
154 result = testbot.pop_message()
155 assert result == expected
156
157 Pattern
158 -------
159
160 It's a good idea to split up your plugin in two types of methods, those that directly interact with the user and those that do extra stuff you need.
161
162 If you do this the `@botcmd` methods should only concern themselves with giving output back to the user and calling different other functions it needs in order to fulfill the user's request.
163
164 Try to keep as many helper methods simple, there's nothing wrong with having an extra helper or two to avoid having to nest fifteen if-statements. It becomes more legible, easier to maintain and easier to test.
165
166 If you can, try to make your helper methods `@staticmethod` decorated functions, it's easier to test and you don't need a full running bot for those tests.
167
168 All together now
169 ----------------
170
171 *myplugin.py*:
172
173 .. code-block:: python
174
175 from errbot import BotPlugin, botcmd
176
177 class MyPlugin(BotPlugin):
178 @botcmd
179 def mycommand(self, message, args):
180 return self.mycommand_helper()
181
182 @botcmd
183 def mycommand_another(self, message, args):
184 return self.mycommand_another_helper()
185
186 @staticmethod
187 def mycommand_helper():
188 return "This is my awesome command"
189
190 def mycommand_another_helper(self):
191 return "This is another awesome command"
192
193 *myplugin.plug*:
194
195 .. code-block:: ini
196
197 [Core]
198 Name = MyPlugin
199 Module = myplugin
200
201 [Documentation]
202 Description = my plugin
203
204 *test_myplugin.py*:
205
206 .. code-block:: python
207
208 import myplugin
209
210 extra_plugin_dir = '.'
211
212 def test_mycommand(testbot):
213 testbot.push_message('!mycommand')
214 assert 'This is my awesome command' in testbot.pop_message()
215
216 def test_mycommand_another(testbot):
217 testbot.push_message('!mycommand another')
218 assert 'This is another awesome command' in testbot.pop_message()
219
220 def test_mycommand_helper(testbot):
221 expected = "This is my awesome command"
222 result = myplugin.MyPlugin.mycommand_helper()
223 assert result == expected
224
225 def test_mycommand_another_helper(testbot):
226 plugin = testbot._bot.plugin_manager.get_plugin_obj_by_name('MyPlugin')
227 expected = "This is another awesome command"
228 result = plugin.mycommand_another_helper()
229 assert result == expected
230
231 You can now simply run :command:`py.test` to execute the tests.
232
233 PEP-8 and code coverage
234 -----------------------
235
236 If you feel like it you can also add syntax checkers like `pep8` into the mix to validate your code behaves to certain stylistic best practices set out in PEP-8.
237
238 First, install the pep8 for py.test_: :command:`pip install pytest-pep8`.
239
240 Then, simply add `--pep8` to the test invocation command: `py.test --pep8`.
241
242 You also want to know how well your tests cover you code.
243
244 To that end, install coverage: :command:`pip install coverage` and then run your tests like this: :command:`coverage run --source myplugin -m py.test --pep8`.
245
246 You can now have a look at coverage statistics through :command:`coverage report`::
247
248 Name Stmts Miss Cover
249 -------------------------------
250 myplugin 49 0 100%
251
252 It's also possible to generate an HTML report with :command:`coverage html` and opening the resulting `htmlcov/index.html`.
253
254 Travis and Coveralls
255 --------------------
256
257 Last but not least, you can run your tests on Travis-CI_ so when you update code or others submit pull requests the tests will automatically run confirming everything still works.
258
259 In order to do that you'll need a `.travis.yml` similar to this:
260
261 .. code-block:: yaml
262
263 language: python
264 python:
265 - 3.6
266 - 3.7
267 install:
268 - pip install -q errbot pytest pytest-pep8 --use-wheel
269 - pip install -q coverage coveralls --use-wheel
270 script:
271 - coverage run --source myplugin -m py.test --pep8
272 after_success:
273 - coveralls
274 notifications:
275 email: false
276
277 Most of it is self-explanatory, except for perhaps the `after_success`. The author of this plugin uses Coveralls.io_ to keep track of code coverage so after a successful build we call out to coveralls and upload the statistics. It's for this reason that we `pip install [..] coveralls [..]` in the `.travis.yml`.
278
279 The `-q` flag causes pip to be a lot more quiet and `--use-wheel` will cause pip to use wheels_ if available, speeding up your builds if you happen to depend on something that builds a C-extension.
280
281 Both Travis-CI and Coveralls easily integrate with Github hosted code.
282
283 .. _py.test: http://pytest.org
284 .. _conftest.py: http://doc.pytest.org/en/latest/writing_plugins.html#conftest-py-local-per-directory-plugins
285 .. _Coveralls.io: https://coveralls.io
286 .. _Travis-CI: https://travis-ci.org
287 .. _wheels: http://www.python.org/dev/peps/pep-0427/