Statistics
| Branch: | Tag: | Revision:

root / test / testutils.py @ 6760e4ed

History | View | Annotate | Download (4.4 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 25231ec5 Michael Hanselmann
class GanetiTestProgram(unittest.TestProgram):
39 25231ec5 Michael Hanselmann
  def runTests(self):
40 25231ec5 Michael Hanselmann
    """
41 25231ec5 Michael Hanselmann

42 25231ec5 Michael Hanselmann
    """
43 25231ec5 Michael Hanselmann
    logging.basicConfig(filename=os.devnull)
44 43983a88 Michael Hanselmann
45 43983a88 Michael Hanselmann
    sys.stderr.write("Running %s\n" % self.progName)
46 43983a88 Michael Hanselmann
    sys.stderr.flush()
47 43983a88 Michael Hanselmann
48 a9b144cb Michael Hanselmann
    # Ensure assertions will be evaluated
49 a9b144cb Michael Hanselmann
    if not __debug__:
50 a9b144cb Michael Hanselmann
      raise Exception("Not running in debug mode, assertions would not be"
51 a9b144cb Michael Hanselmann
                      " evaluated")
52 a9b144cb Michael Hanselmann
53 a9b144cb Michael Hanselmann
    # Check again, this time with a real assertion
54 a9b144cb Michael Hanselmann
    try:
55 a9b144cb Michael Hanselmann
      assert False
56 a9b144cb Michael Hanselmann
    except AssertionError:
57 a9b144cb Michael Hanselmann
      pass
58 a9b144cb Michael Hanselmann
    else:
59 a9b144cb Michael Hanselmann
      raise Exception("Assertion not evaluated")
60 a9b144cb Michael Hanselmann
61 25231ec5 Michael Hanselmann
    return unittest.TestProgram.runTests(self)
62 25231ec5 Michael Hanselmann
63 25231ec5 Michael Hanselmann
64 c9c4f19e Michael Hanselmann
class GanetiTestCase(unittest.TestCase):
65 51596eb2 Iustin Pop
  """Helper class for unittesting.
66 51596eb2 Iustin Pop

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

70 51596eb2 Iustin Pop
  """
71 51596eb2 Iustin Pop
  def setUp(self):
72 51596eb2 Iustin Pop
    self._temp_files = []
73 51596eb2 Iustin Pop
74 51596eb2 Iustin Pop
  def tearDown(self):
75 51596eb2 Iustin Pop
    while self._temp_files:
76 51596eb2 Iustin Pop
      try:
77 51596eb2 Iustin Pop
        utils.RemoveFile(self._temp_files.pop())
78 51596eb2 Iustin Pop
      except EnvironmentError, err:
79 51596eb2 Iustin Pop
        pass
80 51596eb2 Iustin Pop
81 149a5439 Iustin Pop
  def assertFileContent(self, file_name, expected_content):
82 9b977740 Guido Trotter
    """Checks that the content of a file is what we expect.
83 149a5439 Iustin Pop

84 149a5439 Iustin Pop
    @type file_name: str
85 149a5439 Iustin Pop
    @param file_name: the file whose contents we should check
86 149a5439 Iustin Pop
    @type expected_content: str
87 149a5439 Iustin Pop
    @param expected_content: the content we expect
88 149a5439 Iustin Pop

89 149a5439 Iustin Pop
    """
90 149a5439 Iustin Pop
    actual_content = utils.ReadFile(file_name)
91 149a5439 Iustin Pop
    self.assertEqual(actual_content, expected_content)
92 149a5439 Iustin Pop
93 9b977740 Guido Trotter
  def assertFileMode(self, file_name, expected_mode):
94 9b977740 Guido Trotter
    """Checks that the mode of a file is what we expect.
95 9b977740 Guido Trotter

96 9b977740 Guido Trotter
    @type file_name: str
97 9b977740 Guido Trotter
    @param file_name: the file whose contents we should check
98 9b977740 Guido Trotter
    @type expected_mode: int
99 9b977740 Guido Trotter
    @param expected_mode: the mode we expect
100 9b977740 Guido Trotter

101 9b977740 Guido Trotter
    """
102 9b977740 Guido Trotter
    st = os.stat(file_name)
103 9b977740 Guido Trotter
    actual_mode = stat.S_IMODE(st.st_mode)
104 9b977740 Guido Trotter
    self.assertEqual(actual_mode, expected_mode)
105 9b977740 Guido Trotter
106 d357f531 Michael Hanselmann
  def assertEqualValues(self, first, second, msg=None):
107 d357f531 Michael Hanselmann
    """Compares two values whether they're equal.
108 d357f531 Michael Hanselmann

109 d357f531 Michael Hanselmann
    Tuples are automatically converted to lists before comparing.
110 d357f531 Michael Hanselmann

111 d357f531 Michael Hanselmann
    """
112 d357f531 Michael Hanselmann
    return self.assertEqual(UnifyValueType(first),
113 d357f531 Michael Hanselmann
                            UnifyValueType(second),
114 d357f531 Michael Hanselmann
                            msg=msg)
115 d357f531 Michael Hanselmann
116 149a5439 Iustin Pop
  @staticmethod
117 149a5439 Iustin Pop
  def _TestDataFilename(name):
118 149a5439 Iustin Pop
    """Returns the filename of a given test data file.
119 149a5439 Iustin Pop

120 149a5439 Iustin Pop
    @type name: str
121 149a5439 Iustin Pop
    @param name: the 'base' of the file name, as present in
122 149a5439 Iustin Pop
        the test/data directory
123 149a5439 Iustin Pop
    @rtype: str
124 149a5439 Iustin Pop
    @return: the full path to the filename, such that it can
125 149a5439 Iustin Pop
        be used in 'make distcheck' rules
126 c9c4f19e Michael Hanselmann

127 c9c4f19e Michael Hanselmann
    """
128 3f991867 Michael Hanselmann
    return "%s/test/data/%s" % (GetSourceDir(), name)
129 149a5439 Iustin Pop
130 149a5439 Iustin Pop
  @classmethod
131 149a5439 Iustin Pop
  def _ReadTestData(cls, name):
132 149a5439 Iustin Pop
    """Returns the contents of a test data file.
133 149a5439 Iustin Pop

134 149a5439 Iustin Pop
    This is just a very simple wrapper over utils.ReadFile with the
135 149a5439 Iustin Pop
    proper test file name.
136 149a5439 Iustin Pop

137 149a5439 Iustin Pop
    """
138 149a5439 Iustin Pop
    return utils.ReadFile(cls._TestDataFilename(name))
139 51596eb2 Iustin Pop
140 51596eb2 Iustin Pop
  def _CreateTempFile(self):
141 51596eb2 Iustin Pop
    """Creates a temporary file and adds it to the internal cleanup list.
142 51596eb2 Iustin Pop

143 51596eb2 Iustin Pop
    This method simplifies the creation and cleanup of temporary files
144 51596eb2 Iustin Pop
    during tests.
145 51596eb2 Iustin Pop

146 51596eb2 Iustin Pop
    """
147 51596eb2 Iustin Pop
    fh, fname = tempfile.mkstemp(prefix="ganeti-test", suffix=".tmp")
148 51596eb2 Iustin Pop
    os.close(fh)
149 51596eb2 Iustin Pop
    self._temp_files.append(fname)
150 51596eb2 Iustin Pop
    return fname
151 d357f531 Michael Hanselmann
152 d357f531 Michael Hanselmann
153 d357f531 Michael Hanselmann
def UnifyValueType(data):
154 d357f531 Michael Hanselmann
  """Converts all tuples into lists.
155 d357f531 Michael Hanselmann

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

158 d357f531 Michael Hanselmann
  """
159 d357f531 Michael Hanselmann
  if isinstance(data, (tuple, list)):
160 d357f531 Michael Hanselmann
    return [UnifyValueType(i) for i in data]
161 d357f531 Michael Hanselmann
162 d357f531 Michael Hanselmann
  elif isinstance(data, dict):
163 d357f531 Michael Hanselmann
    return dict([(UnifyValueType(key), UnifyValueType(value))
164 d357f531 Michael Hanselmann
                 for (key, value) in data.iteritems()])
165 d357f531 Michael Hanselmann
166 d357f531 Michael Hanselmann
  return data