Debian Codegraph @

docs/api.rst

raw
1 .. _api:
2
3 ====================
4 Behave API Reference
5 ====================
6
7 This reference is meant for people actually writing step implementations
8 for feature tests. It contains way more information than a typical step
9 implementation will need: most implementations will only need to look at
10 the basic implementation of `step functions`_ and *maybe*
11 `environment file functions`_.
12
13 The model stuff is for people getting really *serious* about their step
14 implementations.
15
16 .. note::
17
18 Anywhere this document says "string" it means "unicode string" in
19 Python 2.x
20
21 *behave* works exclusively with unicode strings internally.
22
23
24 Step Functions
25 ==============
26
27 Step functions are implemented in the Python modules present in your
28 "steps" directory. All Python files (files ending in ".py") in that
29 directory will be imported to find step implementations. They are all
30 loaded before *behave* starts executing your feature tests.
31
32 Step functions are identified using step decorators. All step
33 implementations **should normally** start with the import line:
34
35 .. code-block:: python
36
37 from behave import *
38
39 This line imports several decorators defined by *behave* to allow you to
40 identify your step functions. These are available in both PEP-8 (all
41 lowercase) and traditional (title case) versions: "given", "when", "then"
42 and the generic "step". See the `full list of variables imported`_ in the
43 above statement.
44
45 .. _`full list of variables imported`: #from-behave-import-*
46
47 The decorators all take a single string argument: the string to match
48 against the feature file step text *exactly*. So the following step
49 implementation code:
50
51 .. code-block:: python
52
53 @given('some known state')
54 def step_impl(context):
55 set_up(some, state)
56
57
58 will match the "Given" step from the following feature:
59
60 .. code-block:: gherkin
61
62 Scenario: test something
63 Given some known state
64 then some observed outcome.
65
66 *You don't need to import the decorators*: they're automatically available
67 to your step implementation modules as `global variables`_.
68
69 .. _`global variables`: #step-global-variables
70
71 Steps beginning with "and" or "but" in the feature file are renamed to take
72 the name of their preceding keyword, so given the following feature file:
73
74 .. code-block:: gherkin
75
76 Given some known state
77 and some other known state
78 when some action is taken
79 then some outcome is observed
80 but some other outcome is not observed.
81
82 the first "and" step will be renamed internally to "given" and *behave*
83 will look for a step implementation decorated with either "given" or "step":
84
85 .. code-block:: python
86
87 @given('some other known state')
88 def step_impl(context):
89 set_up(some, other, state)
90
91 and similarly the "but" would be renamed internally to "then". Multiple
92 "and" or "but" steps in a row would inherit the non-"and" or "but" keyword.
93
94 The function decorated by the step decorator will be passed at least one
95 argument. The first argument is always the :class:`~behave.runner.Context`
96 variable. Additional arguments come from `step parameters`_, if any.
97
98
99 Step Parameters
100 ---------------
101
102 You may additionally use `parameters`_ in your step names. These will be
103 handled by either the default simple parser (:pypi:`parse`),
104 its extension "cfparse" or by regular expressions
105 if you invoke :func:`~behave.use_step_matcher`.
106
107 .. _`parameters`: tutorial.html#step-parameters
108
109
110 .. autofunction:: behave.use_step_matcher
111
112 You may add new types to the default parser by invoking
113 :func:`~behave.register_type`.
114
115 .. autofunction:: behave.register_type
116
117 .. hidden:
118
119 # -- SUPERCEEDED BY: behave.register_type documentation
120 An example of this in action could be, in steps.py:
121
122 .. code-block:: python
123
124 from behave import register_type
125 register_type(custom=lambda s: s.upper())
126
127 @given('a string {param:custom} a custom type')
128 def step_impl(context, param):
129 assert param.isupper()
130
131 You may define a new parameter matcher by subclassing
132 :class:`behave.matchers.Matcher` and registering it with
133 :attr:`behave.matchers.matcher_mapping` which is a dictionary of "matcher
134 name" to :class:`~behave.matchers.Matcher` class.
135
136 .. autoclass:: behave.matchers.Matcher
137 :members:
138
139 .. autoclass:: behave.model_core.Argument
140
141 .. autoclass:: behave.matchers.Match
142
143
144 Calling Steps From Other Steps
145 ------------------------------
146
147 If you find you'd like your step implementation to invoke another step you
148 may do so with the :class:`~behave.runner.Context` method
149 :func:`~behave.runner.Context.execute_steps`.
150
151 This function allows you to, for example:
152
153 .. code-block:: python
154
155 @when('I do the same thing as before')
156 def step_impl(context):
157 context.execute_steps(u'''
158 when I press the big red button
159 and I duck
160 ''')
161
162 This will cause the "when I do the same thing as before" step to execute
163 the other two steps as though they had also appeared in the scenario file.
164
165
166 from behave import *
167 --------------------
168
169 The import statement:
170
171 .. code-block:: python
172
173 from behave import *
174
175 is written to introduce a restricted set of variables into your code:
176
177 =========================== =========== ===========================================
178 Name Kind Description
179 =========================== =========== ===========================================
180 given, when, then, step Decorator Decorators for step implementations.
181 use_step_matcher(name) Function Selects current step matcher (parser).
182 register_type(Type=func) Function Registers a type converter.
183 =========================== =========== ===========================================
184
185 See also the description in `step parameters`_.
186
187
188
189 Environment File Functions
190 ==========================
191
192 The environment.py module may define code to run before and after certain
193 events during your testing:
194
195 **before_step(context, step), after_step(context, step)**
196 These run before and after every step. The step passed in is an instance
197 of :class:`~behave.model.Step`.
198
199 **before_scenario(context, scenario), after_scenario(context, scenario)**
200 These run before and after each scenario is run. The scenario passed in is an
201 instance of :class:`~behave.model.Scenario`.
202
203 **before_feature(context, feature), after_feature(context, feature)**
204 These run before and after each feature file is exercised. The feature
205 passed in is an instance of :class:`~behave.model.Feature`.
206
207 **before_tag(context, tag), after_tag(context, tag)**
208 These run before and after a section tagged with the given name. They are
209 invoked for each tag encountered in the order they're found in the
210 feature file. See :ref:`controlling things with tags`. The tag passed in is
211 an instance of :class:`~behave.model.Tag` and because it's a subclass of
212 string you can do simple tests like:
213
214 .. code-block:: python
215
216 # -- ASSUMING: tags @browser.chrome or @browser.any are used.
217 if tag.startswith("browser."):
218 browser_type = tag.replace("browser.", "", 1)
219 if browser_type == "chrome":
220 context.browser = webdriver.Chrome()
221 else:
222 context.browser = webdriver.PlainVanilla()
223
224 **before_all(context), after_all(context)**
225 These run before and after the whole shooting match.
226
227
228 Some Useful Environment Ideas
229 -----------------------------
230
231 Here's some ideas for things you could use the environment for.
232
233 Logging Setup
234 ~~~~~~~~~~~~~~
235
236 The following recipe works in all cases (log-capture on or off).
237 If you want to use/configure logging, you should use the following snippet:
238
239 .. code-block:: python
240
241 # -- FILE:features/environment.py
242 def before_all(context):
243 # -- SET LOG LEVEL: behave --logging-level=ERROR ...
244 # on behave command-line or in "behave.ini".
245 context.config.setup_logging()
246
247 # -- ALTERNATIVE: Setup logging with a configuration file.
248 # context.config.setup_logging(configfile="behave_logging.ini")
249
250
251 Capture Logging in Hooks
252 ~~~~~~~~~~~~~~~~~~~~~~~~
253
254 If you wish to capture any logging generated during an environment
255 hook function's invocation, you may use the
256 :func:`~behave.log_capture.capture` decorator, like:
257
258 .. code-block:: python
259
260 # -- FILE:features/environment.py
261 from behave.log_capture import capture
262
263 @capture
264 def after_scenario(context):
265 ...
266
267 This will capture any logging done during the call to *after_scenario*
268 and print it out.
269
270
271 Detecting that user code overwrites behave Context attributes
272 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
273
274 The *context* variable in all cases is an instance of
275 :class:`behave.runner.Context`.
276
277 .. autoclass:: behave.runner.Context
278 :members:
279
280 .. autoclass:: behave.runner.ContextMaskWarning
281
282
283 Fixtures
284 ================
285
286 .. excluded:
287
288 .. automodule:: behave.fixture
289
290 Provide a Fixture
291 ------------------
292
293 .. autofunction:: behave.fixture.fixture
294
295 Use Fixtures
296 ------------------
297
298 .. autofunction:: behave.fixture.use_fixture
299
300 .. autofunction:: behave.fixture.use_fixture_by_tag
301
302 .. autofunction:: behave.fixture.use_composite_fixture_with
303
304
305 Runner Operation
306 ================
307
308 Given all the code that could be run by *behave*, this is the order in
309 which that code is invoked (if they exist.)
310
311 .. parsed-literal::
312
313 before_all
314 for feature in all_features:
315 before_feature
316 for scenario in feature.scenarios:
317 before_scenario
318 for step in scenario.steps:
319 before_step
320 step.run()
321 after_step
322 after_scenario
323 after_feature
324 after_all
325
326 If the feature contains scenario outlines then there is an additional loop
327 over all the scenarios in the outline making the running look like this:
328
329 .. parsed-literal::
330
331 before_all
332 for feature in all_features:
333 before_feature
334 for outline in feature.scenarios:
335 for scenario in outline.scenarios:
336 before_scenario
337 for step in scenario.steps:
338 before_step
339 step.run()
340 after_step
341 after_scenario
342 after_feature
343 after_all
344
345
346 Model Objects
347 =============
348
349 The feature, scenario and step objects represent the information parsed
350 from the feature file. They have a number of common attributes:
351
352 **keyword**
353 "Feature", "Scenario", "Given", etc.
354
355 **name**
356 The name of the step (the text after the keyword.)
357
358 **filename** and **line**
359 The file name (or "<string>") and line number of the statement.
360
361 The structure of model objects parsed from a *feature file* will typically
362 be:
363
364 .. parsed-literal::
365
366 :class:`~behave.model.Tag` (as :py:attr:`Feature.tags`)
367 :class:`~behave.model.Feature` : TaggableModelElement
368 Description (as :py:attr:`Feature.description`)
369
370 :class:`~behave.model.Background`
371 :class:`~behave.model.Step`
372 :class:`~behave.model.Table` (as :py:attr:`Step.table`)
373 MultiLineText (as :py:attr:`Step.text`)
374
375 :class:`~behave.model.Tag` (as :py:attr:`Scenario.tags`)
376 :class:`~behave.model.Scenario` : TaggableModelElement
377 Description (as :py:attr:`Scenario.description`)
378 :class:`~behave.model.Step`
379 :class:`~behave.model.Table` (as :py:attr:`Step.table`)
380 MultiLineText (as :py:attr:`Step.text`)
381
382 :class:`~behave.model.Tag` (as :py:attr:`ScenarioOutline.tags`)
383 :class:`~behave.model.ScenarioOutline` : TaggableModelElement
384 Description (as :py:attr:`ScenarioOutline.description`)
385 :class:`~behave.model.Step`
386 :class:`~behave.model.Table` (as :py:attr:`Step.table`)
387 MultiLineText (as :py:attr:`Step.text`)
388 :class:`~behave.model.Examples`
389 :class:`~behave.model.Table`
390
391
392 .. autoclass:: behave.model.Feature
393
394 .. autoclass:: behave.model.Background
395
396 .. autoclass:: behave.model.Scenario
397
398 .. autoclass:: behave.model.ScenarioOutline
399
400 .. autoclass:: behave.model.Examples
401
402 .. autoclass:: behave.model.Tag
403
404 .. autoclass:: behave.model.Step
405
406 Tables may be associated with either Examples or Steps:
407
408 .. autoclass:: behave.model.Table
409
410 .. autoclass:: behave.model.Row
411
412 And Text may be associated with Steps:
413
414 .. autoclass:: behave.model.Text
415
416
417
418 Logging Capture
419 ===============
420
421 The logging capture *behave* uses by default is implemented by the class
422 :class:`~behave.log_capture.LoggingCapture`. It has methods
423
424 .. autoclass:: behave.log_capture.LoggingCapture
425 :members:
426
427 The *log_capture* module also defines a handy logging capture decorator that's
428 intended to be used on your `environment file functions`_.
429
430 .. autofunction:: behave.log_capture.capture
431
432
433 .. include:: _common_extlinks.rst