Statistics
| Branch: | Tag: | Revision:

root / test / testutils.py @ 8572f1fe

History | View | Annotate | Download (4.9 kB)

1 c9c4f19e Michael Hanselmann
#
2 c9c4f19e Michael Hanselmann
#
3 c9c4f19e Michael Hanselmann
4 c9c4f19e Michael Hanselmann
# Copyright (C) 2006, 2007, 2008 Google Inc.
5 c9c4f19e Michael Hanselmann
#
6 c9c4f19e Michael Hanselmann
# This program is free software; you can redistribute it and/or modify
7 c9c4f19e Michael Hanselmann
# it under the terms of the GNU General Public License as published by
8 c9c4f19e Michael Hanselmann
# the Free Software Foundation; either version 2 of the License, or
9 c9c4f19e Michael Hanselmann
# (at your option) any later version.
10 c9c4f19e Michael Hanselmann
#
11 c9c4f19e Michael Hanselmann
# This program is distributed in the hope that it will be useful, but
12 c9c4f19e Michael Hanselmann
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 c9c4f19e Michael Hanselmann
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 c9c4f19e Michael Hanselmann
# General Public License for more details.
15 c9c4f19e Michael Hanselmann
#
16 c9c4f19e Michael Hanselmann
# You should have received a copy of the GNU General Public License
17 c9c4f19e Michael Hanselmann
# along with this program; if not, write to the Free Software
18 c9c4f19e Michael Hanselmann
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 c9c4f19e Michael Hanselmann
# 02110-1301, USA.
20 c9c4f19e Michael Hanselmann
21 c9c4f19e Michael Hanselmann
22 c9c4f19e Michael Hanselmann
"""Utilities for unit testing"""
23 c9c4f19e Michael Hanselmann
24 149a5439 Iustin Pop
import os
25 43983a88 Michael Hanselmann
import sys
26 9b977740 Guido Trotter
import stat
27 51596eb2 Iustin Pop
import tempfile
28 c9c4f19e Michael Hanselmann
import unittest
29 25231ec5 Michael Hanselmann
import logging
30 c9c4f19e Michael Hanselmann
31 149a5439 Iustin Pop
from ganeti import utils
32 149a5439 Iustin Pop
33 c9c4f19e Michael Hanselmann
34 3f991867 Michael Hanselmann
def GetSourceDir():
35 3f991867 Michael Hanselmann
  return os.environ.get("TOP_SRCDIR", ".")
36 3f991867 Michael Hanselmann
37 3f991867 Michael Hanselmann
38 913138f4 Michael Hanselmann
def _SetupLogging(verbose):
39 913138f4 Michael Hanselmann
  """Setupup logging infrastructure.
40 913138f4 Michael Hanselmann

41 913138f4 Michael Hanselmann
  """
42 913138f4 Michael Hanselmann
  fmt = logging.Formatter("%(asctime)s: %(threadName)s"
43 913138f4 Michael Hanselmann
                          " %(levelname)s %(message)s")
44 913138f4 Michael Hanselmann
45 913138f4 Michael Hanselmann
  if verbose:
46 913138f4 Michael Hanselmann
    handler = logging.StreamHandler()
47 913138f4 Michael Hanselmann
  else:
48 913138f4 Michael Hanselmann
    handler = logging.FileHandler(os.devnull, "a")
49 913138f4 Michael Hanselmann
50 913138f4 Michael Hanselmann
  handler.setLevel(logging.NOTSET)
51 913138f4 Michael Hanselmann
  handler.setFormatter(fmt)
52 913138f4 Michael Hanselmann
53 913138f4 Michael Hanselmann
  root_logger = logging.getLogger("")
54 913138f4 Michael Hanselmann
  root_logger.setLevel(logging.NOTSET)
55 913138f4 Michael Hanselmann
  root_logger.addHandler(handler)
56 913138f4 Michael Hanselmann
57 913138f4 Michael Hanselmann
58 25231ec5 Michael Hanselmann
class GanetiTestProgram(unittest.TestProgram):
59 25231ec5 Michael Hanselmann
  def runTests(self):
60 913138f4 Michael Hanselmann
    """Runs all tests.
61 25231ec5 Michael Hanselmann

62 25231ec5 Michael Hanselmann
    """
