Best Python code snippet using lisa_python
dockersuite.py
Source:dockersuite.py
...170 "There may have been errors when the container was run. "171 f"String Identifier: {string_identifier}. "172 f"Docker Run Output: {docker_run_output}."173 ).is_equal_to(string_identifier)174 def _skip_if_not_supported(self, node: Node) -> None:175 if isinstance(node.os, Redhat) and node.os.information.version < "7.0.0":176 raise SkippedException(177 f"Test not supported for RH/CentOS {node.os.information.release}"178 )179 def _verify_and_remove_containers(180 self, node: Node, docker_image_name: str, docker_container_name: str181 ) -> Docker:182 self._skip_if_not_supported(node)183 docker_tool = node.tools[Docker]184 self._verify_docker_engine(node)185 docker_tool.remove_image(docker_image_name)186 docker_tool.remove_container(docker_container_name)187 return docker_tool188 def _verify_docker_engine(self, node: Node) -> None:189 node.log.debug(f"VerifyDockerEngine on {node.os.information.vendor.lower()}")190 result = node.execute(191 "docker run hello-world",192 expected_exit_code=0,193 expected_exit_code_failure_message="Fail to run docker run hello-world",194 sudo=True,195 )196 node.log.debug(f"VerifyDockerEngine: hello-world output - {result.stdout}")
verify_examples.py
Source:verify_examples.py
...10import shlex11# This fixture is tightly coupled with output formats. Since these tests are12# more fragile than others, we should pin it to a specific version.13SUPPORTED_VERSIONS = ["6.2"]14def _skip_if_not_supported():15 for version in SUPPORTED_VERSIONS:16 supp_nums = version.split(".")17 found_nums = pytest.__version__.split(".")18 if found_nums[:len(supp_nums)] == supp_nums:19 return20 pytest.skip(21 "Documentation examples only supported on pytest versions: "22 + repr(SUPPORTED_VERSIONS)23 )24TYPE_PYTHON = "python"25TYPE_OUTPUT = "output"26def extract_blocks(rst_text):27 """28 Given string rst text, extracts the python code blocks and literal blocks,29 returning them in a list.30 """31 all_examples = []32 current_type = None33 current_example = None34 for line in rst_text.splitlines():35 if current_type is not None:36 if current_example == []:37 if line.strip() == "":38 continue39 if not line.startswith(' '):40 # Not actually a block. Skip it.41 current_type = None42 current_example = None43 continue44 if (45 current_type == TYPE_OUTPUT46 and not line.strip().startswith("$ ")47 ):48 # Not something we care about. ditch it.49 current_type = None50 current_example = None51 continue52 if not (53 line.strip() == ""54 or line.startswith(" ")55 ):56 all_examples.append((current_type, current_example))57 current_type = None58 current_example = None59 else:60 current_example.append(line)61 continue62 if " ".join(line.split()) == ".. code-block:: python":63 current_type = TYPE_PYTHON64 current_example = []65 elif line.strip().endswith("::"):66 current_type = TYPE_OUTPUT67 current_example = []68 if current_example:69 all_examples.append((current_type, current_example))70 all_example_texts = []71 for example_type, example_lines in all_examples:72 while example_lines and example_lines[-1].strip() == "":73 example_lines.pop()74 example_text = dedent("\n".join(example_lines))75 all_example_texts.append((example_type, example_text))76 return all_example_texts77@pytest.fixture78def verify_one_example(testdir, monkeypatch, capsys, run_mypy):79 # Use a consistent width for the terminal output.80 monkeypatch.setenv("COLUMNS", "80")81 def _verify_pytest(args, expected_output):82 result = testdir.runpytest(*args)83 expected_lines = expected_output.splitlines()84 summary, inline, timepart = expected_lines[-1].partition(" in ")85 # Replace the actual running time with a glob, so the test isn't86 # dependent on that.87 timepart = "*" + timepart[timepart.index("s"):]88 expected_lines[-1] = "".join([summary, inline, timepart])89 result.stdout.fnmatch_lines([90 line91 for line in expected_lines92 # Don't match empty lines. Those might be useful for matching.93 if line.strip() != ""94 ])95 capsys.readouterr()96 def _verify_mypy(args, expected_output):97 stdout, *_ = run_mypy([str(testdir.tmpdir), *args])98 # Enforce an exact match, since there's not as much output as pytest.99 assert stdout.rstrip("\n") == expected_output.rstrip("\n")100 def _verify_one_example(code, *shell_blocks):101 testdir.makepyfile(code)102 for output in shell_blocks:103 command_line = output.splitlines()[0]104 cmd_tokens = shlex.split(command_line.lstrip("$ "))105 expected_output = "\n".join(output.splitlines()[1:])106 if cmd_tokens[0] == 'pytest':107 _verify_pytest(cmd_tokens[1:], expected_output)108 elif cmd_tokens[0] == 'mypy':109 _verify_mypy(cmd_tokens[1:], expected_output)110 else:111 pytest.fail(f"Unsupported command: {cmd_tokens[0]}")112 return _verify_one_example113@pytest.fixture114def verify_examples(verify_one_example):115 _skip_if_not_supported()116 def verify_examples(text):117 blocks = extract_blocks(text)118 last_python_block = None119 shell_blocks = []120 for block_type, block_text in blocks:121 if block_type == TYPE_PYTHON:122 if shell_blocks:123 verify_one_example(last_python_block, *shell_blocks)124 last_python_block = block_text125 shell_blocks = []126 continue127 if last_python_block is not None:128 shell_blocks.append(block_text)129 if last_python_block and shell_blocks:...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!