4 # Copyright (C) 2006, 2007, 2008 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 """Utilities for unit testing"""
31 from ganeti import utils
35 return os.environ.get("TOP_SRCDIR", ".")
38 def _SetupLogging(verbose):
39 """Setupup logging infrastructure.
42 fmt = logging.Formatter("%(asctime)s: %(threadName)s"
43 " %(levelname)s %(message)s")
46 handler = logging.StreamHandler()
48 handler = logging.FileHandler(os.devnull, "a")
50 handler.setLevel(logging.NOTSET)
51 handler.setFormatter(fmt)
53 root_logger = logging.getLogger("")
54 root_logger.setLevel(logging.NOTSET)
55 root_logger.addHandler(handler)
58 class GanetiTestProgram(unittest.TestProgram):
63 _SetupLogging("LOGTOSTDERR" in os.environ)
65 sys.stderr.write("Running %s\n" % self.progName)
68 # Ensure assertions will be evaluated
70 raise Exception("Not running in debug mode, assertions would not be"
73 # Check again, this time with a real assertion
76 except AssertionError:
79 raise Exception("Assertion not evaluated")
81 return unittest.TestProgram.runTests(self)
84 class GanetiTestCase(unittest.TestCase):
85 """Helper class for unittesting.
87 This class defines a few utility functions that help in building
88 unittests. Child classes must call the parent setup and cleanup.
95 while self._temp_files:
97 utils.RemoveFile(self._temp_files.pop())
98 except EnvironmentError, err:
101 def assertFileContent(self, file_name, expected_content):
102 """Checks that the content of a file is what we expect.
105 @param file_name: the file whose contents we should check
106 @type expected_content: str
107 @param expected_content: the content we expect
110 actual_content = utils.ReadFile(file_name)
111 self.assertEqual(actual_content, expected_content)
113 def assertFileMode(self, file_name, expected_mode):
114 """Checks that the mode of a file is what we expect.
117 @param file_name: the file whose contents we should check
118 @type expected_mode: int
119 @param expected_mode: the mode we expect
122 st = os.stat(file_name)
123 actual_mode = stat.S_IMODE(st.st_mode)
124 self.assertEqual(actual_mode, expected_mode)
126 def assertEqualValues(self, first, second, msg=None):
127 """Compares two values whether they're equal.
129 Tuples are automatically converted to lists before comparing.
132 return self.assertEqual(UnifyValueType(first),
133 UnifyValueType(second),
137 def _TestDataFilename(name):
138 """Returns the filename of a given test data file.
141 @param name: the 'base' of the file name, as present in
142 the test/data directory
144 @return: the full path to the filename, such that it can
145 be used in 'make distcheck' rules
148 return "%s/test/data/%s" % (GetSourceDir(), name)
151 def _ReadTestData(cls, name):
152 """Returns the contents of a test data file.
154 This is just a very simple wrapper over utils.ReadFile with the
155 proper test file name.
158 return utils.ReadFile(cls._TestDataFilename(name))
160 def _CreateTempFile(self):
161 """Creates a temporary file and adds it to the internal cleanup list.
163 This method simplifies the creation and cleanup of temporary files
167 fh, fname = tempfile.mkstemp(prefix="ganeti-test", suffix=".tmp")
169 self._temp_files.append(fname)
173 def UnifyValueType(data):
174 """Converts all tuples into lists.
176 This is useful for unittests where an external library doesn't keep types.
179 if isinstance(data, (tuple, list)):
180 return [UnifyValueType(i) for i in data]
182 elif isinstance(data, dict):
183 return dict([(UnifyValueType(key), UnifyValueType(value))
184 for (key, value) in data.iteritems()])