pip/tests/lib/configuration_helpers.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

57 lines
1.7 KiB
Python
Raw Normal View History

2017-05-13 12:13:14 +02:00
"""Helpers for tests that check configuration
"""
2017-05-14 21:20:34 +02:00
import contextlib
import functools
import os
import tempfile
2017-05-14 21:20:34 +02:00
import textwrap
from typing import Any, Dict, Iterator
import pip._internal.configuration
from pip._internal.utils.misc import ensure_dir
# This is so that tests don't need to import pip._internal.configuration.
Kind = pip._internal.configuration.Kind
kinds = pip._internal.configuration.kinds
class ConfigurationMixin:
def setup_method(self) -> None:
self.configuration = pip._internal.configuration.Configuration(
isolated=False,
)
2017-05-15 18:38:02 +02:00
def patch_configuration(self, variant: Kind, di: Dict[str, Any]) -> None:
2017-05-15 18:38:02 +02:00
old = self.configuration._load_config_files
@functools.wraps(old)
def overridden() -> None:
2017-05-15 18:38:02 +02:00
# Manual Overload
self.configuration._config[variant].update(di)
# Configuration._parsers has type:
# Dict[Kind, List[Tuple[str, RawConfigParser]]].
# As a testing convenience, pass a special value.
self.configuration._parsers[variant].append(
(None, None), # type: ignore[arg-type]
)
old()
2017-05-15 18:38:02 +02:00
# https://github.com/python/mypy/issues/2427
self.configuration._load_config_files = overridden # type: ignore[method-assign]
@contextlib.contextmanager
def tmpfile(self, contents: str) -> Iterator[str]:
# Create a temporary file
2021-04-02 11:21:40 +02:00
fd, path = tempfile.mkstemp(prefix="pip_", suffix="_config.ini", text=True)
2017-05-17 06:15:34 +02:00
os.close(fd)
2017-05-15 18:38:02 +02:00
contents = textwrap.dedent(contents).lstrip()
ensure_dir(os.path.dirname(path))
with open(path, "w") as f:
f.write(contents)
2017-05-15 18:38:02 +02:00
yield path
os.remove(path)