Best Python code snippet using pytest-play_python
test_plugin.py
Source: test_plugin.py
1from collections.abc import Iterable2from pathlib import Path3from typing import Type4import pytest5from _pytest._code import Source6from _pytest.pytester import RunResult7from pytest_lambda import not_implemented_fixture, lambda_fixture, static_fixture8TEST_DIR: Path = Path(__file__).parent9REPO_DIR: Path = TEST_DIR.parent10class AppendableSource(Source):11 def __add__(self, other: Source):12 if isinstance(other, str):13 other = self.__class__(other)14 if isinstance(other, Source):15 other_lines = other.lines16 elif isinstance(other, Iterable):17 other_lines = [str(line) for line in other]18 else:19 raise TypeError(f'Expected an iterable or Source instance, got {type(other)}')20 return self.__class__(self.lines + other_lines)21# Whether pytest-camel-collect is already loaded.22# Used to prevent double-loading the plugin, if it's already been pip-installed.23#24# Because we don't specifically ask pytest to load camel-collect,25# the only reason it ought to be loaded is because `setup.py install` has been run.26# In that case, we don't want to request the plugin to be loaded, or pytest will error.27#28is_camel_collect_plugin_loaded = lambda_fixture(29 lambda request:30 request.config.pluginmanager.has_plugin('camel_collect'))31# Contents of conftest.py in temporary test folder32conftest_contents = lambda_fixture(33 lambda is_camel_collect_plugin_loaded:34 AppendableSource(35 'pytest_plugins = "pytest_camel_collect.plugin"' if not is_camel_collect_plugin_loaded else ''36 ))37# Contents of pytest.ini in temporary test folder38pytest_ini_contents = static_fixture(AppendableSource('''39 [pytest]40 python_files = *.py41'''))42def find_in_test_output(pattern: str, test_result: RunResult) -> bool:43 """Return whether the pattern was fnmatched in test_result's stdout44 """45 try:46 test_result.stdout.fnmatch_lines(pattern)47 except pytest.fail.Exception:48 return False49 else:50 return True51@pytest.fixture(autouse=True)52def setup_syspath(testdir):53 testdir.syspathinsert(REPO_DIR)54@pytest.fixture(autouse=True)55def setup_conftest(testdir, conftest_contents):56 testdir.makeconftest(conftest_contents)57@pytest.fixture(autouse=True)58def setup_pytest_ini(testdir, pytest_ini_contents):59 testdir.makeini(pytest_ini_contents)60class UsingPyTestIniPythonClasses:61 """Mixin to set the value of python_classes in pytest.ini"""62 # Value of `python_classes` to place in pytest.ini63 pytest_python_classes = lambda_fixture('default_pytest_python_classes')64 # The default python_classes setting (simply "Test", at time of writing)65 default_pytest_python_classes = lambda_fixture(66 lambda request:67 request.config._parser._inidict['python_classes'][2]) # description, type, *default*68 # Adds `python_classes` to pytest.ini69 pytest_ini_contents = lambda_fixture(70 lambda pytest_ini_contents, pytest_python_classes:71 pytest_ini_contents + f'python_classes = {pytest_python_classes}')72def WithPyTestIniPythonClasses(python_classes: str) -> Type[UsingPyTestIniPythonClasses]:73 """Returns mixin class adding the specified python_classes setting to pytest.ini74 Usage:75 class TestMyClass(76 WithPyTestIniPythonClasses('Pattern-*'),77 ):78 # ...79 """80 class CustomPytestIniPythonClasses(UsingPyTestIniPythonClasses):81 pytest_python_classes = static_fixture(python_classes)82 return CustomPytestIniPythonClasses83class RunPyTest:84 """Mixin to run a pytest session at each test and store result in test_result fixture"""85 # Source of test file to be tested86 test_source = not_implemented_fixture()87 # Physical test file to be tested88 test_file = lambda_fixture(lambda testdir, test_source: testdir.makepyfile(test_source))89 # Result of running the py.test session90 test_result = lambda_fixture(lambda testdir, test_file: testdir.runpytest_inprocess(test_file, '--verbose'),91 autouse=True)92class VerifyPyTestCollection:93 """Mixin to verify the collection/non-collection of tests during a pytest session"""94 # Names of tests which ought to be collected95 expected_collected_tests = not_implemented_fixture()96 # Names of tests which ought not to be collected97 unexpected_collected_tests = not_implemented_fixture()98 def it_collects_expected_tests(self, expected_collected_tests, test_result):99 # XXX: this check can give false positives if test names are not specific enough100 expected = set(expected_collected_tests)101 actual = {name102 for name in expected_collected_tests103 if find_in_test_output(f'*{name}*', test_result)}104 assert expected == actual, 'py.test did not collect expected test(s)'105 def it_doesnt_collect_unexpected_tests(self, unexpected_collected_tests, test_result):106 # XXX: this check can give false negatives if test names are not specific enough107 expected = set(unexpected_collected_tests)108 actual = {name109 for name in unexpected_collected_tests110 if not find_in_test_output(f'*{name}*', test_result)}111 assert expected == actual, 'py.test collected unexpected test(s)'112class StrictVerifyPyTestCollection(VerifyPyTestCollection):113 """Mixin to verify only the specified tests were collected"""114 # TODO115class TestCamelCollector(116 RunPyTest,117):118 test_source = static_fixture('''119 def test_sanity_check():120 # I should always be collected121 pass122 class ForTheLoveOfCollection:123 def test_on_camel_boundary(self):124 pass125 class ForTheChildren:126 def test_child_on_camel_boundary(self):127 pass128 class ForgiveMeFatherForIHaveNotCollected:129 def test_not_on_camel_boundary(self):130 pass131 class ForgiveTheChildren:132 def test_child_not_on_camel_boundary(self):133 pass134 ''')135 class WithCamelWordBoundaries(136 VerifyPyTestCollection,137 WithPyTestIniPythonClasses('For-*'), # with a dash to only match word boundaries138 ):139 expected_collected_tests = static_fixture([140 'test_sanity_check',141 'test_on_camel_boundary',142 'test_child_on_camel_boundary',143 ])144 unexpected_collected_tests = static_fixture([145 'test_not_on_camel_boundary',146 'test_child_not_on_camel_boundary',147 ])148 class WithoutCamelWordBoundaries(149 VerifyPyTestCollection,150 WithPyTestIniPythonClasses('For*'), # without a dash to match substring anywhere, even across word boundaries151 ):152 expected_collected_tests = static_fixture([153 'test_sanity_check',154 'test_on_camel_boundary',155 'test_child_on_camel_boundary',156 'test_not_on_camel_boundary',157 'test_child_not_on_camel_boundary',158 ])...
test_repeat.py
Source: test_repeat.py
1import pytest2@pytest.fixture3def conftest_contents():4 return """5import pytest6@pytest.fixture(autouse=True)7def __pytest_repeater_play_test(request):8 pass9@pytest.hookimpl(trylast=True)10def pytest_generate_tests(metafunc):11 metafunc.parametrize(12 '__pytest_repeater_play_test',13 range(2),14 indirect=True,15 )16"""17def test_repeater(testdir, conftest_contents):...
Check out the latest blogs from LambdaTest on this topic:
In today’s data-driven world, the ability to access and analyze large amounts of data can give researchers, businesses & organizations a competitive edge. One of the most important & free sources of this data is the Internet, which can be accessed and mined through web scraping.
In addition to the four values, the Agile Manifesto contains twelve principles that are used as guides for all methodologies included under the Agile movement, such as XP, Scrum, and Kanban.
Sometimes, in our test code, we need to handle actions that apparently could not be done automatically. For example, some mouse actions such as context click, double click, drag and drop, mouse movements, and some special key down and key up actions. These specific actions could be crucial depending on the project context.
Have you ever visited a website that only has plain text and images? Most probably, no. It’s because such websites do not exist now. But there was a time when websites only had plain text and images with almost no styling. For the longest time, websites did not focus on user experience. For instance, this is how eBay’s homepage looked in 1999.
Unit testing is typically software testing within the developer domain. As the QA role expands in DevOps, QAOps, DesignOps, or within an Agile team, QA testers often find themselves creating unit tests. QA testers may create unit tests within the code using a specified unit testing tool, or independently using a variety of methods.
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!!