MCPcopy
hub / github.com/httpie/cli / MockEnvironment

Class MockEnvironment

tests/utils/__init__.py:129–184  ·  view source on GitHub ↗

Environment subclass with reasonable defaults for testing.

Source from the content-addressed store, hash-verified

127
128
129class MockEnvironment(Environment):
130 """Environment subclass with reasonable defaults for testing."""
131 colors = 0 # For easier debugging
132 stdin_isatty = True
133 stdout_isatty = True
134 is_windows = False
135 show_displays = False
136
137 def __init__(self, create_temp_config_dir=True, **kwargs):
138 self._encoder = Encoder()
139 if 'stdout' not in kwargs:
140 kwargs['stdout'] = tempfile.NamedTemporaryFile(
141 mode='w+t',
142 prefix='httpie_stderr',
143 newline='',
144 encoding=UTF8,
145 )
146 kwargs['stdout'].buffer = FakeBytesIOBuffer(kwargs['stdout'], self._encoder)
147 if 'stderr' not in kwargs:
148 kwargs['stderr'] = tempfile.TemporaryFile(
149 mode='w+t',
150 prefix='httpie_stderr',
151 encoding=UTF8,
152 )
153 super().__init__(**kwargs)
154 self._create_temp_config_dir = create_temp_config_dir
155 self._delete_config_dir = False
156 self._temp_dir = Path(tempfile.gettempdir())
157
158 @property
159 def config(self) -> Config:
160 if (self._create_temp_config_dir
161 and self._temp_dir not in self.config_dir.parents):
162 self.create_temp_config_dir()
163 return super().config
164
165 def create_temp_config_dir(self):
166 self.config_dir = mk_config_dir()
167 self._delete_config_dir = True
168
169 def cleanup(self):
170 self.devnull.close()
171 self.stdout.close()
172 self.stderr.close()
173 warnings.resetwarnings()
174 if self._delete_config_dir:
175 assert self._temp_dir in self.config_dir.parents
176 from shutil import rmtree
177 rmtree(self.config_dir, ignore_errors=True)
178
179 def __del__(self):
180 # noinspection PyBroadException
181 try:
182 self.cleanup()
183 except Exception:
184 pass
185
186

Calls

no outgoing calls