Statistics
| Branch: | Tag: | Revision:

root / test / testutils.py @ 25231ec5

History | View | Annotate | Download (4 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008 Google Inc.
5
#
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.
10
#
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.
15
#
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
19
# 02110-1301, USA.
20

    
21

    
22
"""Utilities for unit testing"""
23

    
24
import os
25
import stat
26
import tempfile
27
import unittest
28
import logging
29

    
30
from ganeti import utils
31

    
32

    
33
def GetSourceDir():
34
  return os.environ.get("TOP_SRCDIR", ".")
35

    
36

    
37
class GanetiTestProgram(unittest.TestProgram):
38
  def runTests(self):
39
    """
40

41
    """
42
    logging.basicConfig(filename=os.devnull)
43
    return unittest.TestProgram.runTests(self)
44

    
45

    
46
class GanetiTestCase(unittest.TestCase):
47
  """Helper class for unittesting.
48

49
  This class defines a few utility functions that help in building
50
  unittests. Child classes must call the parent setup and cleanup.
51

52
  """
53
  def setUp(self):
54
    self._temp_files = []
55

    
56
  def tearDown(self):
57
    while self._temp_files:
58
      try:
59
        utils.RemoveFile(self._temp_files.pop())
60
      except EnvironmentError, err:
61
        pass
62

    
63
  def assertFileContent(self, file_name, expected_content):
64
    """Checks that the content of a file is what we expect.
65

66
    @type file_name: str
67
    @param file_name: the file whose contents we should check
68
    @type expected_content: str
69
    @param expected_content: the content we expect
70

71
    """
72
    actual_content = utils.ReadFile(file_name)
73
    self.assertEqual(actual_content, expected_content)
74

    
75
  def assertFileMode(self, file_name, expected_mode):
76
    """Checks that the mode of a file is what we expect.
77

78
    @type file_name: str
79
    @param file_name: the file whose contents we should check
80
    @type expected_mode: int
81
    @param expected_mode: the mode we expect
82

83
    """
84
    st = os.stat(file_name)
85
    actual_mode = stat.S_IMODE(st.st_mode)
86
    self.assertEqual(actual_mode, expected_mode)
87

    
88
  def assertEqualValues(self, first, second, msg=None):
89
    """Compares two values whether they're equal.
90

91
    Tuples are automatically converted to lists before comparing.
92

93
    """
94
    return self.assertEqual(UnifyValueType(first),
95
                            UnifyValueType(second),
96
                            msg=msg)
97

    
98
  @staticmethod
99
  def _TestDataFilename(name):
100
    """Returns the filename of a given test data file.
101

102
    @type name: str
103
    @param name: the 'base' of the file name, as present in
104
        the test/data directory
105
    @rtype: str
106
    @return: the full path to the filename, such that it can
107
        be used in 'make distcheck' rules
108

109
    """
110
    return "%s/test/data/%s" % (GetSourceDir(), name)
111

    
112
  @classmethod
113
  def _ReadTestData(cls, name):
114
    """Returns the contents of a test data file.
115

116
    This is just a very simple wrapper over utils.ReadFile with the
117
    proper test file name.
118

119
    """
120
    return utils.ReadFile(cls._TestDataFilename(name))
121

    
122
  def _CreateTempFile(self):
123
    """Creates a temporary file and adds it to the internal cleanup list.
124

125
    This method simplifies the creation and cleanup of temporary files
126
    during tests.
127

128
    """
129
    fh, fname = tempfile.mkstemp(prefix="ganeti-test", suffix=".tmp")
130
    os.close(fh)
131
    self._temp_files.append(fname)
132
    return fname
133

    
134

    
135
def UnifyValueType(data):
136
  """Converts all tuples into lists.
137

138
  This is useful for unittests where an external library doesn't keep types.
139

140
  """
141
  if isinstance(data, (tuple, list)):
142
    return [UnifyValueType(i) for i in data]
143

    
144
  elif isinstance(data, dict):
145
    return dict([(UnifyValueType(key), UnifyValueType(value))
146
                 for (key, value) in data.iteritems()])
147

    
148
  return data