Python pytest.fixture() Examples

The following are 30 code examples of pytest.fixture(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pytest , or try the search function .
Example #1
Source File: test_schema_validation.py    From drydock with Apache License 2.0 7 votes vote down vote up
def _test_validate(self, schema, expect_failure, input_files, input):
        """validates input yaml against schema.

        :param schema: schema yaml file
        :param expect_failure: should the validation pass or fail.
        :param input_files: pytest fixture used to access the test input files
        :param input: test input yaml doc filename"""
        schema_dir = pkg_resources.resource_filename('drydock_provisioner',
                                                     'schemas')
        schema_filename = os.path.join(schema_dir, schema)
        schema_file = open(schema_filename, 'r')
        schema = yaml.safe_load(schema_file)

        input_file = input_files.join(input)
        instance_file = open(str(input_file), 'r')
        instance = yaml.safe_load(instance_file)

        if expect_failure:
            with pytest.raises(ValidationError):
                jsonschema.validate(instance['spec'], schema['data'])
        else:
            jsonschema.validate(instance['spec'], schema['data']) 
Example #2
Source File: test_shape_base.py    From recruit with Apache License 2.0 6 votes vote down vote up
def block(self, request):
        # blocking small arrays and large arrays go through different paths.
        # the algorithm is triggered depending on the number of element
        # copies required.
        # We define a test fixture that forces most tests to go through
        # both code paths.
        # Ultimately, this should be removed if a single algorithm is found
        # to be faster for both small and large arrays.
        def _block_force_concatenate(arrays):
            arrays, list_ndim, result_ndim, _ = _block_setup(arrays)
            return _block_concatenate(arrays, list_ndim, result_ndim)

        def _block_force_slicing(arrays):
            arrays, list_ndim, result_ndim, _ = _block_setup(arrays)
            return _block_slicing(arrays, list_ndim, result_ndim)

        if request.param == 'force_concatenate':
            return _block_force_concatenate
        elif request.param == 'force_slicing':
            return _block_force_slicing
        elif request.param == 'block':
            return block
        else:
            raise ValueError('Unknown blocking request. There is a typo in the tests.') 
Example #3
Source File: test_coverage.py    From brownie with MIT License 6 votes vote down vote up
def test_always_transact(plugintester, mocker, rpc):
    mocker.spy(rpc, "undo")

    result = plugintester.runpytest()
    result.assert_outcomes(passed=1)
    assert rpc.undo.call_count == 0

    # with coverage eval
    result = plugintester.runpytest("--coverage")
    result.assert_outcomes(passed=1)
    assert rpc.undo.call_count == 1

    # with coverage and no_call_coverage fixture
    plugintester.makeconftest(conf_source)
    result = plugintester.runpytest("--coverage")
    result.assert_outcomes(passed=1)
    assert rpc.undo.call_count == 1 
Example #4
Source File: test_freezegun.py    From pytest-freezegun with MIT License 6 votes vote down vote up
def test_freezing_time_in_fixture(testdir):
    testdir.makepyfile("""
        import pytest
        from datetime import date, datetime

        @pytest.fixture
        def today():
            return datetime.now().date()

        @pytest.mark.freeze_time('2017-05-20 15:42')
        def test_sth(today):
            assert today == date(2017, 5, 20)
    """)

    result = testdir.runpytest('-v', '-s')
    assert result.ret == 0 
Example #5
Source File: conftest.py    From gql with MIT License 6 votes vote down vote up
def server(request):
    """Fixture used to start a dummy server to test the client behaviour.

    It can take as argument either a handler function for the websocket server for
    complete control OR an array of answers to be sent by the default server handler.
    """

    server_handler = get_server_handler(request)

    try:
        test_server = WebSocketServer()

        # Starting the server with the fixture param as the handler function
        await test_server.start(server_handler)

        yield test_server
    except Exception as e:
        print("Exception received in server fixture:", e)
    finally:
        await test_server.stop() 
Example #6
Source File: conftest.py    From gql with MIT License 6 votes vote down vote up
def ws_ssl_server(request):
    """Websockets server fixture using SSL.

    It can take as argument either a handler function for the websocket server for
    complete control OR an array of answers to be sent by the default server handler.
    """

    server_handler = get_server_handler(request)

    try:
        test_server = WebSocketServer(with_ssl=True)

        # Starting the server with the fixture param as the handler function
        await test_server.start(server_handler)

        yield test_server
    except Exception as e:
        print("Exception received in ws server fixture:", e)
    finally:
        await test_server.stop() 
Example #7
Source File: test_api_tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def test_create_task(self, falcontest, blank_state):
        url = '/api/v1.0/tasks'

        req_hdr = {
            'Content-Type': 'application/json',
            'X-IDENTITY-STATUS': 'Confirmed',
            'X-USER-NAME': 'Test',
            'X-ROLES': 'admin',
        }

        json_body = json.dumps({
            'action': 'verify_site',
            'design_ref': 'http://foo.com',
        })

        resp = falcontest.simulate_post(url, headers=req_hdr, body=json_body)

        assert resp.status == falcon.HTTP_201
        assert resp.headers.get('Location') is not None

    # TODO(sh8121att) Make this a general fixture in conftest.py 
Example #8
Source File: conftest.py    From goodtables-py with MIT License 6 votes vote down vote up
def log():
    def fixture(struct):
        # Pack errors/report to tuples list log:
        # - format for errors: (row-number, column-number, code)
        # - format for report: (table-number, row-number, column-number, code)
        result = []
        def pack_error(error, table_number='skip'):
            error = dict(error)
            error = [
                error.get('row-number'),
                error.get('column-number'),
                error.get('code'),
            ]
            if table_number != 'skip':
                error = [table_number] + error
            return tuple(error)
        if isinstance(struct, list):
            for error in struct:
                result.append(pack_error(error))
        if isinstance(struct, dict):
            for table_number, table in enumerate(struct['tables'], start=1):
                for error in table['errors']:
                    result.append(pack_error(error, table_number))
        return result
    return fixture 
Example #9
Source File: test_api_builddata.py    From drydock with Apache License 2.0 6 votes vote down vote up
def test_read_builddata_all(self, falcontest, seeded_builddata):
        """Test that by default the API returns all build data for a node."""
        url = '/api/v1.0/nodes/foo/builddata'

        # Seed the database with build data
        nodelist = ['foo']
        count = 3
        seeded_builddata(nodelist=nodelist, count=count)

        # TODO(sh8121att) Make fixture for request header forging
        hdr = {
            'Content-Type': 'application/json',
            'X-IDENTITY-STATUS': 'Confirmed',
            'X-USER-NAME': 'Test',
            'X-ROLES': 'admin'
        }

        resp = falcontest.simulate_get(url, headers=hdr)

        assert resp.status == falcon.HTTP_200

        resp_body = resp.json

        assert len(resp_body) == count 
Example #10
Source File: test_general_course_data_view.py    From figures with MIT License 6 votes vote down vote up
def test_get_with_course_id_for_other_site(self):
        """
        This tests if the course can't be found in the organization

        This test is incomplete
        """
        with mock.patch('figures.helpers.settings.FEATURES', {'FIGURES_IS_MULTISITE': True}):
            assert figures.helpers.is_multisite()

            # Stand up other site. Candidate for a fixture
            other_site = SiteFactory(domain='other.site')
            other_org = OrganizationFactory(sites=[other_site])
            course = CourseOverviewFactory(org=other_org.short_name)

            request = APIRequestFactory().get(self.request_path)
            force_authenticate(request, user=self.staff_user)
            view = self.view_class.as_view({'get': 'retrieve'})
            response = view(request, pk=str(course.id))
            assert response.status_code == 403 
Example #11
Source File: conftest.py    From brownie with MIT License 6 votes vote down vote up
def pytest_addoption(parser):
    parser.addoption(
        "--target",
        choices=["core", "pm", "plugin"],
        default="core",
        help="Target a specific component of the tests.",
    )
    parser.addoption(
        "--evm",
        nargs=3,
        metavar=("solc_versions", "evm_rulesets", "optimizer_runs"),
        help="Run evm tests against a matrix of solc versions, evm versions, and compiler runs.",
    )


# remove tests based on config flags and fixture names 
Example #12
Source File: conftest.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def migrations(transactional_db):
    """
    This fixture returns a helper object to test Django data migrations.
    Based on: https://gist.github.com/bennylope/82a6088c02fefdd47e18f3c04ec167af
    """

    class Migrator(object):
        def migrate(self, app, to):
            migration = [(app, to)]
            executor = MigrationExecutor(connection)
            executor.migrate(migration)
            return executor.loader.project_state(migration).apps

        def reset(self):
            call_command("migrate", no_input=True)

    return Migrator() 
Example #13
Source File: test_course_monthly_metrics_viewset.py    From figures with MIT License 6 votes vote down vote up
def sog_data():
    """Fixture to create site, organization, and course overview

    This fixture exists mostly to help abstract multisite handing from tests

    Returns a dict of 'site', 'organization', and 'course_overview' objects
    """
    site = SiteFactory()
    course_overview = CourseOverviewFactory()
    if organizations_support_sites():
        organization = OrganizationFactory(sites=[site])
    else:
        organization = OrganizationFactory()
    OrganizationCourseFactory(organization=organization,
                              course_id=str(course_overview.id))
    return dict(
        site=site,
        organization=organization,
        course_overview=course_overview) 
Example #14
Source File: test_qtutils.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def test_version_check(monkeypatch, qversion, compiled, pyqt, version, exact,
                       expected):
    """Test for version_check().

    Args:
        monkeypatch: The pytest monkeypatch fixture.
        qversion: The version to set as fake qVersion().
        compiled: The value for QT_VERSION_STR (set compiled=False)
        pyqt: The value for PYQT_VERSION_STR (set compiled=False)
        version: The version to compare with.
        exact: Use exact comparing (==)
        expected: The expected result.
    """
    monkeypatch.setattr(qtutils, 'qVersion', lambda: qversion)
    if compiled is not None:
        monkeypatch.setattr(qtutils, 'QT_VERSION_STR', compiled)
        monkeypatch.setattr(qtutils, 'PYQT_VERSION_STR', pyqt)
        compiled_arg = True
    else:
        compiled_arg = False

    actual = qtutils.version_check(version, exact, compiled=compiled_arg)
    assert actual == expected 
Example #15
Source File: integration_tests.py    From activitywatch with Mozilla Public License 2.0 6 votes vote down vote up
def test_integration(server_process):
    # This is just here so that the server_process fixture is initialized
    pass

    # exit_code = pytest.main(["./aw-server/tests", "-v"])
    # if exit_code != 0:
    #     pytest.fail("Tests exited with non-zero code: " + str(exit_code)) 
Example #16
Source File: test_moler_test.py    From moler with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_exception_in_observer_is_raised_if_no_result_called_but_decorator_on_method(do_nothing_connection_observer,
                                                                                     ObserverExceptionClass):
    from moler.util.moler_test import MolerTest
    exc = ObserverExceptionClass("some error inside observer")

    class MyTest(object):
        @MolerTest.raise_background_exceptions()
        # @MolerTest.raise_background_exceptions  # doesn't work since it is created by python and given class as first argument
        #                                               # compare with syntax of @pytest.fixture  @pytest.yield_fixture
        def method_using_observer(self):
            observer = do_nothing_connection_observer
            observer.set_exception(exc)

    with pytest.raises(ExecutionException) as err:
        MyTest().method_using_observer()
    ConnectionObserver.get_unraised_exceptions() 
Example #17
Source File: conftest.py    From mutatest with MIT License 6 votes vote down vote up
def mock_source_and_targets():
    """Mock source file with uncovered/covered targets to use with mock_coverage_file.

    Covered lines include: 1, 2, 4
    """
    # see mock_coverage_file fixture
    source_file = Path("file3.py")
    targets = {
        LocIndex(ast_class="AugAssign", lineno=1, col_offset=1, op_type="o"),
        LocIndex(ast_class="AugAssign", lineno=2, col_offset=1, op_type="o"),
        LocIndex(ast_class="AugAssign", lineno=3, col_offset=1, op_type="o"),
        LocIndex(ast_class="BinOp", lineno=4, col_offset=1, op_type="o"),
        LocIndex(ast_class="BinOp", lineno=5, col_offset=1, op_type="o"),
    }
    return SourceAndTargets(source_file, targets)


####################################################################################################
# TRANSFORMERS: AUGASSIGN FIXTURES
#################################################################################################### 
Example #18
Source File: conftest.py    From mutatest with MIT License 6 votes vote down vote up
def mock_coverage_file(tmp_path_factory):
    """Mock .coverage file to read into the CoverageOptimizer."""

    folder = tmp_path_factory.mktemp("cov")

    # aligned to fixture mock_source_and_targets for file3.py used in positive filter.
    mock_contents = {
        "file1.py": [1],
        "file2.py": [1, 3, 4],
        "file3.py": [1, 2, 4],
    }

    mock_cov_file = folder / ".coverage"
    str_cov_file = str(mock_cov_file.resolve())
    write_cov_file(mock_contents, str_cov_file)

    yield mock_cov_file

    mock_cov_file.unlink() 
Example #19
Source File: hmc_definition_fixtures.py    From python-zhmcclient with Apache License 2.0 5 votes vote down vote up
def fixtureid_hmc_definition(fixture_value):
    """
    Return a fixture ID to be used by pytest, for fixture `hmc_definition()`.

    Parameters:
      * fixture_value (HMCDefinition): The HMC definition of the HMC the test
        runs against.
    """
    hd = fixture_value
    assert isinstance(hd, HMCDefinition)
    return "hmc_definition={}".format(hd.nickname) 
Example #20
Source File: test_states.py    From salt-toaster with MIT License 5 votes vote down vote up
def test_pkg_latest_version(setup):
    config, initconfig = setup
    master = config['masters'][0]
    minion = master['minions'][0]
    def test(master, minion):
        try:
            resp = master['fixture'].salt(minion['id'], 'state.apply latest')
            assert resp
            assert minion['id'] in resp
            assert resp[minion['id']][
                'pkg_|-latest-version_|-test-package_|-latest']['result'] is True
            return True
        except TypeError:
            return False
    assert retry(partial(test, master, minion)) 
Example #21
Source File: test_position_caret.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def caret_tester(js_tester_webkit, qtbot):
    """Helper fixture to test caret browsing positions."""
    caret_tester = CaretTester(js_tester_webkit, qtbot)
    # Showing webview here is necessary for test_scrolled_down_img to
    # succeed in some cases, see #1988
    caret_tester.js.tab.show()
    return caret_tester 
Example #22
Source File: test_states.py    From salt-toaster with MIT License 5 votes vote down vote up
def test_patches_installed_downloadonly_sles(setup):
    config, initconfig = setup
    master = config['masters'][0]
    minion = master['minions'][0]
    patches = master['fixture'].salt(minion['id'],
        'cmd.run "zypper --quiet patches | cut -d\'|\' -f2 | cut -d\' \' -f2"'
        )[minion['id']].encode('utf-8').split(os.linesep)
    patches = {"patches": filter(lambda x: "SUSE-SLE-SERVER" in x, patches)[:2]}
    list_pkgs_pre = master['fixture'].salt(minion['id'], 'pkg.list_pkgs')
    resp = master['fixture'].salt(minion['id'], 'state.apply patches-downloaded pillar=\'{0}\''.format(patches))
    list_pkgs_post = master['fixture'].salt(minion['id'], 'pkg.list_pkgs')
    assert resp[minion['id']]['pkg_|-test-patches-downloaded_|-test-patches-downloaded_|-installed']['result'] is True
    assert list_pkgs_pre == list_pkgs_post 
Example #23
Source File: test_all_priors.py    From decompose with MIT License 5 votes vote down vote up
def PriorDistribution(request):
    """A fixture that provides a prior distribution at a time."""
    prior = request.param
    return(prior) 
Example #24
Source File: fixtures.py    From brownie with MIT License 5 votes vote down vote up
def a(self):
        """Short form of the accounts fixture."""
        yield brownie.accounts 
Example #25
Source File: conftest.py    From brownie with MIT License 5 votes vote down vote up
def isolatedtester(plugintester):
    conf_source = """
import pytest

@pytest.fixture(autouse=True)
def isolation(module_isolation):
    pass
    """
    plugintester.makeconftest(conf_source)
    yield plugintester 
Example #26
Source File: conftest.py    From brownie with MIT License 5 votes vote down vote up
def pytest_generate_tests(metafunc):
    # parametrize the evmtester fixture
    evm_config = metafunc.config.getoption("--evm")
    if "evmtester" in metafunc.fixturenames and evm_config:
        params = list(itertools.product(*evm_config))
        metafunc.parametrize("evmtester", params, indirect=True)


# travis cannot call github ethereum/solidity API, so this method is patched 
Example #27
Source File: conftest.py    From brownie with MIT License 5 votes vote down vote up
def pytest_collection_modifyitems(config, items):
    if config.getoption("--evm"):
        target = "evm"
    else:
        target = config.getoption("--target")

    for flag, fixture in TARGET_OPTS.items():
        if target == flag:
            continue
        for test in [i for i in items if fixture in i.fixturenames]:
            items.remove(test)
    if target != "core":
        fixtures = set(TARGET_OPTS.values())
        for test in [i for i in items if not fixtures.intersection(i.fixturenames)]:
            items.remove(test) 
Example #28
Source File: conftest.py    From aioredis with MIT License 5 votes vote down vote up
def pytest_configure(config):
    bins = config.getoption('--redis-server')[:]
    cmd = 'which redis-server'
    if not bins:
        with os.popen(cmd) as pipe:
            path = pipe.read().rstrip()
        assert path, (
            "There is no redis-server on your computer."
            " Please install it first")
        REDIS_SERVERS[:] = [path]
    else:
        REDIS_SERVERS[:] = bins

    VERSIONS.update({srv: _read_server_version(srv)
                     for srv in REDIS_SERVERS})
    assert VERSIONS, ("Expected to detect redis versions", REDIS_SERVERS)

    class DynamicFixturePlugin:
        @pytest.fixture(scope='session',
                        params=REDIS_SERVERS,
                        ids=format_version)
        def server_bin(self, request):
            """Common for start_server and start_sentinel
            server bin path parameter.
            """
            return request.param
    config.pluginmanager.register(DynamicFixturePlugin(), 'server-bin-fixture')

    if config.getoption('--uvloop'):
        try:
            import uvloop
        except ImportError:
            raise RuntimeError(
                "Can not import uvloop, make sure it is installed")
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) 
Example #29
Source File: conftest.py    From aioredis with MIT License 5 votes vote down vote up
def pytest_runtest_setup(item):
    is_coro = inspect.iscoroutinefunction(item.obj)
    if is_coro and 'loop' not in item.fixturenames:
        # inject an event loop fixture for all async tests
        item.fixturenames.append('loop') 
Example #30
Source File: test_version.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def commit_file_mock(self, mocker):
        """Fixture providing a mock for utils.read_file for git-commit-id.

        On fixture teardown, it makes sure it got called with git-commit-id as
        argument.
        """
        mocker.patch('qutebrowser.utils.version.subprocess',
                     side_effect=AssertionError)
        m = mocker.patch('qutebrowser.utils.version.utils.read_file')
        yield m
        m.assert_called_with('git-commit-id')