How to use on_assert_failed_print_details method in Behave

Best Python code snippet using behave

command_steps.py

Source:command_steps.py Github

copy

Full Screen

...28# -----------------------------------------------------------------------------29# UTILITIES:30# -----------------------------------------------------------------------------31@contextlib.contextmanager32def on_assert_failed_print_details(actual, expected):33 """34 Print text details in case of assertation failed errors.35 .. sourcecode:: python36 with on_assert_failed_print_details(actual_text, expected_text):37 assert actual == expected38 """39 try:40 yield41 except AssertionError:42 # diff = difflib.unified_diff(expected.splitlines(), actual.splitlines(),43 # "expected", "actual")44 diff = difflib.ndiff(expected.splitlines(), actual.splitlines())45 diff_text = u"\n".join(diff)46 print(u"DIFF (+ ACTUAL, - EXPECTED):\n{0}\n".format(diff_text))47 if DEBUG:48 print(u"expected:\n{0}\n".format(expected))49 print(u"actual:\n{0}\n".format(actual))50 raise51@contextlib.contextmanager52def on_error_print_details(actual, expected):53 """54 Print text details in case of assertation failed errors.55 .. sourcecode:: python56 with on_error_print_details(actual_text, expected_text):57 ... # Do something58 """59 try:60 yield61 except Exception:62 diff = difflib.ndiff(expected.splitlines(), actual.splitlines())63 diff_text = u"\n".join(diff)64 print(u"DIFF (+ ACTUAL, - EXPECTED):\n{0}\n".format(diff_text))65 if DEBUG:66 print(u"expected:\n{0}\n".format(expected))67 print(u"actual:\n{0}".format(actual))68 raise69# -----------------------------------------------------------------------------70# STEPS: WORKING DIR71# -----------------------------------------------------------------------------72@given(u'a new working directory')73def step_a_new_working_directory(context):74 """Creates a new, empty working directory."""75 command_util.ensure_context_attribute_exists(context, "workdir", None)76 # MAYBE: command_util.ensure_workdir_not_exists(context)77 command_util.ensure_workdir_exists(context)78 # OOPS:79 shutil.rmtree(context.workdir, ignore_errors=True)80 command_util.ensure_workdir_exists(context)81@given(u'I use the current directory as working directory')82def step_use_curdir_as_working_directory(context):83 """84 Uses the current directory as working directory85 """86 context.workdir = os.path.abspath(".")87 command_util.ensure_workdir_exists(context)88# -----------------------------------------------------------------------------89# STEPS: Create files with contents90# -----------------------------------------------------------------------------91@given(u'a file named "{filename}" and encoding="{encoding}" with')92def step_a_file_named_filename_and_encoding_with(context, filename, encoding):93 """Creates a textual file with the content provided as docstring."""94 __encoding_is_valid = True95 assert context.text is not None, "ENSURE: multiline text is provided."96 assert not os.path.isabs(filename)97 assert __encoding_is_valid98 command_util.ensure_workdir_exists(context)99 filename2 = os.path.join(context.workdir, filename)100 pathutil.create_textfile_with_contents(filename2, context.text, encoding)101@given(u'a file named "{filename}" with')102def step_a_file_named_filename_with(context, filename):103 """Creates a textual file with the content provided as docstring."""104 step_a_file_named_filename_and_encoding_with(context, filename, "UTF-8")105 # -- SPECIAL CASE: For usage with behave steps.106 if filename.endswith(".feature"):107 command_util.ensure_context_attribute_exists(context, "features", [])108 context.features.append(filename)109@given(u'an empty file named "{filename}"')110def step_an_empty_file_named_filename(context, filename):111 """112 Creates an empty file.113 """114 assert not os.path.isabs(filename)115 command_util.ensure_workdir_exists(context)116 filename2 = os.path.join(context.workdir, filename)117 pathutil.create_textfile_with_contents(filename2, "")118# -----------------------------------------------------------------------------119# STEPS: Run commands120# -----------------------------------------------------------------------------121@when(u'I run "{command}"')122@when(u'I run `{command}`')123def step_i_run_command(context, command):124 """125 Run a command as subprocess, collect its output and returncode.126 """127 command_util.ensure_workdir_exists(context)128 context.command_result = command_shell.run(command, cwd=context.workdir)129 command_util.workdir_save_coverage_files(context.workdir)130 if False and DEBUG:131 print(u"run_command: {0}".format(command))132 print(u"run_command.output {0}".format(context.command_result.output))133@when(u'I successfully run "{command}"')134@when(u'I successfully run `{command}`')135def step_i_successfully_run_command(context, command):136 step_i_run_command(context, command)137 step_it_should_pass(context)138@then(u'it should fail with result "{result:int}"')139def step_it_should_fail_with_result(context, result):140 assert_that(context.command_result.returncode, equal_to(result))141 assert_that(result, is_not(equal_to(0)))142@then(u'the command should fail with returncode="{result:int}"')143def step_it_should_fail_with_returncode(context, result):144 assert_that(context.command_result.returncode, equal_to(result))145 assert_that(result, is_not(equal_to(0)))146@then(u'the command returncode is "{result:int}"')147def step_the_command_returncode_is(context, result):148 assert_that(context.command_result.returncode, equal_to(result))149@then(u'the command returncode is non-zero')150def step_the_command_returncode_is_nonzero(context):151 assert_that(context.command_result.returncode, is_not(equal_to(0)))152@then(u'it should pass')153def step_it_should_pass(context):154 assert_that(context.command_result.returncode, equal_to(0),155 context.command_result.output)156@then(u'it should fail')157def step_it_should_fail(context):158 assert_that(context.command_result.returncode, is_not(equal_to(0)),159 context.command_result.output)160@then(u'it should pass with')161def step_it_should_pass_with(context):162 '''163 EXAMPLE:164 ...165 when I run "behave ..."166 then it should pass with:167 """168 TEXT169 """170 '''171 assert context.text is not None, "ENSURE: multiline text is provided."172 step_command_output_should_contain(context)173 assert_that(context.command_result.returncode, equal_to(0),174 context.command_result.output)175@then(u'it should fail with')176def step_it_should_fail_with(context):177 '''178 EXAMPLE:179 ...180 when I run "behave ..."181 then it should fail with:182 """183 TEXT184 """185 '''186 assert context.text is not None, "ENSURE: multiline text is provided."187 step_command_output_should_contain(context)188 assert_that(context.command_result.returncode, is_not(equal_to(0)))189# -----------------------------------------------------------------------------190# STEPS FOR: Output Comparison191# -----------------------------------------------------------------------------192@then(u'the command output should contain "{text}"')193def step_command_output_should_contain_text(context, text):194 '''195 EXAMPLE:196 ...197 Then the command output should contain "TEXT"198 '''199 expected_text = text200 if "{__WORKDIR__}" in expected_text or "{__CWD__}" in expected_text:201 expected_text = textutil.template_substitute(text,202 __WORKDIR__ = posixpath_normpath(context.workdir),203 __CWD__ = posixpath_normpath(os.getcwd())204 )205 actual_output = context.command_result.output206 with on_assert_failed_print_details(actual_output, expected_text):207 textutil.assert_normtext_should_contain(actual_output, expected_text)208@then(u'the command output should not contain "{text}"')209def step_command_output_should_not_contain_text(context, text):210 '''211 EXAMPLE:212 ...213 then the command output should not contain "TEXT"214 '''215 expected_text = text216 if "{__WORKDIR__}" in text or "{__CWD__}" in text:217 expected_text = textutil.template_substitute(text,218 __WORKDIR__ = posixpath_normpath(context.workdir),219 __CWD__ = posixpath_normpath(os.getcwd())220 )221 actual_output = context.command_result.output222 with on_assert_failed_print_details(actual_output, expected_text):223 textutil.assert_normtext_should_not_contain(actual_output, expected_text)224@then(u'the command output should contain "{text}" {count:d} times')225def step_command_output_should_contain_text_multiple_times(context, text, count):226 '''227 EXAMPLE:228 ...229 Then the command output should contain "TEXT" 3 times230 '''231 assert count >= 0232 expected_text = text233 if "{__WORKDIR__}" in expected_text or "{__CWD__}" in expected_text:234 expected_text = textutil.template_substitute(text,235 __WORKDIR__ = posixpath_normpath(context.workdir),236 __CWD__ = posixpath_normpath(os.getcwd())237 )238 actual_output = context.command_result.output239 with on_assert_failed_print_details(actual_output, expected_text):240 textutil.assert_normtext_should_contain_multiple_times(actual_output,241 expected_text,242 count)243@then(u'the command output should contain exactly "{text}"')244def step_command_output_should_contain_exactly_text(context, text):245 """246 Verifies that the command output of the last command contains the247 expected text.248 .. code-block:: gherkin249 When I run "echo Hello"250 Then the command output should contain "Hello"251 """252 expected_text = text253 if "{__WORKDIR__}" in text or "{__CWD__}" in text:254 expected_text = textutil.template_substitute(text,255 __WORKDIR__ = posixpath_normpath(context.workdir),256 __CWD__ = posixpath_normpath(os.getcwd())257 )258 actual_output = context.command_result.output259 textutil.assert_text_should_contain_exactly(actual_output, expected_text)260@then(u'the command output should not contain exactly "{text}"')261def step_command_output_should_not_contain_exactly_text(context, text):262 expected_text = text263 if "{__WORKDIR__}" in text or "{__CWD__}" in text:264 expected_text = textutil.template_substitute(text,265 __WORKDIR__ = posixpath_normpath(context.workdir),266 __CWD__ = posixpath_normpath(os.getcwd())267 )268 actual_output = context.command_result.output269 textutil.assert_text_should_not_contain_exactly(actual_output, expected_text)270@then(u'the command output should contain')271def step_command_output_should_contain(context):272 '''273 EXAMPLE:274 ...275 when I run "behave ..."276 then it should pass277 and the command output should contain:278 """279 TEXT280 """281 '''282 assert context.text is not None, "REQUIRE: multi-line text"283 step_command_output_should_contain_text(context, context.text)284@then(u'the command output should not contain')285def step_command_output_should_not_contain(context):286 '''287 EXAMPLE:288 ...289 when I run "behave ..."290 then it should pass291 and the command output should not contain:292 """293 TEXT294 """295 '''296 assert context.text is not None, "REQUIRE: multi-line text"297 step_command_output_should_not_contain_text(context, context.text.strip())298@then(u'the command output should contain {count:d} times')299def step_command_output_should_contain_multiple_times(context, count):300 '''301 EXAMPLE:302 ...303 when I run "behave ..."304 then it should pass305 and the command output should contain 2 times:306 """307 TEXT308 """309 '''310 assert context.text is not None, "REQUIRE: multi-line text"311 step_command_output_should_contain_text_multiple_times(context,312 context.text, count)313@then(u'the command output should contain exactly')314def step_command_output_should_contain_exactly_with_multiline_text(context):315 assert context.text is not None, "REQUIRE: multi-line text"316 step_command_output_should_contain_exactly_text(context, context.text)317@then(u'the command output should not contain exactly')318def step_command_output_should_contain_not_exactly_with_multiline_text(context):319 assert context.text is not None, "REQUIRE: multi-line text"320 step_command_output_should_not_contain_exactly_text(context, context.text)321# -----------------------------------------------------------------------------322# STEPS FOR: Directories323# -----------------------------------------------------------------------------324@step(u'I remove the directory "{directory}"')325def step_remove_directory(context, directory):326 path_ = directory327 if not os.path.isabs(directory):328 path_ = os.path.join(context.workdir, os.path.normpath(directory))329 if os.path.isdir(path_):330 shutil.rmtree(path_, ignore_errors=True)331 assert_that(not os.path.isdir(path_))332@given(u'I ensure that the directory "{directory}" does not exist')333def step_given_the_directory_should_not_exist(context, directory):334 step_remove_directory(context, directory)335@given(u'a directory named "{path}"')336def step_directory_named_dirname(context, path):337 assert context.workdir, "REQUIRE: context.workdir"338 path_ = os.path.join(context.workdir, os.path.normpath(path))339 if not os.path.exists(path_):340 os.makedirs(path_)341 assert os.path.isdir(path_)342@then(u'the directory "{directory}" should exist')343def step_the_directory_should_exist(context, directory):344 path_ = directory345 if not os.path.isabs(directory):346 path_ = os.path.join(context.workdir, os.path.normpath(directory))347 assert_that(os.path.isdir(path_))348@then(u'the directory "{directory}" should not exist')349def step_the_directory_should_not_exist(context, directory):350 path_ = directory351 if not os.path.isabs(directory):352 path_ = os.path.join(context.workdir, os.path.normpath(directory))353 assert_that(not os.path.isdir(path_))354@step(u'the directory "{directory}" exists')355def step_directory_exists(context, directory):356 """357 Verifies that a directory exists.358 .. code-block:: gherkin359 Given the directory "abc.txt" exists360 When the directory "abc.txt" exists361 """362 step_the_directory_should_exist(context, directory)363@step(u'the directory "{directory}" does not exist')364def step_directory_named_does_not_exist(context, directory):365 """366 Verifies that a directory does not exist.367 .. code-block:: gherkin368 Given the directory "abc/" does not exist369 When the directory "abc/" does not exist370 """371 step_the_directory_should_not_exist(context, directory)372# -----------------------------------------------------------------------------373# FILE STEPS:374# -----------------------------------------------------------------------------375@step(u'a file named "{filename}" exists')376def step_file_named_filename_exists(context, filename):377 """378 Verifies that a file with this filename exists.379 .. code-block:: gherkin380 Given a file named "abc.txt" exists381 When a file named "abc.txt" exists382 """383 step_file_named_filename_should_exist(context, filename)384@step(u'a file named "{filename}" does not exist')385def step_file_named_filename_does_not_exist(context, filename):386 """387 Verifies that a file with this filename does not exist.388 .. code-block:: gherkin389 Given a file named "abc.txt" does not exist390 When a file named "abc.txt" does not exist391 """392 step_file_named_filename_should_not_exist(context, filename)393@then(u'a file named "{filename}" should exist')394def step_file_named_filename_should_exist(context, filename):395 command_util.ensure_workdir_exists(context)396 filename_ = pathutil.realpath_with_context(filename, context)397 assert_that(os.path.exists(filename_) and os.path.isfile(filename_))398@then(u'a file named "{filename}" should not exist')399def step_file_named_filename_should_not_exist(context, filename):400 command_util.ensure_workdir_exists(context)401 filename_ = pathutil.realpath_with_context(filename, context)402 assert_that(not os.path.exists(filename_))403# -----------------------------------------------------------------------------404# STEPS FOR FILE CONTENTS:405# -----------------------------------------------------------------------------406@then(u'the file "{filename}" should contain "{text}"')407def step_file_should_contain_text(context, filename, text):408 expected_text = text409 if "{__WORKDIR__}" in text or "{__CWD__}" in text:410 expected_text = textutil.template_substitute(text,411 __WORKDIR__ = posixpath_normpath(context.workdir),412 __CWD__ = posixpath_normpath(os.getcwd())413 )414 file_contents = pathutil.read_file_contents(filename, context=context)415 file_contents = file_contents.rstrip()416 if file_contents_normalizer:417 # -- HACK: Inject TextProcessor as text normalizer418 file_contents = file_contents_normalizer(file_contents)419 with on_assert_failed_print_details(file_contents, expected_text):420 textutil.assert_normtext_should_contain(file_contents, expected_text)421@then(u'the file "{filename}" should not contain "{text}"')422def step_file_should_not_contain_text(context, filename, text):423 file_contents = pathutil.read_file_contents(filename, context=context)424 file_contents = file_contents.rstrip()425 textutil.assert_normtext_should_not_contain(file_contents, text)426 # XXX assert_that(file_contents, is_not(contains_string(text)))427@then(u'the file "{filename}" should contain')428def step_file_should_contain_multiline_text(context, filename):429 assert context.text is not None, "REQUIRE: multiline text"430 step_file_should_contain_text(context, filename, context.text)431@then(u'the file "{filename}" should not contain')432def step_file_should_not_contain_multiline_text(context, filename):433 assert context.text is not None, "REQUIRE: multiline text"...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Behave automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful