Python pytest.ini() Examples

The following are 30 code examples of pytest.ini(). 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_config.py    From pytest with MIT License 7 votes vote down vote up
def test_toxini_before_lower_pytestini(self, testdir):
        sub = testdir.tmpdir.mkdir("sub")
        sub.join("tox.ini").write(
            textwrap.dedent(
                """
            [pytest]
            minversion = 2.0
        """
            )
        )
        testdir.tmpdir.join("pytest.ini").write(
            textwrap.dedent(
                """
            [pytest]
            minversion = 1.5
        """
            )
        )
        config = testdir.parseconfigure(sub)
        assert config.getini("minversion") == "2.0" 
Example #2
Source File: test_config.py    From pytest with MIT License 6 votes vote down vote up
def test_config_in_subdirectory_colon_command_line_issue2148(testdir):
    conftest_source = """
        def pytest_addoption(parser):
            parser.addini('foo', 'foo')
    """

    testdir.makefile(
        ".ini",
        **{"pytest": "[pytest]\nfoo = root", "subdir/pytest": "[pytest]\nfoo = subdir"},
    )

    testdir.makepyfile(
        **{
            "conftest": conftest_source,
            "subdir/conftest": conftest_source,
            "subdir/test_foo": """\
            def test_foo(pytestconfig):
                assert pytestconfig.getini('foo') == 'subdir'
            """,
        }
    )

    result = testdir.runpytest("subdir/test_foo.py::test_foo")
    assert result.ret == 0 
Example #3
Source File: conftest.py    From fastats with MIT License 6 votes vote down vote up
def add_preconfigured_np(doctest_namespace):
    """
    Fixture executed for every doctest.

    Injects pre-configured numpy into each test's namespace.

    Note that even with this, doctests might fail due to the lack of full
    compatibility when using ``numpy.set_printoptions(legacy='1.13')``.

    Some of the whitespace issues can be fixed by ``NORMALIZE_WHITESPACE``
    doctest option, which is currently set in ``pytest.ini``.

    See: https://github.com/numpy/numpy/issues/10383
    """
    current_version = pkg_resources.parse_version(numpy.__version__)
    doctest_namespace['np'] = numpy 
Example #4
Source File: test_config.py    From pytest with MIT License 6 votes vote down vote up
def test_override_ini_pathlist(self, testdir):
        testdir.makeconftest(
            """
            def pytest_addoption(parser):
                parser.addini("paths", "my new ini value", type="pathlist")"""
        )
        testdir.makeini(
            """
            [pytest]
            paths=blah.py"""
        )
        testdir.makepyfile(
            """
            import py.path
            def test_pathlist(pytestconfig):
                config_paths = pytestconfig.getini("paths")
                print(config_paths)
                for cpf in config_paths:
                    print('\\nuser_path:%s' % cpf.basename)"""
        )
        result = testdir.runpytest(
            "--override-ini", "paths=foo/bar1.py foo/bar2.py", "-s"
        )
        result.stdout.fnmatch_lines(["user_path:bar1.py", "user_path:bar2.py"]) 
Example #5
Source File: conftest.py    From sisl with GNU Lesser General Public License v3.0 6 votes vote down vote up
def pytest_configure(config):

    # Locally manage pytest.ini input
    for mark in ['io', 'bloch', 'hamiltonian', 'geometry', 'geom', 'shape',
                 'state', 'electron', 'phonon', 'utils', 'unit', 'distribution',
                 'spin', 'self_energy', 'help', 'messages', 'namedindex', 'sparse',
                 'supercell', 'sc', 'quaternion', 'sparse_geometry', 'ranges',
                 'orbital', 'oplist', 'grid', 'atoms', 'atom', 'sgrid', 'sdata', 'sgeom',
                 'version', 'bz', 'brillouinzone', 'inv', 'eig', 'linalg',
                 'density_matrix', 'dynamicalmatrix', 'energydensity_matrix',
                 'siesta', 'tbtrans', 'ham', 'vasp', 'w90', 'wannier90', 'gulp', 'fdf',
                 "category", "geom_category",
                 'table', 'cube', 'slow', 'selector', 'overlap', 'mixing']:
        config.addinivalue_line(
            "markers", f"{mark}: mark test to run only on named environment"
        ) 
Example #6
Source File: test_config.py    From pytest with MIT License 6 votes vote down vote up
def test_addini_bool(self, testdir, str_val, bool_val):
        testdir.makeconftest(
            """
            def pytest_addoption(parser):
                parser.addini("strip", "", type="bool", default=True)
        """
        )
        if str_val != "no-ini":
            testdir.makeini(
                """
                [pytest]
                strip=%s
            """
                % str_val
            )
        config = testdir.parseconfig()
        assert config.getini("strip") is bool_val 
Example #7
Source File: test_config.py    From pytest with MIT License 6 votes vote down vote up
def test_addini(self, testdir):
        testdir.makeconftest(
            """
            def pytest_addoption(parser):
                parser.addini("myname", "my new ini value")
        """
        )
        testdir.makeini(
            """
            [pytest]
            myname=hello
        """
        )
        config = testdir.parseconfig()
        val = config.getini("myname")
        assert val == "hello"
        pytest.raises(ValueError, config.getini, "other") 
Example #8
Source File: test_config.py    From pytest with MIT License 6 votes vote down vote up
def test_override_ini_handled_asap(self, testdir, with_ini):
        """-o should be handled as soon as possible and always override what's in ini files (#2238)"""
        if with_ini:
            testdir.makeini(
                """
                [pytest]
                python_files=test_*.py
            """
            )
        testdir.makepyfile(
            unittest_ini_handle="""
            def test():
                pass
        """
        )
        result = testdir.runpytest("--override-ini", "python_files=unittest_*.py")
        result.stdout.fnmatch_lines(["*1 passed in*"]) 
Example #9
Source File: test_config.py    From pytest with MIT License 6 votes vote down vote up
def test_addopts_from_ini_not_concatenated(self, testdir):
        """addopts from ini should not take values from normal args (#4265)."""
        testdir.makeini(
            """
            [pytest]
            addopts=-o
        """
        )
        result = testdir.runpytest("cache_dir=ignored")
        result.stderr.fnmatch_lines(
            [
                "%s: error: argument -o/--override-ini: expected one argument (via addopts config)"
                % (testdir.request.config._parser.optparser.prog,)
            ]
        )
        assert result.ret == _pytest.config.ExitCode.USAGE_ERROR 
Example #10
Source File: test_config.py    From pytest with MIT License 6 votes vote down vote up
def test_invalid_ini_keys(
        self, testdir, ini_file_text, invalid_keys, warning_output, exception_text
    ):
        testdir.makeconftest(
            """
            def pytest_addoption(parser):
                parser.addini("conftest_ini_key", "")
        """
        )
        testdir.tmpdir.join("pytest.ini").write(textwrap.dedent(ini_file_text))

        config = testdir.parseconfig()
        assert sorted(config._get_unknown_ini_keys()) == sorted(invalid_keys)

        result = testdir.runpytest()
        result.stdout.fnmatch_lines(warning_output)

        if exception_text:
            with pytest.raises(pytest.fail.Exception, match=exception_text):
                testdir.runpytest("--strict-config")
        else:
            testdir.runpytest("--strict-config") 
Example #11
Source File: test_config.py    From pytest with MIT License 5 votes vote down vote up
def test_override_ini_names(self, testdir, name):
        section = "[pytest]" if name != "setup.cfg" else "[tool:pytest]"
        testdir.tmpdir.join(name).write(
            textwrap.dedent(
                """
            {section}
            custom = 1.0""".format(
                    section=section
                )
            )
        )
        testdir.makeconftest(
            """
            def pytest_addoption(parser):
                parser.addini("custom", "")"""
        )
        testdir.makepyfile(
            """
            def test_pass(pytestconfig):
                ini_val = pytestconfig.getini("custom")
                print('\\ncustom_option:%s\\n' % ini_val)"""
        )

        result = testdir.runpytest("--override-ini", "custom=2.0", "-s")
        assert result.ret == 0
        result.stdout.fnmatch_lines(["custom_option:2.0"])

        result = testdir.runpytest(
            "--override-ini", "custom=2.0", "--override-ini=custom=3.0", "-s"
        )
        assert result.ret == 0
        result.stdout.fnmatch_lines(["custom_option:3.0"]) 
Example #12
Source File: test_pipeline.py    From drizzlepac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_class(self, tmpdir, envopt, pytestconfig):
        """
        Run test in own dir so we can keep results separate from
        other tests.
        """
        if not tmpdir.ensure(self.subdir, dir=True):
            p = tmpdir.mkdir(self.subdir).strpath
        else:
            p = tmpdir.join(self.subdir).strpath
        os.chdir(p)

        # NOTE: This could be explicitly controlled using pytest fixture
        #       but too many ways to do the same thing would be confusing.
        #       Refine this logic if using pytest fixture.
        # HSTCAL cannot open remote CRDS on FTP but central storage is okay.
        # So use central storage if available to avoid FTP.
        if self.prevref is None or self.prevref.startswith(('ftp', 'http')):
            os.environ[self.refstr] = p + os.sep
            self.use_ftp_crds = True

        # This controls astropy.io.fits timeout
        conf.remote_timeout = self.timeout

        # Update tree to point to correct environment
        self.tree = envopt

        # Collect pytest configuration values specified in setup.cfg or pytest.ini
        self.inputs_root = pytestconfig.getini('inputs_root')[0]
        self.results_root = pytestconfig.getini('results_root')[0] 
Example #13
Source File: test_config.py    From pytest with MIT License 5 votes vote down vote up
def test_override_ini_usage_error_bad_style(self, testdir):
        testdir.makeini(
            """
            [pytest]
            xdist_strict=False
        """
        )
        result = testdir.runpytest("--override-ini", "xdist_strict", "True")
        result.stderr.fnmatch_lines(
            [
                "ERROR: -o/--override-ini expects option=value style (got: 'xdist_strict').",
            ]
        ) 
Example #14
Source File: test_config.py    From pytest with MIT License 5 votes vote down vote up
def test_addopts_from_env_not_concatenated(self, monkeypatch, _config_for_test):
        """PYTEST_ADDOPTS should not take values from normal args (#4265)."""
        monkeypatch.setenv("PYTEST_ADDOPTS", "-o")
        config = _config_for_test
        with pytest.raises(UsageError) as excinfo:
            config._preparse(["cache_dir=ignored"], addopts=True)
        assert (
            "error: argument -o/--override-ini: expected one argument (via PYTEST_ADDOPTS)"
            in excinfo.value.args[0]
        ) 
Example #15
Source File: service.py    From agent-python-pytest with Apache License 2.0 5 votes vote down vote up
def _get_launch_attributes(self, ini_attrs):
        """Generate launch attributes in the format supported by the client.

        :param list ini_attrs: List for attributes from the pytest.ini file
        """
        attributes = ini_attrs or []

        system_info = self.rp.get_system_information(self._agent_name)
        system_info['system'] = True
        system_attributes = _dict_to_payload(system_info)

        return attributes + system_attributes 
Example #16
Source File: check_requirements.py    From requirements-tools with MIT License 5 votes vote down vote up
def main():  # pragma: no cover
    print('Checking requirements...')
    # Forces quiet output and overrides pytest.ini
    os.environ['PYTEST_ADDOPTS'] = '-q -s --tb=short'
    return pytest.main([__file__.replace('pyc', 'py')] + sys.argv[1:]) 
Example #17
Source File: test_connection.py    From PyHDB with Apache License 2.0 5 votes vote down vote up
def test_make_connection_from_pytest_ini():
    if not os.path.isfile('pytest.ini'):
        pytest.skip("Requires pytest.ini file")
    connection = pyhdb.connect.from_ini('pytest.ini') 
Example #18
Source File: conftest.py    From drms with MIT License 5 votes vote down vote up
def pytest_configure(config):
    # Register markers here so we don't need to add a pytest.ini file to
    # the drms.tests subpackage.
    config.addinivalue_line(
        'markers', 'jsoc: mark online tests for JSOC')
    config.addinivalue_line(
        'markers', 'kis: mark online tests for KIS')
    config.addinivalue_line(
        'markers', 'export: mark online tests that perform data exports') 
Example #19
Source File: test.py    From cloudformation-cli with Apache License 2.0 5 votes vote down vote up
def temporary_ini_file():
    with NamedTemporaryFile(
        mode="w", encoding="utf-8", prefix="pytest_", suffix=".ini"
    ) as temp:
        LOG.debug("temporary pytest.ini path: %s", temp.name)
        path = Path(temp.name).resolve(strict=True)
        copy_resource(__name__, "data/pytest-contract.ini", path)
        yield str(path) 
Example #20
Source File: plugin.py    From pytest-pylint with MIT License 5 votes vote down vote up
def pytest_configure(self, config):
        """Configure pytest after it is already enabled"""

        # Find pylintrc to check ignore list
        pylintrc_file = config.option.pylint_rcfile or PYLINTRC

        if pylintrc_file and not exists(pylintrc_file):
            # The directory of pytest.ini got a chance
            pylintrc_file = join(dirname(str(config.inifile)), pylintrc_file)

        # Try getting ignores from pylintrc since we use pytest
        # collection methods and not pylint's internal mechanism
        if pylintrc_file and exists(pylintrc_file):
            self.pylintrc_file = pylintrc_file
            if pylintrc_file.endswith(".toml"):
                self._load_pyproject_toml(pylintrc_file)
            else:
                self._load_rc_file(pylintrc_file)

        # Command line arguments take presedence over rcfile ones if set
        if config.option.pylint_ignore is not None:
            self.pylint_ignore = config.option.pylint_ignore.split(',')
        if config.option.pylint_ignore_patterns is not None:
            self.pylint_ignore_patterns = (
                config.option.pylint_ignore_patterns.split(',')
            ) 
Example #21
Source File: conftest.py    From ocs-ci with MIT License 5 votes vote down vote up
def log_cli_level(pytestconfig):
    """
    Retrieves the log_cli_level set in pytest.ini

    Returns:
        str: log_cli_level set in pytest.ini or DEBUG if not set

    """
    return pytestconfig.getini('log_cli_level') or 'DEBUG' 
Example #22
Source File: resources.py    From drizzlepac with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup_class(self, tmpdir, envopt, pytestconfig):
        """
        Run test in own dir so we can keep results separate from
        other tests.
        """
        if not tmpdir.ensure(self.subdir, dir=True):
            p = tmpdir.mkdir(self.subdir).strpath
        else:
            p = tmpdir.join(self.subdir).strpath
        os.chdir(p)

        # NOTE: This could be explicitly controlled using pytest fixture
        #       but too many ways to do the same thing would be confusing.
        #       Refine this logic if using pytest fixture.
        # HSTCAL cannot open remote CRDS on FTP but central storage is okay.
        # So use central storage if available to avoid FTP.
        if self.prevref is None or self.prevref.startswith(('ftp', 'http')):
            os.environ[self.refstr] = p + os.sep
            self.use_ftp_crds = True

        # Turn off Astrometry updates
        os.environ['ASTROMETRY_STEP_CONTROL'] = 'OFF'

        # This controls astropy.io.fits timeout
        conf.remote_timeout = self.timeout

        # Update tree to point to correct environment
        self.tree = envopt

        # Collect pytest configuration values specified in setup.cfg or pytest.ini
        self.inputs_root = pytestconfig.getini('inputs_root')[0]
        self.results_root = pytestconfig.getini('results_root')[0] 
Example #23
Source File: test_config.py    From pytest with MIT License 5 votes vote down vote up
def test_pytestini_overrides_empty_other(self, tmpdir: py.path.local, name) -> None:
        inifile = tmpdir.ensure("pytest.ini")
        a = tmpdir.mkdir("a")
        a.ensure(name)
        rootdir, parsed_inifile, _ = determine_setup(None, [str(a)])
        assert rootdir == tmpdir
        assert parsed_inifile == inifile 
Example #24
Source File: conftest.py    From specter-desktop with MIT License 5 votes vote down vote up
def bitcoin_regtest(docker, request):
    #logging.getLogger().setLevel(logging.DEBUG)
    requested_version = request.config.getoption("--bitcoind-version")
    if docker:
        bitcoind_controller = BitcoindDockerController(rpcport=18543, docker_tag=requested_version)
    else:
        if os.path.isfile('tests/bitcoin/src/bitcoind'):
            bitcoind_controller = BitcoindPlainController(bitcoind_path='tests/bitcoin/src/bitcoind') # always prefer the self-compiled bitcoind if existing
        else:
            bitcoind_controller = BitcoindPlainController() # Alternatively take the one on the path for now
    bitcoind_controller.start_bitcoind(cleanup_at_exit=True)
    running_version = bitcoind_controller.version()
    requested_version = request.config.getoption("--bitcoind-version")
    assert(running_version != requested_version, "Please make sure that the Bitcoind-version (%s) matches with the version in pytest.ini (%s)"%(running_version,requested_version))
    return bitcoind_controller 
Example #25
Source File: target.py    From iris with Mozilla Public License 2.0 5 votes vote down vote up
def option(self, pytestconfig):
        """
        fixture for ovewriting values in pytest.ini file

        :return: Option Object
        """

        new_value = {}

        class Options:
            @staticmethod
            def get(name):
                return new_value.get(name, pytestconfig.getini(name))

        return Options() 
Example #26
Source File: test_findpaths.py    From pytest with MIT License 5 votes vote down vote up
def test_empty_pytest_ini(self, tmpdir):
        """pytest.ini files are always considered for configuration, even if empty"""
        fn = tmpdir.join("pytest.ini")
        fn.write("")
        assert load_config_dict_from_file(fn) == {} 
Example #27
Source File: test_findpaths.py    From pytest with MIT License 5 votes vote down vote up
def test_pytest_ini(self, tmpdir):
        """[pytest] section in pytest.ini files is read correctly"""
        fn = tmpdir.join("pytest.ini")
        fn.write("[pytest]\nx=1")
        assert load_config_dict_from_file(fn) == {"x": "1"} 
Example #28
Source File: test_findpaths.py    From pytest with MIT License 5 votes vote down vote up
def test_custom_ini(self, tmpdir):
        """[pytest] section in any .ini file is read correctly"""
        fn = tmpdir.join("custom.ini")
        fn.write("[pytest]\nx=1")
        assert load_config_dict_from_file(fn) == {"x": "1"} 
Example #29
Source File: test_findpaths.py    From pytest with MIT License 5 votes vote down vote up
def test_custom_ini_without_section(self, tmpdir):
        """Custom .ini files without [pytest] section are not considered for configuration"""
        fn = tmpdir.join("custom.ini")
        fn.write("[custom]")
        assert load_config_dict_from_file(fn) is None 
Example #30
Source File: test_config.py    From pytest with MIT License 5 votes vote down vote up
def test_tox_ini_wrong_version(self, testdir):
        testdir.makefile(
            ".ini",
            tox="""
            [pytest]
            minversion=999.0
        """,
        )
        result = testdir.runpytest()
        assert result.ret != 0
        result.stderr.fnmatch_lines(
            ["*tox.ini: 'minversion' requires pytest-999.0, actual pytest-*"]
        )