Debian Codegraph @

docs/fixtures.rst

raw
1 .. _docid.fixtures:
2
3 Fixtures
4 ==============================================================================
5
6 A common task during test execution is to:
7
8 * setup a functionality when a test-scope is entered
9 * cleanup (or teardown) the functionality at the end of the test-scope
10
11 **Fixtures** are provided as concept to simplify this setup/cleanup task
12 in `behave`_.
13
14
15 Providing a Fixture
16 -------------------
17
18 .. code-block:: python
19
20 # -- FILE: behave4my_project/fixtures.py (or in: features/environment.py)
21 from behave import fixture
22 from somewhere.browser.firefox import FirefoxBrowser
23
24 # -- FIXTURE-VARIANT 1: Use generator-function
25 @fixture
26 def browser_firefox(context, timeout=30, **kwargs):
27 # -- SETUP-FIXTURE PART:
28 context.browser = FirefoxBrowser(timeout, **kwargs)
29 yield context.browser
30 # -- CLEANUP-FIXTURE PART:
31 context.browser.shutdown()
32
33 .. code-block:: python
34
35 # -- FIXTURE-VARIANT 2: Use normal function
36 from somewhere.browser.chrome import ChromeBrowser
37
38 @fixture
39 def browser_chrome(context, timeout=30, **kwargs):
40 # -- SETUP-FIXTURE PART: And register as context-cleanup task.
41 browser = ChromeBrowser(timeout, **kwargs)
42 context.browser = browser
43 context.add_cleanup(browser.shutdown)
44 return browser
45 # -- CLEANUP-FIXTURE PART: browser.shutdown()
46 # Fixture-cleanup is called when current context-layer is removed.
47
48 .. seealso::
49
50 A *fixture* is similar to:
51
52 * a :func:`contextlib.contextmanager`
53 * a `pytest.fixture`_
54 * the `scope guard`_ idiom
55
56 .. include:: _common_extlinks.rst
57
58
59 Using a Fixture
60 ---------------
61
62 In many cases, the usage of a fixture is triggered by the ``fixture-tag``
63 in a feature file. The ``fixture-tag`` marks that a fixture
64 should be used in this scenario/feature (as test-scope).
65
66 .. code-block:: Gherkin
67
68 # -- FILE: features/use_fixture1.feature
69 Feature: Use Fixture on Scenario Level
70
71 @fixture.browser.firefox
72 Scenario: Use Web Browser Firefox
73 Given I load web page "https://somewhere.web"
74 ...
75 # -- AFTER-SCENARIO: Cleanup fixture.browser.firefox
76
77 .. code-block:: Gherkin
78
79 # -- FILE: features/use_fixture2.feature
80 @fixture.browser.firefox
81 Feature: Use Fixture on Feature Level
82
83 Scenario: Use Web Browser Firefox
84 Given I load web page "https://somewhere.web"
85 ...
86
87 Scenario: Another Browser Test
88 ...
89
90 # -- AFTER-FEATURE: Cleanup fixture.browser.firefox
91
92
93 A **fixture** can be used by calling the :func:`~behave.use_fixture()` function.
94 The :func:`~behave.use_fixture()` call performs the ``SETUP-FIXTURE`` part and returns the
95 setup result. In addition, it ensures that ``CLEANUP-FIXTURE`` part is called
96 later-on when the current context-layer is removed.
97 Therefore, any manual cleanup handling in the ``after_tag()`` hook is not necessary.
98
99 .. code-block:: python
100
101 # -- FILE: features/environment.py
102 from behave import use_fixture
103 from behave4my_project.fixtures import browser_firefox
104
105 def before_tag(context, tag):
106 if tag == "fixture.browser.firefox":
107 use_fixture(browser_firefox, context, timeout=10)
108
109
110
111 Realistic Example
112 ~~~~~~~~~~~~~~~~~
113
114 A more realistic example by using a fixture registry is shown below:
115
116 .. code-block:: python
117
118 # -- FILE: features/environment.py
119 from behave.fixture import use_fixture_by_tag, fixture_call_params
120 from behave4my_project.fixtures import browser_firefox, browser_chrome
121
122 # -- REGISTRY DATA SCHEMA 1: fixture_func
123 fixture_registry1 = {
124 "fixture.browser.firefox": browser_firefox,
125 "fixture.browser.chrome": browser_chrome,
126 }
127 # -- REGISTRY DATA SCHEMA 2: (fixture_func, fixture_args, fixture_kwargs)
128 fixture_registry2 = {
129 "fixture.browser.firefox": fixture_call_params(browser_firefox),
130 "fixture.browser.chrome": fixture_call_params(browser_chrome, timeout=12),
131 }
132
133 def before_tag(context, tag):
134 if tag.startswith("fixture."):
135 return use_fixture_by_tag(tag, context, fixture_registry1):
136 # -- MORE: Tag processing steps ...
137
138
139 .. code-block:: python
140
141 # -- FILE: behave/fixture.py
142 # ...
143 def use_fixture_by_tag(tag, context, fixture_registry):
144 fixture_data = fixture_registry.get(tag, None)
145 if fixture_data is None:
146 raise LookupError("Unknown fixture-tag: %s" % tag)
147
148 # -- FOR DATA SCHEMA 1:
149 fixture_func = fixture_data
150 return use_fixture(fixture_func, context)
151
152 # -- FOR DATA SCHEMA 2:
153 fixture_func, fixture_args, fixture_kwargs = fixture_data
154 return use_fixture(fixture_func, context, *fixture_args, **fixture_kwargs)
155
156
157
158 .. hint:: **Naming Convention for Fixture Tags**
159
160 Fixture tags should start with ``"@fixture.*"`` prefix to improve readability
161 and understandibilty in feature files (Gherkin).
162
163 Tags are used for different purposes. Therefore, it should be clear
164 when a ``fixture-tag`` is used.
165
166
167
168 Fixture Cleanup Points
169 ------------------------------------------------------------------------------
170
171 The point when a fixture-cleanup is performed depends on the scope where
172 :func:`~behave.use_fixture()` is called (and the fixture-setup is performed).
173
174
175 ============= =========================== ==========================================================================================
176 Context Layer Fixture-Setup Point Fixture-Cleanup Point
177 ============= =========================== ==========================================================================================
178 test run In ``before_all()`` hook After ``after_all()`` at end of test-run.
179 feature In ``before_feature()`` After ``after_feature()``, at end of feature.
180 feature In ``before_tag()`` After ``after_feature()`` for feature tag.
181 scenario In ``before_scenario()`` After ``after_scenario()``, at end of scenario.
182 scenario In ``before_tag()`` After ``after_scenario()`` for scenario tag.
183 scenario In a step After ``after_scenario()``. Fixture is usable until end of scenario.
184 ============= =========================== ==========================================================================================
185
186
187 Fixture Setup/Cleanup Semantics
188 ------------------------------------------------------------------------------
189
190 If an error occurs during fixture-setup (meaning an exception is raised):
191
192 * Feature/scenario execution is aborted
193 * Any remaining fixture-setups are skipped
194 * After feature/scenario hooks are processed
195 * All fixture-cleanups and context cleanups are performed
196 * The feature/scenario is marked as failed
197
198 If an error occurs during fixture-cleanup (meaning an exception is raised):
199
200 * All remaining fixture-cleanups and context cleanups are performed
201 * First cleanup-error is reraised to pass failure to user (test runner)
202 * The feature/scenario is marked as failed
203
204
205
206 Ensure Fixture Cleanups with Fixture Setup Errors
207 ------------------------------------------------------------------------------
208
209 Fixture-setup errors are special because a cleanup of a fixture is in many
210 cases not necessary (or rather difficult because the fixture object
211 is only partly created, etc.). Therefore, if an error occurs during fixture-setup
212 (meaning: an exception is raised), the fixture-cleanup part is normally not called.
213
214 If you need to ensure that the fixture-cleanup is performed, you need to
215 provide a slightly different fixture implementation:
216
217 .. code-block:: python
218
219 # -- FILE: behave4my_project/fixtures.py (or: features/environment.py)
220 from behave import fixture
221 from somewhere.browser.firefox import FirefoxBrowser
222
223 def setup_fixture_part2_with_error(arg):
224 raise RuntimeError("OOPS-FIXTURE-SETUP-ERROR-HERE)
225
226 # -- FIXTURE-VARIANT 1: Use generator-function with try/finally.
227 @fixture
228 def browser_firefox(context, timeout=30, **kwargs):
229 try:
230 browser = FirefoxBrowser(timeout, **kwargs)
231 browser.part2 = setup_fixture_part2_with_error("OOPS")
232 context.browser = browser # NOT_REACHED
233 yield browser
234 # -- NORMAL FIXTURE-CLEANUP PART: NOT_REACHED due to setup-error.
235 finally:
236 browser.shutdown() # -- CLEANUP: When generator-function is left.
237
238 .. code-block:: python
239
240 # -- FIXTURE-VARIANT 2: Use normal function and register cleanup-task early.
241 from somewhere.browser.chrome import ChromeBrowser
242
243 @fixture
244 def browser_chrome(context, timeout=30, **kwargs):
245 browser = ChromeBrowser(timeout, **kwargs)
246 context.browser = browser
247 context.add_cleanup(browser.shutdown) # -- ENSURE-CLEANUP EARLY
248 browser.part2 = setup_fixture_part2_with_error("OOPS")
249 return browser # NOT_REACHED
250 # -- CLEANUP: browser.shutdown() when context-layer is removed.
251
252 .. note::
253
254 An fixture-setup-error that occurs when the browser object is created,
255 is not covered by these solutions and not so easy to solve.
256
257
258
259 Composite Fixtures
260 ------------------------------------------------------------------------------
261
262 The last section already describes some problems when you use
263 complex or *composite fixtures*. It must be ensured that cleanup of already
264 created fixture parts is performed even when errors occur late in the creation
265 of a *composite fixture*. This is basically a `scope guard`_ problem.
266
267 Solution 1:
268 ~~~~~~~~~~~
269
270 .. code-block:: python
271
272 # -- FILE: behave4my_project/fixtures.py
273 # SOLUTION 1: Use "use_fixture()" to ensure cleanup even in case of errors.
274 from behave import fixture, use_fixture
275
276 @fixture
277 def foo(context, *args, **kwargs):
278 pass # -- FIXTURE IMPLEMENTATION: Not of interest here.
279
280 @fixture
281 def bar(context, *args, **kwargs):
282 pass # -- FIXTURE IMPLEMENTATION: Not of interest here.
283
284 # -- SOLUTION: With use_fixture()
285 # ENSURES: foo-fixture is cleaned up even when setup-error occurs later.
286 @fixture
287 def composite1(context, *args, **kwargs):
288 the_fixture1 = use_fixture(foo, context)
289 the_fixture2 = use_fixture(bar, context)
290 return [the_fixture1, the_fixture2]
291
292
293 Solution 2:
294 ~~~~~~~~~~~
295
296 .. code-block:: python
297
298 # -- ALTERNATIVE SOLUTION: With use_composite_fixture_with()
299 from behave import fixture
300 from behave.fixture import use_composite_fixture_with, fixture_call_params
301
302 @fixture
303 def composite2(context, *args, **kwargs):
304 the_composite = use_composite_fixture_with(context, [
305 fixture_call_params(foo, name="foo"),
306 fixture_call_params(bar, name="bar"),
307 ])
308 return the_composite
309
310