63 913138f4 Michael Hanselmann
    _SetupLogging("LOGTOSTDERR" in os.environ)
64 43983a88 Michael Hanselmann
65 43983a88 Michael Hanselmann
    sys.stderr.write("Running %s\n" % self.progName)
66 43983a88 Michael Hanselmann
    sys.stderr.flush()
67 43983a88 Michael Hanselmann
68 a9b144cb Michael Hanselmann
    # Ensure assertions will be evaluated
69 a9b144cb Michael Hanselmann
    if not __debug__:
70 a9b144cb Michael Hanselmann
      raise Exception("Not running in debug mode, assertions would not be"
71 a9b144cb Michael Hanselmann
                      " evaluated")
72 a9b144cb Michael Hanselmann
73 a9b144cb Michael Hanselmann
    # Check again, this time with a real assertion
74 a9b144cb Michael Hanselmann
    try:
75 a9b144cb Michael Hanselmann
      assert False
76 a9b144cb Michael Hanselmann
    except AssertionError:
77 a9b144cb Michael Hanselmann
      pass
78 a9b144cb Michael Hanselmann
    else:
79 a9b144cb Michael Hanselmann
      raise Exception("Assertion not evaluated")
80 a9b144cb Michael Hanselmann
81 25231ec5 Michael Hanselmann
    return unittest.TestProgram.runTests(self)
82 25231ec5 Michael Hanselmann
83 25231ec5 Michael Hanselmann
84 c9c4f19e Michael Hanselmann
class GanetiTestCase(unittest.TestCase):
85 51596eb2 Iustin Pop
  """Helper class for unittesting.
86 51596eb2 Iustin Pop

87 51596eb2 Iustin Pop
  This class defines a few utility functions that help in building
88 51596eb2 Iustin Pop
  unittests. Child classes must call the parent setup and cleanup.
89 51596eb2 Iustin Pop

90 51596eb2 Iustin Pop
  """
91 51596eb2 Iustin Pop
  def setUp(self):
92 51596eb2 Iustin Pop
    self._temp_files = []
93 51596eb2 Iustin Pop
94 51596eb2 Iustin Pop
  def tearDown(self):
95 51596eb2 Iustin Pop
    while self._temp_files:
96 51596eb2 Iustin Pop
      try:
97 51596eb2 Iustin Pop
        utils.RemoveFile(self._temp_files.pop())
98 51596eb2 Iustin Pop
      except EnvironmentError, err:
99 51596eb2 Iustin Pop
        pass
100 51596eb2 Iustin Pop
101 149a5439 Iustin Pop
  def assertFileContent(self, file_name, expected_content):
102 9b977740 Guido Trotter
    """Checks that the content of a file is what we expect.
103 149a5439 Iustin Pop

104 149a5439 Iustin Pop
    @type file_name: str
105 149a5439 Iustin Pop
    @param file_name: the file whose contents we should check
106 149a5439 Iustin Pop
    @type expected_content: str
107 149a5439 Iustin Pop
    @param expected_content: the content we expect
108 149a5439 Iustin Pop

109 149a5439 Iustin Pop
    """
110 149a5439 Iustin Pop
    actual_content = utils.ReadFile(file_name)
111 149a5439 Iustin Pop
    self.assertEqual(actual_content, expected_content)
112 149a5439 Iustin Pop
113 9b977740 Guido Trotter
  def assertFileMode(self, file_name, expected_mode):
114 9b977740 Guido Trotter
    """Checks that the mode of a file is what we expect.
115 9b977740 Guido Trotter

116 9b977740 Guido Trotter
    @type file_name: str
117 9b977740 Guido Trotter
    @param file_name: the file whose contents we should check
118 9b977740 Guido Trotter
    @type expected_mode: int
119 9b977740 Guido Trotter
    @param expected_mode: the mode we expect
120 9b977740 Guido Trotter

121 9b977740 Guido Trotter
    """
122 9b977740 Guido Trotter
    st = os.stat(file_name)
123 9b977740 Guido Trotter
    actual_mode = stat.S_IMODE(st.st_mode)
