当前位置: 首页>>代码示例>>Python>>正文


Python pytest.fixture方法代码示例

本文整理汇总了Python中pytest.fixture方法的典型用法代码示例。如果您正苦于以下问题:Python pytest.fixture方法的具体用法?Python pytest.fixture怎么用?Python pytest.fixture使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pytest的用法示例。


在下文中一共展示了pytest.fixture方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: mock_coverage_file

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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() 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:21,代码来源:conftest.py

示例2: mock_source_and_targets

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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
#################################################################################################### 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:22,代码来源:conftest.py

示例3: test_read_builddata_all

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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 
开发者ID:airshipit,项目名称:drydock,代码行数:26,代码来源:test_api_builddata.py

示例4: test_create_task

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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 
开发者ID:airshipit,项目名称:drydock,代码行数:23,代码来源:test_api_tasks.py

示例5: _test_validate

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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']) 
开发者ID:airshipit,项目名称:drydock,代码行数:24,代码来源:test_schema_validation.py

示例6: ws_ssl_server

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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() 
开发者ID:graphql-python,项目名称:gql,代码行数:22,代码来源:conftest.py

示例7: server

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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() 
开发者ID:graphql-python,项目名称:gql,代码行数:22,代码来源:conftest.py

示例8: log

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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 
开发者ID:frictionlessdata,项目名称:goodtables-py,代码行数:27,代码来源:conftest.py

示例9: sog_data

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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) 
开发者ID:appsembler,项目名称:figures,代码行数:21,代码来源:test_course_monthly_metrics_viewset.py

示例10: test_get_with_course_id_for_other_site

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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 
开发者ID:appsembler,项目名称:figures,代码行数:21,代码来源:test_general_course_data_view.py

示例11: test_freezing_time_in_fixture

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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 
开发者ID:ktosiek,项目名称:pytest-freezegun,代码行数:18,代码来源:test_freezegun.py

示例12: test_version_check

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:25,代码来源:test_qtutils.py

示例13: migrations

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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() 
开发者ID:mozilla,项目名称:normandy,代码行数:19,代码来源:conftest.py

示例14: pytest_addoption

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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 
开发者ID:eth-brownie,项目名称:brownie,代码行数:18,代码来源:conftest.py

示例15: test_always_transact

# 需要导入模块: import pytest [as 别名]
# 或者: from pytest import fixture [as 别名]
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 
开发者ID:eth-brownie,项目名称:brownie,代码行数:19,代码来源:test_coverage.py


注:本文中的pytest.fixture方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。