How to use step_command_output_should_contain method in Behave

Best Python code snippet using behave

Run Behave automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

command_steps.py

Source: command_steps.py Github

copy
1# -*- coding -*-
2"""
3Provides step definitions to:
4
5    * run commands, like behave
6    * create textual files within a working directory
7
8TODO:
9  matcher that ignores empty lines and whitespace and has contains comparison
10"""
11
12from __future__ import absolute_import, print_function
13from behave import given, when, then, step, matchers
14from behave4cmd0 import command_shell, command_util, pathutil, textutil
15from behave4cmd0.pathutil import posixpath_normpath
16import os
17import shutil
18from hamcrest import assert_that, equal_to, is_not, contains_string
19
20# -----------------------------------------------------------------------------
21# INIT:
22# -----------------------------------------------------------------------------
23matchers.register_type(int=int)
24DEBUG = True
25
26
27# -----------------------------------------------------------------------------
28# STEPS: WORKING DIR
29# -----------------------------------------------------------------------------
30@given(u'a new working directory')
31def step_a_new_working_directory(context):
32    """
33    Creates a new, empty working directory
34    """
35    command_util.ensure_context_attribute_exists(context, "workdir", None)
36    command_util.ensure_workdir_exists(context)
37    shutil.rmtree(context.workdir, ignore_errors=True)
38
39@given(u'I use the current directory as working directory')
40def step_use_curdir_as_working_directory(context):
41    """
42    Uses the current directory as working directory
43    """
44    context.workdir = os.path.abspath(".")
45    command_util.ensure_workdir_exists(context)
46
47# -----------------------------------------------------------------------------
48# STEPS: Create files with contents
49# -----------------------------------------------------------------------------
50@given(u'a file named "{filename}" with')
51def step_a_file_named_filename_with(context, filename):
52    """
53    Creates a textual file with the content provided as docstring.
54    """
55    assert context.text is not None, "ENSURE: multiline text is provided."
56    assert not os.path.isabs(filename)
57    command_util.ensure_workdir_exists(context)
58    filename2 = os.path.join(context.workdir, filename)
59    pathutil.create_textfile_with_contents(filename2, context.text)
60
61    # -- SPECIAL CASE: For usage with behave steps.
62    if filename.endswith(".feature"):
63        command_util.ensure_context_attribute_exists(context, "features", [])
64        context.features.append(filename)
65
66@given(u'an empty file named "{filename}"')
67def step_an_empty_file_named_filename(context, filename):
68    """
69    Creates an empty file.
70    """
71    assert not os.path.isabs(filename)
72    command_util.ensure_workdir_exists(context)
73    filename2 = os.path.join(context.workdir, filename)
74    pathutil.create_textfile_with_contents(filename2, "")
75
76
77# -----------------------------------------------------------------------------
78# STEPS: Run commands
79# -----------------------------------------------------------------------------
80@when(u'I run "{command}"')
81def step_i_run_command(context, command):
82    """
83    Run a command as subprocess, collect its output and returncode.
84    """
85    command_util.ensure_workdir_exists(context)
86    context.command_result = command_shell.run(command, cwd=context.workdir)
87    command_util.workdir_save_coverage_files(context.workdir)
88    if False and DEBUG:
89        print(u"run_command: {0}".format(command))
90        print(u"run_command.output {0}".format(context.command_result.output))
91
92
93@then(u'it should fail with result "{result:int}"')
94def step_it_should_fail_with_result(context, result):
95    assert_that(context.command_result.returncode, equal_to(result))
96    assert_that(result, is_not(equal_to(0)))
97
98@then(u'the command should fail with returncode="{result:int}"')
99def step_it_should_fail_with_returncode(context, result):
100    assert_that(context.command_result.returncode, equal_to(result))
101    assert_that(result, is_not(equal_to(0)))
102
103@then(u'the command returncode is "{result:int}"')
104def step_the_command_returncode_is(context, result):
105    assert_that(context.command_result.returncode, equal_to(result))
106
107@then(u'the command returncode is non-zero')
108def step_the_command_returncode_is_nonzero(context):
109    assert_that(context.command_result.returncode, is_not(equal_to(0)))
110
111@then(u'it should pass')
112def step_it_should_pass(context):
113    assert_that(context.command_result.returncode, equal_to(0))
114
115@then(u'it should fail')
116def step_it_should_fail(context):
117    assert_that(context.command_result.returncode, is_not(equal_to(0)))
118
119@then(u'it should pass with')
120def step_it_should_pass_with(context):
121    '''
122    EXAMPLE:
123        ...
124        when I run "behave ..."
125        then it should pass with:
126            """
127            TEXT
128            """
129    '''
130    assert context.text is not None, "ENSURE: multiline text is provided."
131    step_command_output_should_contain(context)
132    assert_that(context.command_result.returncode, equal_to(0))
133
134
135@then(u'it should fail with')
136def step_it_should_fail_with(context):
137    '''
138    EXAMPLE:
139        ...
140        when I run "behave ..."
141        then it should fail with:
142            """
143            TEXT
144            """
145    '''
146    assert context.text is not None, "ENSURE: multiline text is provided."
147    step_command_output_should_contain(context)
148    assert_that(context.command_result.returncode, is_not(equal_to(0)))
149
150
151# -----------------------------------------------------------------------------
152# STEPS FOR: Output Comparison
153# -----------------------------------------------------------------------------
154@then(u'the command output should contain "{text}"')
155def step_command_output_should_contain_text(context, text):
156    '''
157    EXAMPLE:
158        ...
159        Then the command output should contain "TEXT"
160    '''
161    expected_text = text
162    if "{__WORKDIR__}" in expected_text or "{__CWD__}" in expected_text:
163        expected_text = textutil.template_substitute(text,
164             __WORKDIR__ = posixpath_normpath(context.workdir),
165             __CWD__     = posixpath_normpath(os.getcwd())
166        )
167    actual_output = context.command_result.output
168    if DEBUG:
169        print(u"expected:\n{0}".format(expected_text))
170        print(u"actual:\n{0}".format(actual_output))
171    textutil.assert_normtext_should_contain(actual_output, expected_text)
172
173
174@then(u'the command output should not contain "{text}"')
175def step_command_output_should_not_contain_text(context, text):
176    '''
177    EXAMPLE:
178        ...
179        then the command output should not contain "TEXT"
180    '''
181    expected_text = text
182    if "{__WORKDIR__}" in text or "{__CWD__}" in text:
183        expected_text = textutil.template_substitute(text,
184             __WORKDIR__ = posixpath_normpath(context.workdir),
185             __CWD__     = posixpath_normpath(os.getcwd())
186        )
187    actual_output  = context.command_result.output
188    if DEBUG:
189        print(u"expected:\n{0}".format(expected_text))
190        print(u"actual:\n{0}".format(actual_output))
191    textutil.assert_normtext_should_not_contain(actual_output, expected_text)
192
193
194@then(u'the command output should contain exactly "{text}"')
195def step_command_output_should_contain_exactly_text(context, text):
196    """
197    Verifies that the command output of the last command contains the
198    expected text.
199
200    .. code-block:: gherkin
201
202        When I run "echo Hello"
203        Then the command output should contain "Hello"
204    """
205    expected_text = text
206    if "{__WORKDIR__}" in text or "{__CWD__}" in text:
207        expected_text = textutil.template_substitute(text,
208             __WORKDIR__ = posixpath_normpath(context.workdir),
209             __CWD__     = posixpath_normpath(os.getcwd())
210        )
211    actual_output  = context.command_result.output
212    textutil.assert_text_should_contain_exactly(actual_output, expected_text)
213
214
215@then(u'the command output should not contain exactly "{text}"')
216def step_command_output_should_not_contain_exactly_text(context, text):
217    expected_text = text
218    if "{__WORKDIR__}" in text or "{__CWD__}" in text:
219        expected_text = textutil.template_substitute(text,
220             __WORKDIR__ = posixpath_normpath(context.workdir),
221             __CWD__     = posixpath_normpath(os.getcwd())
222        )
223    actual_output  = context.command_result.output
224    textutil.assert_text_should_not_contain_exactly(actual_output, expected_text)
225
226
227@then(u'the command output should contain')
228def step_command_output_should_contain(context):
229    '''
230    EXAMPLE:
231        ...
232        when I run "behave ..."
233        then it should pass
234        and  the command output should contain:
235            """
236            TEXT
237            """
238    '''
239    assert context.text is not None, "REQUIRE: multi-line text"
240    step_command_output_should_contain_text(context, context.text)
241
242
243@then(u'the command output should not contain')
244def step_command_output_should_not_contain(context):
245    '''
246    EXAMPLE:
247        ...
248        when I run "behave ..."
249        then it should pass
250        and  the command output should not contain:
251            """
252            TEXT
253            """
254    '''
255    assert context.text is not None, "REQUIRE: multi-line text"
256    step_command_output_should_not_contain_text(context, context.text.strip())
257
258
259@then(u'the command output should contain exactly')
260def step_command_output_should_contain_exactly_with_multiline_text(context):
261    assert context.text is not None, "REQUIRE: multi-line text"
262    step_command_output_should_contain_exactly_text(context, context.text)
263
264
265@then(u'the command output should not contain exactly')
266def step_command_output_should_contain_not_exactly_with_multiline_text(context):
267    assert context.text is not None, "REQUIRE: multi-line text"
268    step_command_output_should_not_contain_exactly_text(context, context.text)
269
270
271# -----------------------------------------------------------------------------
272# STEPS FOR: Directories
273# -----------------------------------------------------------------------------
274@step(u'I remove the directory "{directory}"')
275def step_remove_directory(context, directory):
276    path_ = directory
277    if not os.path.isabs(directory):
278        path_ = os.path.join(context.workdir, os.path.normpath(directory))
279    if os.path.isdir(path_):
280        shutil.rmtree(path_, ignore_errors=True)
281    assert_that(not os.path.isdir(path_))
282
283@given(u'I ensure that the directory "{directory}" does not exist')
284def step_given_the_directory_should_not_exist(context, directory):
285    step_remove_directory(context, directory)
286
287@given(u'a directory named "{path}"')
288def step_directory_named_dirname(context, path):
289    assert context.workdir, "REQUIRE: context.workdir"
290    path_ = os.path.join(context.workdir, os.path.normpath(path))
291    if not os.path.exists(path_):
292        os.makedirs(path_)
293    assert os.path.isdir(path_)
294
295@then(u'the directory "{directory}" should exist')
296def step_the_directory_should_exist(context, directory):
297    path_ = directory
298    if not os.path.isabs(directory):
299        path_ = os.path.join(context.workdir, os.path.normpath(directory))
300    assert_that(os.path.isdir(path_))
301
302@then(u'the directory "{directory}" should not exist')
303def step_the_directory_should_not_exist(context, directory):
304    path_ = directory
305    if not os.path.isabs(directory):
306        path_ = os.path.join(context.workdir, os.path.normpath(directory))
307    assert_that(not os.path.isdir(path_))
308
309@step(u'the directory "{directory}" exists')
310def step_directory_exists(context, directory):
311    """
312    Verifies that a directory exists.
313
314    .. code-block:: gherkin
315
316        Given the directory "abc.txt" exists
317         When the directory "abc.txt" exists
318    """
319    step_the_directory_should_exist(context, directory)
320
321@step(u'the directory "{directory}" does not exist')
322def step_directory_named_does_not_exist(context, directory):
323    """
324    Verifies that a directory does not exist.
325
326    .. code-block:: gherkin
327
328        Given the directory "abc/" does not exist
329         When the directory "abc/" does not exist
330    """
331    step_the_directory_should_not_exist(context, directory)
332
333# -----------------------------------------------------------------------------
334# FILE STEPS:
335# -----------------------------------------------------------------------------
336@step(u'a file named "{filename}" exists')
337def step_file_named_filename_exists(context, filename):
338    """
339    Verifies that a file with this filename exists.
340
341    .. code-block:: gherkin
342
343        Given a file named "abc.txt" exists
344         When a file named "abc.txt" exists
345    """
346    step_file_named_filename_should_exist(context, filename)
347
348@step(u'a file named "{filename}" does not exist')
349def step_file_named_filename_does_not_exist(context, filename):
350    """
351    Verifies that a file with this filename does not exist.
352
353    .. code-block:: gherkin
354
355        Given a file named "abc.txt" does not exist
356         When a file named "abc.txt" does not exist
357    """
358    step_file_named_filename_should_not_exist(context, filename)
359
360@then(u'a file named "{filename}" should exist')
361def step_file_named_filename_should_exist(context, filename):
362    command_util.ensure_workdir_exists(context)
363    filename_ = pathutil.realpath_with_context(filename, context)
364    assert_that(os.path.exists(filename_) and os.path.isfile(filename_))
365
366@then(u'a file named "{filename}" should not exist')
367def step_file_named_filename_should_not_exist(context, filename):
368    command_util.ensure_workdir_exists(context)
369    filename_ = pathutil.realpath_with_context(filename, context)
370    assert_that(not os.path.exists(filename_))
371
372# -----------------------------------------------------------------------------
373# STEPS FOR FILE CONTENTS:
374# -----------------------------------------------------------------------------
375@then(u'the file "{filename}" should contain "{text}"')
376def step_file_should_contain_text(context, filename, text):
377    expected_text = text
378    if "{__WORKDIR__}" in text or "{__CWD__}" in text:
379        expected_text = textutil.template_substitute(text,
380            __WORKDIR__ = posixpath_normpath(context.workdir),
381            __CWD__     = posixpath_normpath(os.getcwd())
382        )
383    file_contents = pathutil.read_file_contents(filename, context=context)
384    file_contents = file_contents.rstrip()
385    if DEBUG:
386        print(u"expected:\n{0}".format(expected_text))
387        print(u"actual:\n{0}".format(file_contents))
388    textutil.assert_normtext_should_contain(file_contents, expected_text)
389
390
391@then(u'the file "{filename}" should not contain "{text}"')
392def step_file_should_not_contain_text(context, filename, text):
393    file_contents = pathutil.read_file_contents(filename, context=context)
394    file_contents = file_contents.rstrip()
395    textutil.assert_normtext_should_not_contain(file_contents, text)
396    # XXX assert_that(file_contents, is_not(contains_string(text)))
397
398
399@then(u'the file "{filename}" should contain')
400def step_file_should_contain_multiline_text(context, filename):
401    assert context.text is not None, "REQUIRE: multiline text"
402    step_file_should_contain_text(context, filename, context.text)
403
404
405@then(u'the file "{filename}" should not contain')
406def step_file_should_not_contain_multiline_text(context, filename):
407    assert context.text is not None, "REQUIRE: multiline text"
408    step_file_should_not_contain_text(context, filename, context.text)
409
410
411# -----------------------------------------------------------------------------
412# ENVIRONMENT VARIABLES
413# -----------------------------------------------------------------------------
414@step(u'I set the environment variable "{env_name}" to "{env_value}"')
415def step_I_set_the_environment_variable_to(context, env_name, env_value):
416    if not hasattr(context, "environ"):
417        context.environ = {}
418    context.environ[env_name] = env_value
419    os.environ[env_name] = env_value
420
421@step(u'I remove the environment variable "{env_name}"')
422def step_I_remove_the_environment_variable(context, env_name):
423    if not hasattr(context, "environ"):
424        context.environ = {}
425    context.environ[env_name] = ""
426    os.environ[env_name] = ""
427    del context.environ[env_name]
428    del os.environ[env_name]
429
430
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Behave on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)