124 9b977740 Guido Trotter
    self.assertEqual(actual_mode, expected_mode)
125 9b977740 Guido Trotter
126 d357f531 Michael Hanselmann
  def assertEqualValues(self, first, second, msg=None):
127 d357f531 Michael Hanselmann
    """Compares two values whether they're equal.
128 d357f531 Michael Hanselmann

129 d357f531 Michael Hanselmann
    Tuples are automatically converted to lists before comparing.
130 d357f531 Michael Hanselmann

131 d357f531 Michael Hanselmann
    """
132 d357f531 Michael Hanselmann
    return self.assertEqual(UnifyValueType(first),
133 d357f531 Michael Hanselmann
                            UnifyValueType(second),
134 d357f531 Michael Hanselmann
                            msg=msg)
135 d357f531 Michael Hanselmann
136 149a5439 Iustin Pop
  @staticmethod
137 149a5439 Iustin Pop
  def _TestDataFilename(name):
138 149a5439 Iustin Pop
    """Returns the filename of a given test data file.
139 149a5439 Iustin Pop

140 149a5439 Iustin Pop
    @type name: str
141 149a5439 Iustin Pop
    @param name: the 'base' of the file name, as present in
142 149a5439 Iustin Pop
        the test/data directory
143 149a5439 Iustin Pop
    @rtype: str
144 149a5439 Iustin Pop
    @return: the full path to the filename, such that it can
145 149a5439 Iustin Pop
        be used in 'make distcheck' rules
146 c9c4f19e Michael Hanselmann

147 c9c4f19e Michael Hanselmann
    """
148 3f991867 Michael Hanselmann
    return "%s/test/data/%s" % (GetSourceDir(), name)
149 149a5439 Iustin Pop
150 149a5439 Iustin Pop
  @classmethod
151 149a5439 Iustin Pop
  def _ReadTestData(cls, name):
152 149a5439 Iustin Pop
    """Returns the contents of a test data file.
153 149a5439 Iustin Pop

154 149a5439 Iustin Pop
    This is just a very simple wrapper over utils.ReadFile with the
155 149a5439 Iustin Pop
    proper test file name.
156 149a5439 Iustin Pop

157 149a5439 Iustin Pop
    """
158 149a5439 Iustin Pop
    return utils.ReadFile(cls._TestDataFilename(name))
159 51596eb2 Iustin Pop
160 51596eb2 Iustin Pop
  def _CreateTempFile(self):
161 51596eb2 Iustin Pop
    """Creates a temporary file and adds it to the internal cleanup list.
162 51596eb2 Iustin Pop

163 51596eb2 Iustin Pop
    This method simplifies the creation and cleanup of temporary files
164 51596eb2 Iustin Pop
    during tests.
165 51596eb2 Iustin Pop

166 51596eb2 Iustin Pop
    """
167 51596eb2 Iustin Pop
    fh, fname = tempfile.mkstemp(prefix="ganeti-test", suffix=".tmp")
168 51596eb2 Iustin Pop
    os.close(fh)
169 51596eb2 Iustin Pop
    self._temp_files.append(fname)
170 51596eb2 Iustin Pop
    return fname
171 d357f531 Michael Hanselmann
172 d357f531 Michael Hanselmann
173 d357f531 Michael Hanselmann
def UnifyValueType(data):
174 d357f531 Michael Hanselmann
  """Converts all tuples into lists.
175 d357f531 Michael Hanselmann

176 d357f531 Michael Hanselmann
  This is useful for unittests where an external library doesn't keep types.
177 d357f531 Michael Hanselmann

178 d357f531 Michael Hanselmann
  """
179 d357f531 Michael Hanselmann
  if isinstance(data, (tuple, list)):
180 d357f531 Michael Hanselmann
    return [UnifyValueType(i) for i in data]
181 d357f531 Michael Hanselmann
182 d357f531 Michael Hanselmann
  elif isinstance(data, dict):
183 d357f531 Michael Hanselmann
    return dict([(UnifyValueType(key), UnifyValueType(value))
184 d357f531 Michael Hanselmann
                 for (key, value) in data.iteritems()])
185 d357f531 Michael Hanselmann
186 d357f531 Michael Hanselmann
  return data