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