1
# Copyright (C) 2013 Canonical Ltd.
2
# Author: Colin Watson <cjwatson@ubuntu.com>
4
# This program is free software: you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; version 3 of the License.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program. If not, see <http://www.gnu.org/licenses/>.
16
"""Testing helpers."""
18
from __future__ import print_function
27
import unittest2 as unittest
31
from clickpackage import osextras
34
class TestCase(unittest.TestCase):
36
super(TestCase, self).setUp()
38
self.save_env = dict(os.environ)
42
for key in set(os.environ.keys()) - set(self.save_env.keys()):
44
for key, value in os.environ.items():
45
if value != self.save_env[key]:
46
os.environ[key] = self.save_env[key]
47
for key in set(self.save_env.keys()) - set(os.environ.keys()):
48
os.environ[key] = self.save_env[key]
50
def use_temp_dir(self):
51
if self.temp_dir is not None:
53
self.temp_dir = tempfile.mkdtemp(prefix="clickpackage")
54
self.addCleanup(shutil.rmtree, self.temp_dir)
57
# Monkey-patch for Python 2/3 compatibility.
58
if not hasattr(unittest.TestCase, 'assertCountEqual'):
59
assertCountEqual = unittest.TestCase.assertItemsEqual
60
if not hasattr(unittest.TestCase, 'assertRegex'):
61
assertRegex = unittest.TestCase.assertRegexpMatches
62
if not hasattr(unittest.TestCase, 'assertRaisesRegex'):
63
assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
66
@contextlib.contextmanager
67
def mkfile(path, mode="w"):
68
osextras.ensuredir(os.path.dirname(path))
69
with open(path, mode) as f:
74
with mkfile(path, mode="a"):