1# Copyright 2020 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""Contains convenient helpers for writing tests.""" 15 16import contextlib 17import os 18import shutil 19import tempfile 20from unittest import mock 21 22 23def patch_environ(testcase_obj, env=None): 24 """Patch environment.""" 25 if env is None: 26 env = {} 27 28 patcher = mock.patch.dict(os.environ, env) 29 testcase_obj.addCleanup(patcher.stop) 30 patcher.start() 31 32 33@contextlib.contextmanager 34def temp_dir_copy(directory): 35 """Context manager that yields a temporary copy of |directory|.""" 36 with tempfile.TemporaryDirectory() as temp_dir: 37 temp_copy_path = os.path.join(temp_dir, os.path.basename(directory)) 38 shutil.copytree(directory, temp_copy_path) 39 yield temp_copy_path 40