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