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 class GanetiTestProgram(unittest.TestProgram):
43 logging.basicConfig(filename=os.devnull)
45 sys.stderr.write("Running %s\n" % self.progName)
48 # Ensure assertions will be evaluated
50 raise Exception("Not running in debug mode, assertions would not be"
53 # Check again, this time with a real assertion
56 except AssertionError:
59 raise Exception("Assertion not evaluated")
61 return unittest.TestProgram.runTests(self)
64 class GanetiTestCase(unittest.TestCase):
65 """Helper class for unittesting.
67 This class defines a few utility functions that help in building
68 unittests. Child classes must call the parent setup and cleanup.
75 while self._temp_files:
77 utils.RemoveFile(self._temp_files.pop())
78 except EnvironmentError, err:
81 def assertFileContent(self, file_name, expected_content):
82 """Checks that the content of a file is what we expect.
85 @param file_name: the file whose contents we should check
86 @type expected_content: str
87 @param expected_content: the content we expect
90 actual_content = utils.ReadFile(file_name)
91 self.assertEqual(actual_content, expected_content)
93 def assertFileMode(self, file_name, expected_mode):
94 """Checks that the mode of a file is what we expect.
97 @param file_name: the file whose contents we should check
98 @type expected_mode: int
99 @param expected_mode: the mode we expect
102 st = os.stat(file_name)
103 actual_mode = stat.S_IMODE(st.st_mode)
104 self.assertEqual(actual_mode, expected_mode)
106 def assertEqualValues(self, first, second, msg=None):
107 """Compares two values whether they're equal.
109 Tuples are automatically converted to lists before comparing.
112 return self.assertEqual(UnifyValueType(first),
113 UnifyValueType(second),
117 def _TestDataFilename(name):
118 """Returns the filename of a given test data file.
121 @param name: the 'base' of the file name, as present in
122 the test/data directory
124 @return: the full path to the filename, such that it can
125 be used in 'make distcheck' rules
128 return "%s/test/data/%s" % (GetSourceDir(), name)
131 def _ReadTestData(cls, name):
132 """Returns the contents of a test data file.
134 This is just a very simple wrapper over utils.ReadFile with the
135 proper test file name.
138 return utils.ReadFile(cls._TestDataFilename(name))
140 def _CreateTempFile(self):
141 """Creates a temporary file and adds it to the internal cleanup list.
143 This method simplifies the creation and cleanup of temporary files
147 fh, fname = tempfile.mkstemp(prefix="ganeti-test", suffix=".tmp")
149 self._temp_files.append(fname)
153 def UnifyValueType(data):
154 """Converts all tuples into lists.
156 This is useful for unittests where an external library doesn't keep types.
159 if isinstance(data, (tuple, list)):
160 return [UnifyValueType(i) for i in data]
162 elif isinstance(data, dict):
163 return dict([(UnifyValueType(key), UnifyValueType(value))
164 for (key, value) in data.iteritems()])