Debian Codegraph @

test/test_runner.py

raw ◀ ▶
Source reconstructed at patch state 0 of 3 — not the installed (fully patched) source.
3 Debian patches touch this file
1 # -*- coding: UTF-8 -*-
2 # pylint: disable=too-many-lines, line-too-long
3
4 from __future__ import absolute_import, print_function, with_statement
5 from collections import defaultdict
6 from platform import python_implementation
7 import os.path
8 import sys
9 import warnings
10 import tempfile
11 import unittest
12 import six
13 from six import StringIO
14
15 from mock import Mock, patch
16 from nose.tools import * # pylint: disable=wildcard-import, unused-wildcard-import
17
18 from behave import runner_util
19 from behave.model import Table
20 from behave.step_registry import StepRegistry
21 from behave import parser, runner
22 from behave.configuration import ConfigError
23 from behave.formatter.base import StreamOpener
24
25
26 # -- CONVENIENCE-ALIAS:
27 _text = six.text_type
28
29
30 class TestContext(unittest.TestCase):
31 # pylint: disable=invalid-name, protected-access, no-self-use
32
33 def setUp(self):
34 r = Mock()
35 self.config = r.config = Mock()
36 r.config.verbose = False
37 self.context = runner.Context(r)
38
39 def test_user_mode_shall_restore_behave_mode(self):
40 # -- CASE: No exception is raised.
41 initial_mode = runner.Context.BEHAVE
42 eq_(self.context._mode, initial_mode)
43 with self.context.use_with_user_mode():
44 eq_(self.context._mode, runner.Context.USER)
45 self.context.thing = "stuff"
46 eq_(self.context._mode, initial_mode)
47
48 def test_user_mode_shall_restore_behave_mode_if_assert_fails(self):
49 initial_mode = runner.Context.BEHAVE
50 eq_(self.context._mode, initial_mode)
51 try:
52 with self.context.use_with_user_mode():
53 eq_(self.context._mode, runner.Context.USER)
54 assert False, "XFAIL"
55 except AssertionError:
56 eq_(self.context._mode, initial_mode)
57
58 def test_user_mode_shall_restore_behave_mode_if_exception_is_raised(self):
59 initial_mode = runner.Context.BEHAVE
60 eq_(self.context._mode, initial_mode)
61 try:
62 with self.context.use_with_user_mode():
63 eq_(self.context._mode, runner.Context.USER)
64 raise RuntimeError("XFAIL")
65 except RuntimeError:
66 eq_(self.context._mode, initial_mode)
67
68 def test_use_with_user_mode__shall_restore_initial_mode(self):
69 # -- CASE: No exception is raised.
70 # pylint: disable=protected-access
71 initial_mode = runner.Context.BEHAVE
72 self.context._mode = initial_mode
73 with self.context.use_with_user_mode():
74 eq_(self.context._mode, runner.Context.USER)
75 self.context.thing = "stuff"
76 eq_(self.context._mode, initial_mode)
77
78 def test_use_with_user_mode__shall_restore_initial_mode_with_error(self):
79 # -- CASE: Exception is raised.
80 # pylint: disable=protected-access
81 initial_mode = runner.Context.BEHAVE
82 self.context._mode = initial_mode
83 try:
84 with self.context.use_with_user_mode():
85 eq_(self.context._mode, runner.Context.USER)
86 raise RuntimeError("XFAIL")
87 except RuntimeError:
88 eq_(self.context._mode, initial_mode)
89
90 def test_use_with_behave_mode__shall_restore_initial_mode(self):
91 # -- CASE: No exception is raised.
92 # pylint: disable=protected-access
93 initial_mode = runner.Context.USER
94 self.context._mode = initial_mode
95 with self.context._use_with_behave_mode():
96 eq_(self.context._mode, runner.Context.BEHAVE)
97 self.context.thing = "stuff"
98 eq_(self.context._mode, initial_mode)
99
100 def test_use_with_behave_mode__shall_restore_initial_mode_with_error(self):
101 # -- CASE: Exception is raised.
102 # pylint: disable=protected-access
103 initial_mode = runner.Context.USER
104 self.context._mode = initial_mode
105 try:
106 with self.context._use_with_behave_mode():
107 eq_(self.context._mode, runner.Context.BEHAVE)
108 raise RuntimeError("XFAIL")
109 except RuntimeError:
110 eq_(self.context._mode, initial_mode)
111
112 def test_context_contains(self):
113 eq_("thing" in self.context, False)
114 self.context.thing = "stuff"
115 eq_("thing" in self.context, True)
116 self.context._push()
117 eq_("thing" in self.context, True)
118
119 def test_attribute_set_at_upper_level_visible_at_lower_level(self):
120 self.context.thing = "stuff"
121 self.context._push()
122 eq_(self.context.thing, "stuff")
123
124 def test_attribute_set_at_lower_level_not_visible_at_upper_level(self):
125 self.context._push()
126 self.context.thing = "stuff"
127 self.context._pop()
128 assert getattr(self.context, "thing", None) is None
129
130 def test_attributes_set_at_upper_level_visible_at_lower_level(self):
131 self.context.thing = "stuff"
132 self.context._push()
133 eq_(self.context.thing, "stuff")
134 self.context.other_thing = "more stuff"
135 self.context._push()
136 eq_(self.context.thing, "stuff")
137 eq_(self.context.other_thing, "more stuff")
138 self.context.third_thing = "wombats"
139 self.context._push()
140 eq_(self.context.thing, "stuff")
141 eq_(self.context.other_thing, "more stuff")
142 eq_(self.context.third_thing, "wombats")
143
144 def test_attributes_set_at_lower_level_not_visible_at_upper_level(self):
145 self.context.thing = "stuff"
146
147 self.context._push()
148 self.context.other_thing = "more stuff"
149
150 self.context._push()
151 self.context.third_thing = "wombats"
152 eq_(self.context.thing, "stuff")
153 eq_(self.context.other_thing, "more stuff")
154 eq_(self.context.third_thing, "wombats")
155
156 self.context._pop()
157 eq_(self.context.thing, "stuff")
158 eq_(self.context.other_thing, "more stuff")
159 assert getattr(self.context, "third_thing", None) is None, "%s is not None" % self.context.third_thing
160
161 self.context._pop()
162 eq_(self.context.thing, "stuff")
163 assert getattr(self.context, "other_thing", None) is None, "%s is not None" % self.context.other_thing
164 assert getattr(self.context, "third_thing", None) is None, "%s is not None" % self.context.third_thing
165
166 def test_masking_existing_user_attribute_when_verbose_causes_warning(self):
167 warns = []
168
169 def catch_warning(*args, **kwargs):
170 warns.append(args[0])
171
172 old_showwarning = warnings.showwarning
173 warnings.showwarning = catch_warning
174
175 # pylint: disable=protected-access
176 self.config.verbose = True
177 with self.context.use_with_user_mode():
178 self.context.thing = "stuff"
179 self.context._push()
180 self.context.thing = "other stuff"
181
182 warnings.showwarning = old_showwarning
183
184 print(repr(warns))
185 assert warns, "warns is empty!"
186 warning = warns[0]
187 assert isinstance(warning, runner.ContextMaskWarning), "warning is not a ContextMaskWarning"
188 info = warning.args[0]
189 assert info.startswith("user code"), "%r doesn't start with 'user code'" % info
190 assert "'thing'" in info, "%r not in %r" % ("'thing'", info)
191 assert "tutorial" in info, '"tutorial" not in %r' % (info, )
192
193 def test_masking_existing_user_attribute_when_not_verbose_causes_no_warning(self):
194 warns = []
195
196 def catch_warning(*args, **kwargs):
197 warns.append(args[0])
198
199 old_showwarning = warnings.showwarning
200 warnings.showwarning = catch_warning
201
202 # explicit
203 # pylint: disable=protected-access
204 self.config.verbose = False
205 with self.context.use_with_user_mode():
206 self.context.thing = "stuff"
207 self.context._push()
208 self.context.thing = "other stuff"
209
210 warnings.showwarning = old_showwarning
211
212 assert not warns
213
214 def test_behave_masking_user_attribute_causes_warning(self):
215 warns = []
216
217 def catch_warning(*args, **kwargs):
218 warns.append(args[0])
219
220 old_showwarning = warnings.showwarning
221 warnings.showwarning = catch_warning
222
223 with self.context.use_with_user_mode():
224 self.context.thing = "stuff"
225 # pylint: disable=protected-access
226 self.context._push()
227 self.context.thing = "other stuff"
228
229 warnings.showwarning = old_showwarning
230
231 print(repr(warns))
232 assert warns, "OOPS: warns is empty, but expected non-empty"
233 warning = warns[0]
234 assert isinstance(warning, runner.ContextMaskWarning), "warning is not a ContextMaskWarning"
235 info = warning.args[0]
236 assert info.startswith("behave runner"), "%r doesn't start with 'behave runner'" % info
237 assert "'thing'" in info, "%r not in %r" % ("'thing'", info)
238 filename = __file__.rsplit(".", 1)[0]
239 if python_implementation() == "Jython":
240 filename = filename.replace("$py", ".py")
241 assert filename in info, "%r not in %r" % (filename, info)
242
243 def test_setting_root_attribute_that_masks_existing_causes_warning(self):
244 # pylint: disable=protected-access
245 warns = []
246
247 def catch_warning(*args, **kwargs):
248 warns.append(args[0])
249
250 old_showwarning = warnings.showwarning
251 warnings.showwarning = catch_warning
252
253 with self.context.use_with_user_mode():
254 self.context._push()
255 self.context.thing = "teak"
256 self.context._set_root_attribute("thing", "oak")
257
258 warnings.showwarning = old_showwarning
259
260 print(repr(warns))
261 assert warns
262 warning = warns[0]
263 assert isinstance(warning, runner.ContextMaskWarning)
264 info = warning.args[0]
265 assert info.startswith("behave runner"), "%r doesn't start with 'behave runner'" % info
266 assert "'thing'" in info, "%r not in %r" % ("'thing'", info)
267 filename = __file__.rsplit(".", 1)[0]
268 if python_implementation() == "Jython":
269 filename = filename.replace("$py", ".py")
270 assert filename in info, "%r not in %r" % (filename, info)
271
272 def test_context_deletable(self):
273 eq_("thing" in self.context, False)
274 self.context.thing = "stuff"
275 eq_("thing" in self.context, True)
276 del self.context.thing
277 eq_("thing" in self.context, False)
278
279 @raises(AttributeError)
280 def test_context_deletable_raises(self):
281 # pylint: disable=protected-access
282 eq_("thing" in self.context, False)
283 self.context.thing = "stuff"
284 eq_("thing" in self.context, True)
285 self.context._push()
286 eq_("thing" in self.context, True)
287 del self.context.thing
288
289 class ExampleSteps(object):
290 text = None
291 table = None
292
293 @staticmethod
294 def step_passes(context): # pylint: disable=unused-argument
295 pass
296
297 @staticmethod
298 def step_fails(context): # pylint: disable=unused-argument
299 assert False, "XFAIL"
300
301 @classmethod
302 def step_with_text(cls, context):
303 assert context.text is not None, "REQUIRE: multi-line text"
304 cls.text = context.text
305
306 @classmethod
307 def step_with_table(cls, context):
308 assert context.table, "REQUIRE: table"
309 cls.table = context.table
310
311 @classmethod
312 def register_steps_with(cls, step_registry):
313 # pylint: disable=bad-whitespace
314 step_definitions = [
315 ("step", "a step passes", cls.step_passes),
316 ("step", "a step fails", cls.step_fails),
317 ("step", "a step with text", cls.step_with_text),
318 ("step", "a step with a table", cls.step_with_table),
319 ]
320 for keyword, pattern, func in step_definitions:
321 step_registry.add_step_definition(keyword, pattern, func)
322
323 class TestContext_ExecuteSteps(unittest.TestCase):
324 """
325 Test the behave.runner.Context.execute_steps() functionality.
326 """
327 # pylint: disable=invalid-name, no-self-use
328 step_registry = None
329
330 def setUp(self):
331 if not self.step_registry:
332 # -- SETUP ONCE:
333 self.step_registry = StepRegistry()
334 ExampleSteps.register_steps_with(self.step_registry)
335 ExampleSteps.text = None
336 ExampleSteps.table = None
337
338 runner_ = Mock()
339 self.config = runner_.config = Mock()
340 runner_.config.verbose = False
341 runner_.config.stdout_capture = False
342 runner_.config.stderr_capture = False
343 runner_.config.log_capture = False
344 runner_.step_registry = self.step_registry
345
346 self.context = runner.Context(runner_)
347 runner_.context = self.context
348 self.context.feature = Mock()
349 self.context.feature.parser = parser.Parser()
350 self.context.runner = runner_
351 # self.context.text = None
352 # self.context.table = None
353
354 def test_execute_steps_with_simple_steps(self):
355 doc = u"""
356 Given a step passes
357 Then a step passes
358 """.lstrip()
359 with patch("behave.step_registry.registry", self.step_registry):
360 result = self.context.execute_steps(doc)
361 eq_(result, True)
362
363 def test_execute_steps_with_failing_step(self):
364 doc = u"""
365 Given a step passes
366 When a step fails
367 Then a step passes
368 """.lstrip()
369 with patch("behave.step_registry.registry", self.step_registry):
370 try:
371 result = self.context.execute_steps(doc)
372 except AssertionError as e:
373 ok_("FAILED SUB-STEP: When a step fails" in _text(e))
374
375 def test_execute_steps_with_undefined_step(self):
376 doc = u"""
377 Given a step passes
378 When a step is undefined
379 Then a step passes
380 """.lstrip()
381 with patch("behave.step_registry.registry", self.step_registry):
382 try:
383 result = self.context.execute_steps(doc)
384 except AssertionError as e:
385 ok_("UNDEFINED SUB-STEP: When a step is undefined" in _text(e))
386
387 def test_execute_steps_with_text(self):
388 doc = u'''
389 Given a step passes
390 When a step with text:
391 """
392 Lorem ipsum
393 Ipsum lorem
394 """
395 Then a step passes
396 '''.lstrip()
397 with patch("behave.step_registry.registry", self.step_registry):
398 result = self.context.execute_steps(doc)
399 expected_text = "Lorem ipsum\nIpsum lorem"
400 eq_(result, True)
401 eq_(expected_text, ExampleSteps.text)
402
403 def test_execute_steps_with_table(self):
404 doc = u"""
405 Given a step with a table:
406 | Name | Age |
407 | Alice | 12 |
408 | Bob | 23 |
409 Then a step passes
410 """.lstrip()
411 with patch("behave.step_registry.registry", self.step_registry):
412 # pylint: disable=bad-whitespace, bad-continuation
413 result = self.context.execute_steps(doc)
414 expected_table = Table([u"Name", u"Age"], 0, [
415 [u"Alice", u"12"],
416 [u"Bob", u"23"],
417 ])
418 eq_(result, True)
419 eq_(expected_table, ExampleSteps.table)
420
421 def test_context_table_is_restored_after_execute_steps_without_table(self):
422 doc = u"""
423 Given a step passes
424 Then a step passes
425 """.lstrip()
426 with patch("behave.step_registry.registry", self.step_registry):
427 original_table = "<ORIGINAL_TABLE>"
428 self.context.table = original_table
429 self.context.execute_steps(doc)
430 eq_(self.context.table, original_table)
431
432 def test_context_table_is_restored_after_execute_steps_with_table(self):
433 doc = u"""
434 Given a step with a table:
435 | Name | Age |
436 | Alice | 12 |
437 | Bob | 23 |
438 Then a step passes
439 """.lstrip()
440 with patch("behave.step_registry.registry", self.step_registry):
441 original_table = "<ORIGINAL_TABLE>"
442 self.context.table = original_table
443 self.context.execute_steps(doc)
444 eq_(self.context.table, original_table)
445
446 def test_context_text_is_restored_after_execute_steps_without_text(self):
447 doc = u"""
448 Given a step passes
449 Then a step passes
450 """.lstrip()
451 with patch("behave.step_registry.registry", self.step_registry):
452 original_text = "<ORIGINAL_TEXT>"
453 self.context.text = original_text
454 self.context.execute_steps(doc)
455 eq_(self.context.text, original_text)
456
457 def test_context_text_is_restored_after_execute_steps_with_text(self):
458 doc = u'''
459 Given a step passes
460 When a step with text:
461 """
462 Lorem ipsum
463 Ipsum lorem
464 """
465 '''.lstrip()
466 with patch("behave.step_registry.registry", self.step_registry):
467 original_text = "<ORIGINAL_TEXT>"
468 self.context.text = original_text
469 self.context.execute_steps(doc)
470 eq_(self.context.text, original_text)
471
472
473 @raises(ValueError)
474 def test_execute_steps_should_fail_when_called_without_feature(self):
475 doc = u"""
476 Given a passes
477 Then a step passes
478 """.lstrip()
479 with patch("behave.step_registry.registry", self.step_registry):
480 self.context.feature = None
481 self.context.execute_steps(doc)
482
483
484 def create_mock_config():
485 config = Mock()
486 config.steps_dir = "steps"
487 config.environment_file = "environment.py"
488 return config
489
490
491 class TestRunner(object):
492 # pylint: disable=invalid-name, no-self-use
493
494 def test_load_hooks_execfiles_hook_file(self):
495 with patch("behave.runner.exec_file") as ef:
496 with patch("os.path.exists") as exists:
497 exists.return_value = True
498 base_dir = "fake/path"
499 hooks_path = os.path.join(base_dir, "environment.py")
500
501 r = runner.Runner(create_mock_config())
502 r.base_dir = base_dir
503 r.load_hooks()
504
505 exists.assert_called_with(hooks_path)
506 ef.assert_called_with(hooks_path, r.hooks)
507
508 def test_run_hook_runs_a_hook_that_exists(self):
509 config = Mock()
510 r = runner.Runner(config)
511 # XXX r.config = Mock()
512 r.config.stdout_capture = False
513 r.config.stderr_capture = False
514 r.config.dry_run = False
515 r.hooks["before_lunch"] = hook = Mock()
516 args = (runner.Context(Mock()), Mock(), Mock())
517 r.run_hook("before_lunch", *args)
518
519 hook.assert_called_with(*args)
520
521 def test_run_hook_does_not_runs_a_hook_that_exists_if_dry_run(self):
522 r = runner.Runner(None)
523 r.config = Mock()
524 r.config.dry_run = True
525 r.hooks["before_lunch"] = hook = Mock()
526 args = (runner.Context(Mock()), Mock(), Mock())
527 r.run_hook("before_lunch", *args)
528
529 assert len(hook.call_args_list) == 0
530
531 def test_setup_capture_creates_stringio_for_stdout(self):
532 r = runner.Runner(Mock())
533 r.config.stdout_capture = True
534 r.config.log_capture = False
535 r.context = Mock()
536
537 r.setup_capture()
538
539 assert r.capture_controller.stdout_capture is not None
540 assert isinstance(r.capture_controller.stdout_capture, StringIO)
541
542 def test_setup_capture_does_not_create_stringio_if_not_wanted(self):
543 r = runner.Runner(Mock())
544 r.config.stdout_capture = False
545 r.config.stderr_capture = False
546 r.config.log_capture = False
547
548 r.setup_capture()
549
550 assert r.capture_controller.stdout_capture is None
551
552 @patch("behave.capture.LoggingCapture")
553 def test_setup_capture_creates_memory_handler_for_logging(self, handler):
554 r = runner.Runner(Mock())
555 r.config.stdout_capture = False
556 r.config.log_capture = True
557 r.context = Mock()
558
559 r.setup_capture()
560
561 assert r.capture_controller.log_capture is not None
562 handler.assert_called_with(r.config)
563 r.capture_controller.log_capture.inveigle.assert_called_with()
564
565 def test_setup_capture_does_not_create_memory_handler_if_not_wanted(self):
566 r = runner.Runner(Mock())
567 r.config.stdout_capture = False
568 r.config.stderr_capture = False
569 r.config.log_capture = False
570
571 r.setup_capture()
572
573 assert r.capture_controller.log_capture is None
574
575 def test_start_stop_capture_switcheroos_sys_stdout(self):
576 old_stdout = sys.stdout
577 sys.stdout = new_stdout = Mock()
578
579 r = runner.Runner(Mock())
580 r.config.stdout_capture = True
581 r.config.log_capture = False
582 r.context = Mock()
583
584 r.setup_capture()
585 r.start_capture()
586
587 eq_(sys.stdout, r.capture_controller.stdout_capture)
588
589 r.stop_capture()
590
591 eq_(sys.stdout, new_stdout)
592
593 sys.stdout = old_stdout
594
595 def test_start_stop_capture_leaves_sys_stdout_alone_if_off(self):
596 r = runner.Runner(Mock())
597 r.config.stdout_capture = False
598 r.config.log_capture = False
599
600 old_stdout = sys.stdout
601
602 r.start_capture()
603
604 eq_(sys.stdout, old_stdout)
605
606 r.stop_capture()
607
608 eq_(sys.stdout, old_stdout)
609
610 def test_teardown_capture_removes_log_tap(self):
611 r = runner.Runner(Mock())
612 r.config.stdout_capture = False
613 r.config.log_capture = True
614
615 r.capture_controller.log_capture = Mock()
616
617 r.teardown_capture()
618
619 r.capture_controller.log_capture.abandon.assert_called_with()
620
621 def test_exec_file(self):
622 fn = tempfile.mktemp()
623 with open(fn, "w") as f:
624 f.write("spam = __file__\n")
625 g = {}
626 l = {}
627 runner_util.exec_file(fn, g, l)
628 assert "__file__" in l
629 # pylint: disable=too-many-format-args
630 assert "spam" in l, '"spam" variable not set in locals (%r)' % (g, l)
631 # pylint: enable=too-many-format-args
632 eq_(l["spam"], fn)
633
634 def test_run_returns_true_if_everything_passed(self):
635 r = runner.Runner(Mock())
636 r.setup_capture = Mock()
637 r.setup_paths = Mock()
638 r.run_with_paths = Mock()
639 r.run_with_paths.return_value = True
640 assert r.run()
641
642 def test_run_returns_false_if_anything_failed(self):
643 r = runner.Runner(Mock())
644 r.setup_capture = Mock()
645 r.setup_paths = Mock()
646 r.run_with_paths = Mock()
647 r.run_with_paths.return_value = False
648 assert not r.run()
649
650
651 class TestRunWithPaths(unittest.TestCase):
652 # pylint: disable=invalid-name, no-self-use
653
654 def setUp(self):
655 self.config = Mock()
656 self.config.reporters = []
657 self.config.logging_level = None
658 self.config.logging_filter = None
659 self.config.outputs = [Mock(), StreamOpener(stream=sys.stdout)]
660 self.config.format = ["plain", "progress"]
661 self.runner = runner.Runner(self.config)
662 self.load_hooks = self.runner.load_hooks = Mock()
663 self.load_step_definitions = self.runner.load_step_definitions = Mock()
664 self.run_hook = self.runner.run_hook = Mock()
665 self.run_step = self.runner.run_step = Mock()
666 self.feature_locations = self.runner.feature_locations = Mock()
667 self.calculate_summaries = self.runner.calculate_summaries = Mock()
668
669 self.formatter_class = patch("behave.formatter.pretty.PrettyFormatter")
670 formatter_class = self.formatter_class.start()
671 formatter_class.return_value = self.formatter = Mock()
672
673 def tearDown(self):
674 self.formatter_class.stop()
675
676 def test_loads_hooks_and_step_definitions(self):
677 self.feature_locations.return_value = []
678 self.runner.run_with_paths()
679
680 assert self.load_hooks.called
681 assert self.load_step_definitions.called
682
683 def test_runs_before_all_and_after_all_hooks(self):
684 # Make runner.feature_locations() and runner.run_hook() the same mock so
685 # we can make sure things happen in the right order.
686 self.runner.feature_locations = self.run_hook
687 self.runner.feature_locations.return_value = []
688 self.runner.context = Mock()
689 self.runner.run_with_paths()
690
691 eq_(self.run_hook.call_args_list, [
692 ((), {}),
693 (("before_all", self.runner.context), {}),
694 (("after_all", self.runner.context), {}),
695 ])
696
697 @patch("behave.parser.parse_file")
698 @patch("os.path.abspath")
699 def test_parses_feature_files_and_appends_to_feature_list(self, abspath,
700 parse_file):
701 feature_locations = ["one", "two", "three"]
702 feature = Mock()
703 feature.tags = []
704 feature.__iter__ = Mock(return_value=iter([]))
705 feature.run.return_value = False
706 self.runner.feature_locations.return_value = feature_locations
707 abspath.side_effect = lambda x: x.upper()
708 self.config.lang = "fritz"
709 self.config.format = ["plain"]
710 self.config.outputs = [StreamOpener(stream=sys.stdout)]
711 self.config.output.encoding = None
712 self.config.exclude = lambda s: False
713 self.config.junit = False
714 self.config.summary = False
715 parse_file.return_value = feature
716
717 self.runner.run_with_paths()
718
719 expected_parse_file_args = \
720 [((x.upper(),), {"language": "fritz"}) for x in feature_locations]
721 eq_(parse_file.call_args_list, expected_parse_file_args)
722 eq_(self.runner.features, [feature] * 3)
723
724
725 class FsMock(object):
726 def __init__(self, *paths):
727 self.base = os.path.abspath(".")
728 self.sep = os.path.sep
729
730 # This bit of gymnastics is to support Windows. We feed in a bunch of
731 # paths in places using FsMock that assume that POSIX-style paths
732 # work. This is faster than fixing all of those but at some point we
733 # should totally do it properly with os.path.join() and all that.
734 def full_split(path):
735 bits = []
736
737 while path:
738 path, bit = os.path.split(path)
739 bits.insert(0, bit)
740
741 return bits
742
743 paths = [os.path.join(self.base, *full_split(path)) for path in paths]
744 print(repr(paths))
745 self.paths = paths
746 self.files = set()
747 self.dirs = defaultdict(list)
748 separators = [sep for sep in (os.path.sep, os.path.altsep) if sep]
749 for path in paths:
750 if path[-1] in separators:
751 self.dirs[path[:-1]] = []
752 d, p = os.path.split(path[:-1])
753 while d and p:
754 self.dirs[d].append(p)
755 d, p = os.path.split(d)
756 else:
757 self.files.add(path)
758 d, f = os.path.split(path)
759 self.dirs[d].append(f)
760 self.calls = []
761
762 def listdir(self, dir):
763 # pylint: disable=W0622
764 # W0622 Redefining built-in dir
765 self.calls.append(("listdir", dir))
766 return self.dirs.get(dir, [])
767
768 def isfile(self, path):
769 self.calls.append(("isfile", path))
770 return path in self.files
771
772 def isdir(self, path):
773 self.calls.append(("isdir", path))
774 return path in self.dirs
775
776 def exists(self, path):
777 self.calls.append(("exists", path))
778 return path in self.dirs or path in self.files
779
780 def walk(self, path, locations=None):
781 if locations is None:
782 assert path in self.dirs, "%s not in %s" % (path, self.dirs)
783 locations = []
784 dirnames = []
785 filenames = []
786 for e in self.dirs[path]:
787 if os.path.join(path, e) in self.dirs:
788 dirnames.append(e)
789 self.walk(os.path.join(path, e), locations)
790 else:
791 filenames.append(e)
792 locations.append((path, dirnames, filenames))
793 return locations
794
795 # utilities that we need
796 # pylint: disable=no-self-use
797 def dirname(self, path, orig=os.path.dirname):
798 return orig(path)
799
800 def abspath(self, path, orig=os.path.abspath):
801 return orig(path)
802
803 def join(self, x, y, orig=os.path.join):
804 return orig(x, y)
805
806 def split(self, path, orig=os.path.split):
807 return orig(path)
808
809 def splitdrive(self, path, orig=os.path.splitdrive):
810 return orig(path)
811
812
813 class TestFeatureDirectory(object):
814 # pylint: disable=invalid-name, no-self-use
815
816 def test_default_path_no_steps(self):
817 config = create_mock_config()
818 config.paths = []
819 config.verbose = True
820 r = runner.Runner(config)
821
822 fs = FsMock()
823
824 # will look for a "features" directory and not find one
825 with patch("os.path", fs):
826 assert_raises(ConfigError, r.setup_paths)
827
828 ok_(("isdir", os.path.join(fs.base, "features", "steps")) in fs.calls)
829
830 def test_default_path_no_features(self):
831 config = create_mock_config()
832 config.paths = []
833 config.verbose = True
834 r = runner.Runner(config)
835
836 fs = FsMock("features/steps/")
837 with patch("os.path", fs):
838 with patch("os.walk", fs.walk):
839 assert_raises(ConfigError, r.setup_paths)
840
841 def test_default_path(self):
842 config = create_mock_config()
843 config.paths = []
844 config.verbose = True
845 r = runner.Runner(config)
846
847 fs = FsMock("features/steps/", "features/foo.feature")
848
849 with patch("os.path", fs):
850 with patch("os.walk", fs.walk):
851 with r.path_manager:
852 r.setup_paths()
853
854 eq_(r.base_dir, os.path.abspath("features"))
855
856 def test_supplied_feature_file(self):
857 config = create_mock_config()
858 config.paths = ["foo.feature"]
859 config.verbose = True
860 r = runner.Runner(config)
861 r.context = Mock()
862
863 fs = FsMock("steps/", "foo.feature")
864
865 with patch("os.path", fs):
866 with patch("os.walk", fs.walk):
867 with r.path_manager:
868 r.setup_paths()
869 ok_(("isdir", os.path.join(fs.base, "steps")) in fs.calls)
870 ok_(("isfile", os.path.join(fs.base, "foo.feature")) in fs.calls)
871
872 eq_(r.base_dir, fs.base)
873
874 def test_supplied_feature_file_no_steps(self):
875 config = create_mock_config()
876 config.paths = ["foo.feature"]
877 config.verbose = True
878 r = runner.Runner(config)
879
880 fs = FsMock("foo.feature")
881
882 with patch("os.path", fs):
883 with patch("os.walk", fs.walk):
884 with r.path_manager:
885 assert_raises(ConfigError, r.setup_paths)
886
887 def test_supplied_feature_directory(self):
888 config = create_mock_config()
889 config.paths = ["spam"]
890 config.verbose = True
891 r = runner.Runner(config)
892
893 fs = FsMock("spam/", "spam/steps/", "spam/foo.feature")
894
895 with patch("os.path", fs):
896 with patch("os.walk", fs.walk):
897 with r.path_manager:
898 r.setup_paths()
899
900 ok_(("isdir", os.path.join(fs.base, "spam", "steps")) in fs.calls)
901
902 eq_(r.base_dir, os.path.join(fs.base, "spam"))
903
904 def test_supplied_feature_directory_no_steps(self):
905 config = create_mock_config()
906 config.paths = ["spam"]
907 config.verbose = True
908 r = runner.Runner(config)
909
910 fs = FsMock("spam/", "spam/foo.feature")
911
912 with patch("os.path", fs):
913 with patch("os.walk", fs.walk):
914 assert_raises(ConfigError, r.setup_paths)
915
916 ok_(("isdir", os.path.join(fs.base, "spam", "steps")) in fs.calls)
917
918 def test_supplied_feature_directory_missing(self):
919 config = create_mock_config()
920 config.paths = ["spam"]
921 config.verbose = True
922 r = runner.Runner(config)
923
924 fs = FsMock()
925
926 with patch("os.path", fs):
927 with patch("os.walk", fs.walk):
928 assert_raises(ConfigError, r.setup_paths)
929
930
931 class TestFeatureDirectoryLayout2(object):
932 # pylint: disable=invalid-name, no-self-use
933
934 def test_default_path(self):
935 config = create_mock_config()
936 config.paths = []
937 config.verbose = True
938 r = runner.Runner(config)
939
940 fs = FsMock(
941 "features/",
942 "features/steps/",
943 "features/group1/",
944 "features/group1/foo.feature",
945 )
946
947 with patch("os.path", fs):
948 with patch("os.walk", fs.walk):
949 with r.path_manager:
950 r.setup_paths()
951
952 eq_(r.base_dir, os.path.abspath("features"))
953
954 def test_supplied_root_directory(self):
955 config = create_mock_config()
956 config.paths = ["features"]
957 config.verbose = True
958 r = runner.Runner(config)
959
960 fs = FsMock(
961 "features/",
962 "features/group1/",
963 "features/group1/foo.feature",
964 "features/steps/",
965 )
966
967 with patch("os.path", fs):
968 with patch("os.walk", fs.walk):
969 with r.path_manager:
970 r.setup_paths()
971
972 ok_(("isdir", os.path.join(fs.base, "features", "steps")) in fs.calls)
973 eq_(r.base_dir, os.path.join(fs.base, "features"))
974
975 def test_supplied_root_directory_no_steps(self):
976 config = create_mock_config()
977 config.paths = ["features"]
978 config.verbose = True
979 r = runner.Runner(config)
980
981 fs = FsMock(
982 "features/",
983 "features/group1/",
984 "features/group1/foo.feature",
985 )
986
987 with patch("os.path", fs):
988 with patch("os.walk", fs.walk):
989 with r.path_manager:
990 assert_raises(ConfigError, r.setup_paths)
991
992 ok_(("isdir", os.path.join(fs.base, "features", "steps")) in fs.calls)
993 eq_(r.base_dir, None)
994
995
996 def test_supplied_feature_file(self):
997 config = create_mock_config()
998 config.paths = ["features/group1/foo.feature"]
999 config.verbose = True
1000 r = runner.Runner(config)
1001 r.context = Mock()
1002
1003 fs = FsMock(
1004 "features/",
1005 "features/group1/",
1006 "features/group1/foo.feature",
1007 "features/steps/",
1008 )
1009
1010 with patch("os.path", fs):
1011 with patch("os.walk", fs.walk):
1012 with r.path_manager:
1013 r.setup_paths()
1014
1015 ok_(("isdir", os.path.join(fs.base, "features", "steps")) in fs.calls)
1016 ok_(("isfile", os.path.join(fs.base, "features", "group1", "foo.feature")) in fs.calls)
1017 eq_(r.base_dir, fs.join(fs.base, "features"))
1018
1019 def test_supplied_feature_file_no_steps(self):
1020 config = create_mock_config()
1021 config.paths = ["features/group1/foo.feature"]
1022 config.verbose = True
1023 r = runner.Runner(config)
1024
1025 fs = FsMock(
1026 "features/",
1027 "features/group1/",
1028 "features/group1/foo.feature",
1029 )
1030
1031 with patch("os.path", fs):
1032 with patch("os.walk", fs.walk):
1033 with r.path_manager:
1034 assert_raises(ConfigError, r.setup_paths)
1035
1036 def test_supplied_feature_directory(self):
1037 config = create_mock_config()
1038 config.paths = ["features/group1"]
1039 config.verbose = True
1040 r = runner.Runner(config)
1041
1042 fs = FsMock(
1043 "features/",
1044 "features/group1/",
1045 "features/group1/foo.feature",
1046 "features/steps/",
1047 )
1048
1049 with patch("os.path", fs):
1050 with patch("os.walk", fs.walk):
1051 with r.path_manager:
1052 r.setup_paths()
1053
1054 ok_(("isdir", os.path.join(fs.base, "features", "steps")) in fs.calls)
1055 eq_(r.base_dir, os.path.join(fs.base, "features"))
1056
1057
1058 def test_supplied_feature_directory_no_steps(self):
1059 config = create_mock_config()
1060 config.paths = ["features/group1"]
1061 config.verbose = True
1062 r = runner.Runner(config)
1063
1064 fs = FsMock(
1065 "features/",
1066 "features/group1/",
1067 "features/group1/foo.feature",
1068 )
1069
1070 with patch("os.path", fs):
1071 with patch("os.walk", fs.walk):
1072 assert_raises(ConfigError, r.setup_paths)
1073
1074 ok_(("isdir", os.path.join(fs.base, "features", "steps")) in fs.calls)
1075