configuration_helpers.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Helpers for tests that check configuration
  2. """
  3. import contextlib
  4. import functools
  5. import os
  6. import tempfile
  7. import textwrap
  8. import pip._internal.configuration
  9. from pip._internal.utils.misc import ensure_dir
  10. # This is so that tests don't need to import pip.configuration
  11. kinds = pip._internal.configuration.kinds
  12. class ConfigurationMixin(object):
  13. def setup(self):
  14. self.configuration = pip._internal.configuration.Configuration(
  15. isolated=False,
  16. )
  17. self._files_to_clear = []
  18. self._old_environ = os.environ.copy()
  19. def teardown(self):
  20. for fname in self._files_to_clear:
  21. fname.stop()
  22. os.environ = self._old_environ
  23. def patch_configuration(self, variant, di):
  24. old = self.configuration._load_config_files
  25. @functools.wraps(old)
  26. def overidden():
  27. # Manual Overload
  28. self.configuration._config[variant].update(di)
  29. self.configuration._parsers[variant].append((None, None))
  30. return old()
  31. self.configuration._load_config_files = overidden
  32. @contextlib.contextmanager
  33. def tmpfile(self, contents):
  34. # Create a temporary file
  35. fd, path = tempfile.mkstemp(
  36. prefix="pip_", suffix="_config.ini", text=True
  37. )
  38. os.close(fd)
  39. contents = textwrap.dedent(contents).lstrip()
  40. ensure_dir(os.path.dirname(path))
  41. with open(path, "w") as f:
  42. f.write(contents)
  43. yield path
  44. os.remove(path)
  45. @staticmethod
  46. def get_file_contents(path):
  47. with open(path) as f:
  48. return f.read()