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