Statistics
| Branch: | Tag: | Revision:

root / test / ganeti.utils_unittest.py @ a426508d

History | View | Annotate | Download (35.6 kB)

1 a8083063 Iustin Pop
#!/usr/bin/python
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 a8083063 Iustin Pop
"""Script for unittesting the utils module"""
23 a8083063 Iustin Pop
24 a8083063 Iustin Pop
import unittest
25 a8083063 Iustin Pop
import os
26 a8083063 Iustin Pop
import time
27 a8083063 Iustin Pop
import tempfile
28 a8083063 Iustin Pop
import os.path
29 320b4e2d Alexander Schreiber
import os
30 a8083063 Iustin Pop
import md5
31 740c5aab Guido Trotter
import signal
32 2c30e9d7 Alexander Schreiber
import socket
33 eedbda4b Michael Hanselmann
import shutil
34 59072e7e Michael Hanselmann
import re
35 09352fa4 Iustin Pop
import select
36 d392fa34 Iustin Pop
import string
37 a8083063 Iustin Pop
38 a8083063 Iustin Pop
import ganeti
39 c9c4f19e Michael Hanselmann
import testutils
40 16abfbc2 Alexander Schreiber
from ganeti import constants
41 59072e7e Michael Hanselmann
from ganeti import utils
42 a5728081 Guido Trotter
from ganeti import errors
43 e5392d79 Iustin Pop
from ganeti.utils import IsProcessAlive, RunCmd, \
44 31e22135 Iustin Pop
     RemoveFile, MatchNameComponent, FormatUnit, \
45 a8083063 Iustin Pop
     ParseUnit, AddAuthorizedKey, RemoveAuthorizedKey, \
46 899d2a81 Michael Hanselmann
     ShellQuote, ShellQuoteArgs, TcpPing, ListVisibleFiles, \
47 f65f63ef Iustin Pop
     SetEtcHostsEntry, RemoveEtcHostsEntry, FirstFree, OwnIpAddress, \
48 3b813dd2 Iustin Pop
     TailFile, ForceDictType, SafeEncode, IsNormAbsPath, FormatTime
49 f65f63ef Iustin Pop
50 b2a1f511 Iustin Pop
from ganeti.errors import LockError, UnitParseError, GenericError, \
51 b2a1f511 Iustin Pop
     ProgrammerError
52 a8083063 Iustin Pop
53 d9f311d7 Iustin Pop
54 a8083063 Iustin Pop
class TestIsProcessAlive(unittest.TestCase):
55 a8083063 Iustin Pop
  """Testing case for IsProcessAlive"""
56 740c5aab Guido Trotter
57 a8083063 Iustin Pop
  def testExists(self):
58 a8083063 Iustin Pop
    mypid = os.getpid()
59 a8083063 Iustin Pop
    self.assert_(IsProcessAlive(mypid),
60 a8083063 Iustin Pop
                 "can't find myself running")
61 a8083063 Iustin Pop
62 a8083063 Iustin Pop
  def testNotExisting(self):
63 09352fa4 Iustin Pop
    pid_non_existing = os.fork()
64 09352fa4 Iustin Pop
    if pid_non_existing == 0:
65 09352fa4 Iustin Pop
      os._exit(0)
66 09352fa4 Iustin Pop
    elif pid_non_existing < 0:
67 09352fa4 Iustin Pop
      raise SystemError("can't fork")
68 09352fa4 Iustin Pop
    os.waitpid(pid_non_existing, 0)
69 09352fa4 Iustin Pop
    self.assert_(not IsProcessAlive(pid_non_existing),
70 09352fa4 Iustin Pop
                 "nonexisting process detected")
71 a8083063 Iustin Pop
72 d9f311d7 Iustin Pop
73 af99afa6 Guido Trotter
class TestPidFileFunctions(unittest.TestCase):
74 d9f311d7 Iustin Pop
  """Tests for WritePidFile, RemovePidFile and ReadPidFile"""
75 af99afa6 Guido Trotter
76 af99afa6 Guido Trotter
  def setUp(self):
77 af99afa6 Guido Trotter
    self.dir = tempfile.mkdtemp()
78 af99afa6 Guido Trotter
    self.f_dpn = lambda name: os.path.join(self.dir, "%s.pid" % name)
79 53beffbb Iustin Pop
    utils.DaemonPidFileName = self.f_dpn
80 af99afa6 Guido Trotter
81 af99afa6 Guido Trotter
  def testPidFileFunctions(self):
82 d9f311d7 Iustin Pop
    pid_file = self.f_dpn('test')
83 af99afa6 Guido Trotter
    utils.WritePidFile('test')
84 d9f311d7 Iustin Pop
    self.failUnless(os.path.exists(pid_file),
85 d9f311d7 Iustin Pop
                    "PID file should have been created")
86 d9f311d7 Iustin Pop
    read_pid = utils.ReadPidFile(pid_file)
87 d9f311d7 Iustin Pop
    self.failUnlessEqual(read_pid, os.getpid())
88 d9f311d7 Iustin Pop
    self.failUnless(utils.IsProcessAlive(read_pid))
89 d9f311d7 Iustin Pop
    self.failUnlessRaises(GenericError, utils.WritePidFile, 'test')
90 d9f311d7 Iustin Pop
    utils.RemovePidFile('test')
91 d9f311d7 Iustin Pop
    self.failIf(os.path.exists(pid_file),
92 d9f311d7 Iustin Pop
                "PID file should not exist anymore")
93 d9f311d7 Iustin Pop
    self.failUnlessEqual(utils.ReadPidFile(pid_file), 0,
94 d9f311d7 Iustin Pop
                         "ReadPidFile should return 0 for missing pid file")
95 d9f311d7 Iustin Pop
    fh = open(pid_file, "w")
96 d9f311d7 Iustin Pop
    fh.write("blah\n")
97 d9f311d7 Iustin Pop
    fh.close()
98 d9f311d7 Iustin Pop
    self.failUnlessEqual(utils.ReadPidFile(pid_file), 0,
99 d9f311d7 Iustin Pop
                         "ReadPidFile should return 0 for invalid pid file")
100 af99afa6 Guido Trotter
    utils.RemovePidFile('test')
101 d9f311d7 Iustin Pop
    self.failIf(os.path.exists(pid_file),
102 d9f311d7 Iustin Pop
                "PID file should not exist anymore")
103 af99afa6 Guido Trotter
104 b2a1f511 Iustin Pop
  def testKill(self):
105 b2a1f511 Iustin Pop
    pid_file = self.f_dpn('child')
106 b2a1f511 Iustin Pop
    r_fd, w_fd = os.pipe()
107 b2a1f511 Iustin Pop
    new_pid = os.fork()
108 b2a1f511 Iustin Pop
    if new_pid == 0: #child
109 b2a1f511 Iustin Pop
      utils.WritePidFile('child')
110 b2a1f511 Iustin Pop
      os.write(w_fd, 'a')
111 b2a1f511 Iustin Pop
      signal.pause()
112 b2a1f511 Iustin Pop
      os._exit(0)
113 b2a1f511 Iustin Pop
      return
114 b2a1f511 Iustin Pop
    # else we are in the parent
115 b2a1f511 Iustin Pop
    # wait until the child has written the pid file
116 b2a1f511 Iustin Pop
    os.read(r_fd, 1)
117 b2a1f511 Iustin Pop
    read_pid = utils.ReadPidFile(pid_file)
118 b2a1f511 Iustin Pop
    self.failUnlessEqual(read_pid, new_pid)
119 b2a1f511 Iustin Pop
    self.failUnless(utils.IsProcessAlive(new_pid))
120 ff5251bc Iustin Pop
    utils.KillProcess(new_pid, waitpid=True)
121 b2a1f511 Iustin Pop
    self.failIf(utils.IsProcessAlive(new_pid))
122 b2a1f511 Iustin Pop
    utils.RemovePidFile('child')
123 b2a1f511 Iustin Pop
    self.failUnlessRaises(ProgrammerError, utils.KillProcess, 0)
124 b2a1f511 Iustin Pop
125 af99afa6 Guido Trotter
  def tearDown(self):
126 d9f311d7 Iustin Pop
    for name in os.listdir(self.dir):
127 d9f311d7 Iustin Pop
      os.unlink(os.path.join(self.dir, name))
128 af99afa6 Guido Trotter
    os.rmdir(self.dir)
129 af99afa6 Guido Trotter
130 a8083063 Iustin Pop
131 36117c2b Iustin Pop
class TestRunCmd(testutils.GanetiTestCase):
132 a8083063 Iustin Pop
  """Testing case for the RunCmd function"""
133 a8083063 Iustin Pop
134 a8083063 Iustin Pop
  def setUp(self):
135 51596eb2 Iustin Pop
    testutils.GanetiTestCase.setUp(self)
136 a8083063 Iustin Pop
    self.magic = time.ctime() + " ganeti test"
137 51596eb2 Iustin Pop
    self.fname = self._CreateTempFile()
138 a8083063 Iustin Pop
139 a8083063 Iustin Pop
  def testOk(self):
140 31ee599c Michael Hanselmann
    """Test successful exit code"""
141 a8083063 Iustin Pop
    result = RunCmd("/bin/sh -c 'exit 0'")
142 a8083063 Iustin Pop
    self.assertEqual(result.exit_code, 0)
143 36117c2b Iustin Pop
    self.assertEqual(result.output, "")
144 a8083063 Iustin Pop
145 a8083063 Iustin Pop
  def testFail(self):
146 a8083063 Iustin Pop
    """Test fail exit code"""
147 a8083063 Iustin Pop
    result = RunCmd("/bin/sh -c 'exit 1'")
148 a8083063 Iustin Pop
    self.assertEqual(result.exit_code, 1)
149 36117c2b Iustin Pop
    self.assertEqual(result.output, "")
150 a8083063 Iustin Pop
151 a8083063 Iustin Pop
  def testStdout(self):
152 a8083063 Iustin Pop
    """Test standard output"""
153 a8083063 Iustin Pop
    cmd = 'echo -n "%s"' % self.magic
154 a8083063 Iustin Pop
    result = RunCmd("/bin/sh -c '%s'" % cmd)
155 a8083063 Iustin Pop
    self.assertEqual(result.stdout, self.magic)
156 36117c2b Iustin Pop
    result = RunCmd("/bin/sh -c '%s'" % cmd, output=self.fname)
157 36117c2b Iustin Pop
    self.assertEqual(result.output, "")
158 36117c2b Iustin Pop
    self.assertFileContent(self.fname, self.magic)
159 a8083063 Iustin Pop
160 a8083063 Iustin Pop
  def testStderr(self):
161 a8083063 Iustin Pop
    """Test standard error"""
162 a8083063 Iustin Pop
    cmd = 'echo -n "%s"' % self.magic
163 a8083063 Iustin Pop
    result = RunCmd("/bin/sh -c '%s' 1>&2" % cmd)
164 a8083063 Iustin Pop
    self.assertEqual(result.stderr, self.magic)
165 36117c2b Iustin Pop
    result = RunCmd("/bin/sh -c '%s' 1>&2" % cmd, output=self.fname)
166 36117c2b Iustin Pop
    self.assertEqual(result.output, "")
167 36117c2b Iustin Pop
    self.assertFileContent(self.fname, self.magic)
168 a8083063 Iustin Pop
169 a8083063 Iustin Pop
  def testCombined(self):
170 a8083063 Iustin Pop
    """Test combined output"""
171 a8083063 Iustin Pop
    cmd = 'echo -n "A%s"; echo -n "B%s" 1>&2' % (self.magic, self.magic)
172 36117c2b Iustin Pop
    expected = "A" + self.magic + "B" + self.magic
173 a8083063 Iustin Pop
    result = RunCmd("/bin/sh -c '%s'" % cmd)
174 36117c2b Iustin Pop
    self.assertEqual(result.output, expected)
175 36117c2b Iustin Pop
    result = RunCmd("/bin/sh -c '%s'" % cmd, output=self.fname)
176 36117c2b Iustin Pop
    self.assertEqual(result.output, "")
177 36117c2b Iustin Pop
    self.assertFileContent(self.fname, expected)
178 a8083063 Iustin Pop
179 a8083063 Iustin Pop
  def testSignal(self):
180 01fd6005 Manuel Franceschini
    """Test signal"""
181 01fd6005 Manuel Franceschini
    result = RunCmd(["python", "-c", "import os; os.kill(os.getpid(), 15)"])
182 a8083063 Iustin Pop
    self.assertEqual(result.signal, 15)
183 36117c2b Iustin Pop
    self.assertEqual(result.output, "")
184 a8083063 Iustin Pop
185 7fcf849f Iustin Pop
  def testListRun(self):
186 7fcf849f Iustin Pop
    """Test list runs"""
187 7fcf849f Iustin Pop
    result = RunCmd(["true"])
188 7fcf849f Iustin Pop
    self.assertEqual(result.signal, None)
189 7fcf849f Iustin Pop
    self.assertEqual(result.exit_code, 0)
190 7fcf849f Iustin Pop
    result = RunCmd(["/bin/sh", "-c", "exit 1"])
191 7fcf849f Iustin Pop
    self.assertEqual(result.signal, None)
192 7fcf849f Iustin Pop
    self.assertEqual(result.exit_code, 1)
193 7fcf849f Iustin Pop
    result = RunCmd(["echo", "-n", self.magic])
194 7fcf849f Iustin Pop
    self.assertEqual(result.signal, None)
195 7fcf849f Iustin Pop
    self.assertEqual(result.exit_code, 0)
196 7fcf849f Iustin Pop
    self.assertEqual(result.stdout, self.magic)
197 7fcf849f Iustin Pop
198 36117c2b Iustin Pop
  def testFileEmptyOutput(self):
199 36117c2b Iustin Pop
    """Test file output"""
200 36117c2b Iustin Pop
    result = RunCmd(["true"], output=self.fname)
201 36117c2b Iustin Pop
    self.assertEqual(result.signal, None)
202 36117c2b Iustin Pop
    self.assertEqual(result.exit_code, 0)
203 36117c2b Iustin Pop
    self.assertFileContent(self.fname, "")
204 36117c2b Iustin Pop
205 f6441c7c Iustin Pop
  def testLang(self):
206 f6441c7c Iustin Pop
    """Test locale environment"""
207 23f41a3e Michael Hanselmann
    old_env = os.environ.copy()
208 23f41a3e Michael Hanselmann
    try:
209 23f41a3e Michael Hanselmann
      os.environ["LANG"] = "en_US.UTF-8"
210 23f41a3e Michael Hanselmann
      os.environ["LC_ALL"] = "en_US.UTF-8"
211 23f41a3e Michael Hanselmann
      result = RunCmd(["locale"])
212 23f41a3e Michael Hanselmann
      for line in result.output.splitlines():
213 23f41a3e Michael Hanselmann
        key, value = line.split("=", 1)
214 23f41a3e Michael Hanselmann
        # Ignore these variables, they're overridden by LC_ALL
215 23f41a3e Michael Hanselmann
        if key == "LANG" or key == "LANGUAGE":
216 23f41a3e Michael Hanselmann
          continue
217 23f41a3e Michael Hanselmann
        self.failIf(value and value != "C" and value != '"C"',
218 23f41a3e Michael Hanselmann
            "Variable %s is set to the invalid value '%s'" % (key, value))
219 23f41a3e Michael Hanselmann
    finally:
220 23f41a3e Michael Hanselmann
      os.environ = old_env
221 f6441c7c Iustin Pop
222 8797df43 Iustin Pop
  def testDefaultCwd(self):
223 8797df43 Iustin Pop
    """Test default working directory"""
224 8797df43 Iustin Pop
    self.failUnlessEqual(RunCmd(["pwd"]).stdout.strip(), "/")
225 8797df43 Iustin Pop
226 8797df43 Iustin Pop
  def testCwd(self):
227 8797df43 Iustin Pop
    """Test default working directory"""
228 8797df43 Iustin Pop
    self.failUnlessEqual(RunCmd(["pwd"], cwd="/").stdout.strip(), "/")
229 8797df43 Iustin Pop
    self.failUnlessEqual(RunCmd(["pwd"], cwd="/tmp").stdout.strip(), "/tmp")
230 8797df43 Iustin Pop
    cwd = os.getcwd()
231 8797df43 Iustin Pop
    self.failUnlessEqual(RunCmd(["pwd"], cwd=cwd).stdout.strip(), cwd)
232 8797df43 Iustin Pop
233 a8083063 Iustin Pop
234 a8083063 Iustin Pop
class TestRemoveFile(unittest.TestCase):
235 a8083063 Iustin Pop
  """Test case for the RemoveFile function"""
236 a8083063 Iustin Pop
237 a8083063 Iustin Pop
  def setUp(self):
238 a8083063 Iustin Pop
    """Create a temp dir and file for each case"""
239 a8083063 Iustin Pop
    self.tmpdir = tempfile.mkdtemp('', 'ganeti-unittest-')
240 a8083063 Iustin Pop
    fd, self.tmpfile = tempfile.mkstemp('', '', self.tmpdir)
241 a8083063 Iustin Pop
    os.close(fd)
242 a8083063 Iustin Pop
243 a8083063 Iustin Pop
  def tearDown(self):
244 a8083063 Iustin Pop
    if os.path.exists(self.tmpfile):
245 a8083063 Iustin Pop
      os.unlink(self.tmpfile)
246 a8083063 Iustin Pop
    os.rmdir(self.tmpdir)
247 a8083063 Iustin Pop
248 a8083063 Iustin Pop
249 a8083063 Iustin Pop
  def testIgnoreDirs(self):
250 a8083063 Iustin Pop
    """Test that RemoveFile() ignores directories"""
251 a8083063 Iustin Pop
    self.assertEqual(None, RemoveFile(self.tmpdir))
252 a8083063 Iustin Pop
253 a8083063 Iustin Pop
254 a8083063 Iustin Pop
  def testIgnoreNotExisting(self):
255 a8083063 Iustin Pop
    """Test that RemoveFile() ignores non-existing files"""
256 a8083063 Iustin Pop
    RemoveFile(self.tmpfile)
257 a8083063 Iustin Pop
    RemoveFile(self.tmpfile)
258 a8083063 Iustin Pop
259 a8083063 Iustin Pop
260 a8083063 Iustin Pop
  def testRemoveFile(self):
261 a8083063 Iustin Pop
    """Test that RemoveFile does remove a file"""
262 a8083063 Iustin Pop
    RemoveFile(self.tmpfile)
263 a8083063 Iustin Pop
    if os.path.exists(self.tmpfile):
264 a8083063 Iustin Pop
      self.fail("File '%s' not removed" % self.tmpfile)
265 a8083063 Iustin Pop
266 a8083063 Iustin Pop
267 a8083063 Iustin Pop
  def testRemoveSymlink(self):
268 a8083063 Iustin Pop
    """Test that RemoveFile does remove symlinks"""
269 a8083063 Iustin Pop
    symlink = self.tmpdir + "/symlink"
270 a8083063 Iustin Pop
    os.symlink("no-such-file", symlink)
271 a8083063 Iustin Pop
    RemoveFile(symlink)
272 a8083063 Iustin Pop
    if os.path.exists(symlink):
273 a8083063 Iustin Pop
      self.fail("File '%s' not removed" % symlink)
274 a8083063 Iustin Pop
    os.symlink(self.tmpfile, symlink)
275 a8083063 Iustin Pop
    RemoveFile(symlink)
276 a8083063 Iustin Pop
    if os.path.exists(symlink):
277 a8083063 Iustin Pop
      self.fail("File '%s' not removed" % symlink)
278 a8083063 Iustin Pop
279 a8083063 Iustin Pop
280 6e797216 Michael Hanselmann
class TestRename(unittest.TestCase):
281 6e797216 Michael Hanselmann
  """Test case for RenameFile"""
282 6e797216 Michael Hanselmann
283 6e797216 Michael Hanselmann
  def setUp(self):
284 6e797216 Michael Hanselmann
    """Create a temporary directory"""
285 6e797216 Michael Hanselmann
    self.tmpdir = tempfile.mkdtemp()
286 6e797216 Michael Hanselmann
    self.tmpfile = os.path.join(self.tmpdir, "test1")
287 6e797216 Michael Hanselmann
288 6e797216 Michael Hanselmann
    # Touch the file
289 6e797216 Michael Hanselmann
    open(self.tmpfile, "w").close()
290 6e797216 Michael Hanselmann
291 6e797216 Michael Hanselmann
  def tearDown(self):
292 6e797216 Michael Hanselmann
    """Remove temporary directory"""
293 6e797216 Michael Hanselmann
    shutil.rmtree(self.tmpdir)
294 6e797216 Michael Hanselmann
295 6e797216 Michael Hanselmann
  def testSimpleRename1(self):
296 6e797216 Michael Hanselmann
    """Simple rename 1"""
297 6e797216 Michael Hanselmann
    utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "xyz"))
298 a426508d Michael Hanselmann
    self.assert_(os.path.isfile(os.path.join(self.tmpdir, "xyz")))
299 6e797216 Michael Hanselmann
300 6e797216 Michael Hanselmann
  def testSimpleRename2(self):
301 6e797216 Michael Hanselmann
    """Simple rename 2"""
302 6e797216 Michael Hanselmann
    utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "xyz"),
303 6e797216 Michael Hanselmann
                     mkdir=True)
304 a426508d Michael Hanselmann
    self.assert_(os.path.isfile(os.path.join(self.tmpdir, "xyz")))
305 6e797216 Michael Hanselmann
306 6e797216 Michael Hanselmann
  def testRenameMkdir(self):
307 6e797216 Michael Hanselmann
    """Rename with mkdir"""
308 6e797216 Michael Hanselmann
    utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "test/xyz"),
309 6e797216 Michael Hanselmann
                     mkdir=True)
310 a426508d Michael Hanselmann
    self.assert_(os.path.isdir(os.path.join(self.tmpdir, "test")))
311 a426508d Michael Hanselmann
    self.assert_(os.path.isfile(os.path.join(self.tmpdir, "test/xyz")))
312 a426508d Michael Hanselmann
313 a426508d Michael Hanselmann
    utils.RenameFile(os.path.join(self.tmpdir, "test/xyz"),
314 a426508d Michael Hanselmann
                     os.path.join(self.tmpdir, "test/foo/bar/baz"),
315 a426508d Michael Hanselmann
                     mkdir=True)
316 a426508d Michael Hanselmann
    self.assert_(os.path.isdir(os.path.join(self.tmpdir, "test")))
317 a426508d Michael Hanselmann
    self.assert_(os.path.isdir(os.path.join(self.tmpdir, "test/foo/bar")))
318 a426508d Michael Hanselmann
    self.assert_(os.path.isfile(os.path.join(self.tmpdir, "test/foo/bar/baz")))
319 6e797216 Michael Hanselmann
320 6e797216 Michael Hanselmann
321 a8083063 Iustin Pop
class TestMatchNameComponent(unittest.TestCase):
322 a8083063 Iustin Pop
  """Test case for the MatchNameComponent function"""
323 a8083063 Iustin Pop
324 a8083063 Iustin Pop
  def testEmptyList(self):
325 a8083063 Iustin Pop
    """Test that there is no match against an empty list"""
326 a8083063 Iustin Pop
327 a8083063 Iustin Pop
    self.failUnlessEqual(MatchNameComponent("", []), None)
328 a8083063 Iustin Pop
    self.failUnlessEqual(MatchNameComponent("test", []), None)
329 a8083063 Iustin Pop
330 a8083063 Iustin Pop
  def testSingleMatch(self):
331 a8083063 Iustin Pop
    """Test that a single match is performed correctly"""
332 a8083063 Iustin Pop
    mlist = ["test1.example.com", "test2.example.com", "test3.example.com"]
333 a8083063 Iustin Pop
    for key in "test2", "test2.example", "test2.example.com":
334 a8083063 Iustin Pop
      self.failUnlessEqual(MatchNameComponent(key, mlist), mlist[1])
335 a8083063 Iustin Pop
336 a8083063 Iustin Pop
  def testMultipleMatches(self):
337 a8083063 Iustin Pop
    """Test that a multiple match is returned as None"""
338 a8083063 Iustin Pop
    mlist = ["test1.example.com", "test1.example.org", "test1.example.net"]
339 a8083063 Iustin Pop
    for key in "test1", "test1.example":
340 a8083063 Iustin Pop
      self.failUnlessEqual(MatchNameComponent(key, mlist), None)
341 a8083063 Iustin Pop
342 3a541d90 Iustin Pop
  def testFullMatch(self):
343 3a541d90 Iustin Pop
    """Test that a full match is returned correctly"""
344 3a541d90 Iustin Pop
    key1 = "test1"
345 3a541d90 Iustin Pop
    key2 = "test1.example"
346 3a541d90 Iustin Pop
    mlist = [key2, key2 + ".com"]
347 3a541d90 Iustin Pop
    self.failUnlessEqual(MatchNameComponent(key1, mlist), None)
348 3a541d90 Iustin Pop
    self.failUnlessEqual(MatchNameComponent(key2, mlist), key2)
349 3a541d90 Iustin Pop
350 256eb94b Guido Trotter
  def testCaseInsensitivePartialMatch(self):
351 256eb94b Guido Trotter
    """Test for the case_insensitive keyword"""
352 256eb94b Guido Trotter
    mlist = ["test1.example.com", "test2.example.net"]
353 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("test2", mlist, case_sensitive=False),
354 256eb94b Guido Trotter
                     "test2.example.net")
355 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("Test2", mlist, case_sensitive=False),
356 256eb94b Guido Trotter
                     "test2.example.net")
357 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("teSt2", mlist, case_sensitive=False),
358 256eb94b Guido Trotter
                     "test2.example.net")
359 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("TeSt2", mlist, case_sensitive=False),
360 256eb94b Guido Trotter
                     "test2.example.net")
361 256eb94b Guido Trotter
362 256eb94b Guido Trotter
363 256eb94b Guido Trotter
  def testCaseInsensitiveFullMatch(self):
364 256eb94b Guido Trotter
    mlist = ["ts1.ex", "ts1.ex.org", "ts2.ex", "Ts2.ex"]
365 256eb94b Guido Trotter
    # Between the two ts1 a full string match non-case insensitive should work
366 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("Ts1", mlist, case_sensitive=False),
367 256eb94b Guido Trotter
                     None)
368 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("Ts1.ex", mlist, case_sensitive=False),
369 256eb94b Guido Trotter
                     "ts1.ex")
370 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("ts1.ex", mlist, case_sensitive=False),
371 256eb94b Guido Trotter
                     "ts1.ex")
372 256eb94b Guido Trotter
    # Between the two ts2 only case differs, so only case-match works
373 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("ts2.ex", mlist, case_sensitive=False),
374 256eb94b Guido Trotter
                     "ts2.ex")
375 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("Ts2.ex", mlist, case_sensitive=False),
376 256eb94b Guido Trotter
                     "Ts2.ex")
377 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("TS2.ex", mlist, case_sensitive=False),
378 256eb94b Guido Trotter
                     None)
379 256eb94b Guido Trotter
380 a8083063 Iustin Pop
381 a8083063 Iustin Pop
class TestFormatUnit(unittest.TestCase):
382 a8083063 Iustin Pop
  """Test case for the FormatUnit function"""
383 a8083063 Iustin Pop
384 a8083063 Iustin Pop
  def testMiB(self):
385 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1, 'h'), '1M')
386 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(100, 'h'), '100M')
387 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1023, 'h'), '1023M')
388 9fbfbb7b Iustin Pop
389 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1, 'm'), '1')
390 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(100, 'm'), '100')
391 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1023, 'm'), '1023')
392 9fbfbb7b Iustin Pop
393 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024, 'm'), '1024')
394 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1536, 'm'), '1536')
395 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(17133, 'm'), '17133')
396 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024 - 1, 'm'), '1048575')
397 a8083063 Iustin Pop
398 a8083063 Iustin Pop
  def testGiB(self):
399 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024, 'h'), '1.0G')
400 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1536, 'h'), '1.5G')
401 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(17133, 'h'), '16.7G')
402 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024 - 1, 'h'), '1024.0G')
403 9fbfbb7b Iustin Pop
404 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024, 'g'), '1.0')
405 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1536, 'g'), '1.5')
406 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(17133, 'g'), '16.7')
407 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024 - 1, 'g'), '1024.0')
408 9fbfbb7b Iustin Pop
409 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024, 'g'), '1024.0')
410 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(5120 * 1024, 'g'), '5120.0')
411 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(29829 * 1024, 'g'), '29829.0')
412 a8083063 Iustin Pop
413 a8083063 Iustin Pop
  def testTiB(self):
414 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024, 'h'), '1.0T')
415 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(5120 * 1024, 'h'), '5.0T')
416 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(29829 * 1024, 'h'), '29.1T')
417 a8083063 Iustin Pop
418 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024, 't'), '1.0')
419 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(5120 * 1024, 't'), '5.0')
420 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(29829 * 1024, 't'), '29.1')
421 a8083063 Iustin Pop
422 a8083063 Iustin Pop
class TestParseUnit(unittest.TestCase):
423 a8083063 Iustin Pop
  """Test case for the ParseUnit function"""
424 a8083063 Iustin Pop
425 a8083063 Iustin Pop
  SCALES = (('', 1),
426 a8083063 Iustin Pop
            ('M', 1), ('G', 1024), ('T', 1024 * 1024),
427 a8083063 Iustin Pop
            ('MB', 1), ('GB', 1024), ('TB', 1024 * 1024),
428 a8083063 Iustin Pop
            ('MiB', 1), ('GiB', 1024), ('TiB', 1024 * 1024))
429 a8083063 Iustin Pop
430 a8083063 Iustin Pop
  def testRounding(self):
431 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('0'), 0)
432 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1'), 4)
433 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('2'), 4)
434 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('3'), 4)
435 a8083063 Iustin Pop
436 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('124'), 124)
437 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('125'), 128)
438 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('126'), 128)
439 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('127'), 128)
440 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('128'), 128)
441 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('129'), 132)
442 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('130'), 132)
443 a8083063 Iustin Pop
444 a8083063 Iustin Pop
  def testFloating(self):
445 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('0'), 0)
446 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('0.5'), 4)
447 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.75'), 4)
448 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.99'), 4)
449 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('2.00'), 4)
450 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('2.01'), 4)
451 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('3.99'), 4)
452 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('4.00'), 4)
453 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('4.01'), 8)
454 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.5G'), 1536)
455 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.8G'), 1844)
456 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('8.28T'), 8682212)
457 a8083063 Iustin Pop
458 a8083063 Iustin Pop
  def testSuffixes(self):
459 a8083063 Iustin Pop
    for sep in ('', ' ', '   ', "\t", "\t "):
460 a8083063 Iustin Pop
      for suffix, scale in TestParseUnit.SCALES:
461 a8083063 Iustin Pop
        for func in (lambda x: x, str.lower, str.upper):
462 667479d5 Michael Hanselmann
          self.assertEqual(ParseUnit('1024' + sep + func(suffix)),
463 667479d5 Michael Hanselmann
                           1024 * scale)
464 a8083063 Iustin Pop
465 a8083063 Iustin Pop
  def testInvalidInput(self):
466 a8083063 Iustin Pop
    for sep in ('-', '_', ',', 'a'):
467 a8083063 Iustin Pop
      for suffix, _ in TestParseUnit.SCALES:
468 a8083063 Iustin Pop
        self.assertRaises(UnitParseError, ParseUnit, '1' + sep + suffix)
469 a8083063 Iustin Pop
470 a8083063 Iustin Pop
    for suffix, _ in TestParseUnit.SCALES:
471 a8083063 Iustin Pop
      self.assertRaises(UnitParseError, ParseUnit, '1,3' + suffix)
472 a8083063 Iustin Pop
473 a8083063 Iustin Pop
474 c9c4f19e Michael Hanselmann
class TestSshKeys(testutils.GanetiTestCase):
475 a8083063 Iustin Pop
  """Test case for the AddAuthorizedKey function"""
476 a8083063 Iustin Pop
477 a8083063 Iustin Pop
  KEY_A = 'ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a'
478 a8083063 Iustin Pop
  KEY_B = ('command="/usr/bin/fooserver -t --verbose",from="1.2.3.4" '
479 a8083063 Iustin Pop
           'ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b')
480 a8083063 Iustin Pop
481 ebe8ef17 Michael Hanselmann
  def setUp(self):
482 51596eb2 Iustin Pop
    testutils.GanetiTestCase.setUp(self)
483 51596eb2 Iustin Pop
    self.tmpname = self._CreateTempFile()
484 51596eb2 Iustin Pop
    handle = open(self.tmpname, 'w')
485 a8083063 Iustin Pop
    try:
486 51596eb2 Iustin Pop
      handle.write("%s\n" % TestSshKeys.KEY_A)
487 51596eb2 Iustin Pop
      handle.write("%s\n" % TestSshKeys.KEY_B)
488 51596eb2 Iustin Pop
    finally:
489 51596eb2 Iustin Pop
      handle.close()
490 a8083063 Iustin Pop
491 a8083063 Iustin Pop
  def testAddingNewKey(self):
492 ebe8ef17 Michael Hanselmann
    AddAuthorizedKey(self.tmpname, 'ssh-dss AAAAB3NzaC1kc3MAAACB root@test')
493 a8083063 Iustin Pop
494 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
495 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
496 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
497 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n"
498 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1kc3MAAACB root@test\n")
499 a8083063 Iustin Pop
500 f89f17a8 Michael Hanselmann
  def testAddingAlmostButNotCompletelyTheSameKey(self):
501 ebe8ef17 Michael Hanselmann
    AddAuthorizedKey(self.tmpname,
502 ebe8ef17 Michael Hanselmann
        'ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@test')
503 ebe8ef17 Michael Hanselmann
504 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
505 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
506 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
507 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n"
508 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@test\n")
509 a8083063 Iustin Pop
510 a8083063 Iustin Pop
  def testAddingExistingKeyWithSomeMoreSpaces(self):
511 ebe8ef17 Michael Hanselmann
    AddAuthorizedKey(self.tmpname,
512 ebe8ef17 Michael Hanselmann
        'ssh-dss  AAAAB3NzaC1w5256closdj32mZaQU   root@key-a')
513 a8083063 Iustin Pop
514 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
515 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
516 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
517 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
518 a8083063 Iustin Pop
519 a8083063 Iustin Pop
  def testRemovingExistingKeyWithSomeMoreSpaces(self):
520 ebe8ef17 Michael Hanselmann
    RemoveAuthorizedKey(self.tmpname,
521 ebe8ef17 Michael Hanselmann
        'ssh-dss  AAAAB3NzaC1w5256closdj32mZaQU   root@key-a')
522 a8083063 Iustin Pop
523 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
524 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
525 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
526 a8083063 Iustin Pop
527 a8083063 Iustin Pop
  def testRemovingNonExistingKey(self):
528 ebe8ef17 Michael Hanselmann
    RemoveAuthorizedKey(self.tmpname,
529 ebe8ef17 Michael Hanselmann
        'ssh-dss  AAAAB3Nsdfj230xxjxJjsjwjsjdjU   root@test')
530 a8083063 Iustin Pop
531 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
532 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
533 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
534 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
535 a8083063 Iustin Pop
536 a8083063 Iustin Pop
537 c9c4f19e Michael Hanselmann
class TestEtcHosts(testutils.GanetiTestCase):
538 899d2a81 Michael Hanselmann
  """Test functions modifying /etc/hosts"""
539 899d2a81 Michael Hanselmann
540 ebe8ef17 Michael Hanselmann
  def setUp(self):
541 51596eb2 Iustin Pop
    testutils.GanetiTestCase.setUp(self)
542 51596eb2 Iustin Pop
    self.tmpname = self._CreateTempFile()
543 51596eb2 Iustin Pop
    handle = open(self.tmpname, 'w')
544 899d2a81 Michael Hanselmann
    try:
545 51596eb2 Iustin Pop
      handle.write('# This is a test file for /etc/hosts\n')
546 51596eb2 Iustin Pop
      handle.write('127.0.0.1\tlocalhost\n')
547 51596eb2 Iustin Pop
      handle.write('192.168.1.1 router gw\n')
548 51596eb2 Iustin Pop
    finally:
549 51596eb2 Iustin Pop
      handle.close()
550 899d2a81 Michael Hanselmann
551 9440aeab Michael Hanselmann
  def testSettingNewIp(self):
552 ebe8ef17 Michael Hanselmann
    SetEtcHostsEntry(self.tmpname, '1.2.3.4', 'myhost.domain.tld', ['myhost'])
553 899d2a81 Michael Hanselmann
554 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
555 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
556 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
557 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router gw\n"
558 ebe8ef17 Michael Hanselmann
      "1.2.3.4\tmyhost.domain.tld myhost\n")
559 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
560 899d2a81 Michael Hanselmann
561 9440aeab Michael Hanselmann
  def testSettingExistingIp(self):
562 ebe8ef17 Michael Hanselmann
    SetEtcHostsEntry(self.tmpname, '192.168.1.1', 'myhost.domain.tld',
563 ebe8ef17 Michael Hanselmann
                     ['myhost'])
564 899d2a81 Michael Hanselmann
565 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
566 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
567 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
568 ebe8ef17 Michael Hanselmann
      "192.168.1.1\tmyhost.domain.tld myhost\n")
569 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
570 899d2a81 Michael Hanselmann
571 7fbb1f65 Michael Hanselmann
  def testSettingDuplicateName(self):
572 7fbb1f65 Michael Hanselmann
    SetEtcHostsEntry(self.tmpname, '1.2.3.4', 'myhost', ['myhost'])
573 7fbb1f65 Michael Hanselmann
574 7fbb1f65 Michael Hanselmann
    self.assertFileContent(self.tmpname,
575 7fbb1f65 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
576 7fbb1f65 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
577 7fbb1f65 Michael Hanselmann
      "192.168.1.1 router gw\n"
578 7fbb1f65 Michael Hanselmann
      "1.2.3.4\tmyhost\n")
579 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
580 7fbb1f65 Michael Hanselmann
581 899d2a81 Michael Hanselmann
  def testRemovingExistingHost(self):
582 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'router')
583 899d2a81 Michael Hanselmann
584 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
585 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
586 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
587 ebe8ef17 Michael Hanselmann
      "192.168.1.1 gw\n")
588 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
589 899d2a81 Michael Hanselmann
590 899d2a81 Michael Hanselmann
  def testRemovingSingleExistingHost(self):
591 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'localhost')
592 899d2a81 Michael Hanselmann
593 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
594 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
595 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router gw\n")
596 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
597 899d2a81 Michael Hanselmann
598 899d2a81 Michael Hanselmann
  def testRemovingNonExistingHost(self):
599 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'myhost')
600 899d2a81 Michael Hanselmann
601 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
602 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
603 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
604 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router gw\n")
605 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
606 899d2a81 Michael Hanselmann
607 9440aeab Michael Hanselmann
  def testRemovingAlias(self):
608 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'gw')
609 9440aeab Michael Hanselmann
610 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
611 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
612 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
613 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router\n")
614 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
615 9440aeab Michael Hanselmann
616 899d2a81 Michael Hanselmann
617 a8083063 Iustin Pop
class TestShellQuoting(unittest.TestCase):
618 a8083063 Iustin Pop
  """Test case for shell quoting functions"""
619 a8083063 Iustin Pop
620 a8083063 Iustin Pop
  def testShellQuote(self):
621 a8083063 Iustin Pop
    self.assertEqual(ShellQuote('abc'), "abc")
622 a8083063 Iustin Pop
    self.assertEqual(ShellQuote('ab"c'), "'ab\"c'")
623 a8083063 Iustin Pop
    self.assertEqual(ShellQuote("a'bc"), "'a'\\''bc'")
624 a8083063 Iustin Pop
    self.assertEqual(ShellQuote("a b c"), "'a b c'")
625 a8083063 Iustin Pop
    self.assertEqual(ShellQuote("a b\\ c"), "'a b\\ c'")
626 a8083063 Iustin Pop
627 a8083063 Iustin Pop
  def testShellQuoteArgs(self):
628 a8083063 Iustin Pop
    self.assertEqual(ShellQuoteArgs(['a', 'b', 'c']), "a b c")
629 a8083063 Iustin Pop
    self.assertEqual(ShellQuoteArgs(['a', 'b"', 'c']), "a 'b\"' c")
630 a8083063 Iustin Pop
    self.assertEqual(ShellQuoteArgs(['a', 'b\'', 'c']), "a 'b'\\\''' c")
631 a8083063 Iustin Pop
632 a8083063 Iustin Pop
633 2c30e9d7 Alexander Schreiber
class TestTcpPing(unittest.TestCase):
634 2c30e9d7 Alexander Schreiber
  """Testcase for TCP version of ping - against listen(2)ing port"""
635 2c30e9d7 Alexander Schreiber
636 2c30e9d7 Alexander Schreiber
  def setUp(self):
637 2c30e9d7 Alexander Schreiber
    self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
638 16abfbc2 Alexander Schreiber
    self.listener.bind((constants.LOCALHOST_IP_ADDRESS, 0))
639 2c30e9d7 Alexander Schreiber
    self.listenerport = self.listener.getsockname()[1]
640 2c30e9d7 Alexander Schreiber
    self.listener.listen(1)
641 2c30e9d7 Alexander Schreiber
642 2c30e9d7 Alexander Schreiber
  def tearDown(self):
643 2c30e9d7 Alexander Schreiber
    self.listener.shutdown(socket.SHUT_RDWR)
644 2c30e9d7 Alexander Schreiber
    del self.listener
645 2c30e9d7 Alexander Schreiber
    del self.listenerport
646 2c30e9d7 Alexander Schreiber
647 2c30e9d7 Alexander Schreiber
  def testTcpPingToLocalHostAccept(self):
648 16abfbc2 Alexander Schreiber
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
649 2c30e9d7 Alexander Schreiber
                         self.listenerport,
650 2c30e9d7 Alexander Schreiber
                         timeout=10,
651 b15d625f Iustin Pop
                         live_port_needed=True,
652 b15d625f Iustin Pop
                         source=constants.LOCALHOST_IP_ADDRESS,
653 b15d625f Iustin Pop
                         ),
654 2c30e9d7 Alexander Schreiber
                 "failed to connect to test listener")
655 2c30e9d7 Alexander Schreiber
656 b15d625f Iustin Pop
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
657 b15d625f Iustin Pop
                         self.listenerport,
658 b15d625f Iustin Pop
                         timeout=10,
659 b15d625f Iustin Pop
                         live_port_needed=True,
660 b15d625f Iustin Pop
                         ),
661 b15d625f Iustin Pop
                 "failed to connect to test listener (no source)")
662 b15d625f Iustin Pop
663 2c30e9d7 Alexander Schreiber
664 2c30e9d7 Alexander Schreiber
class TestTcpPingDeaf(unittest.TestCase):
665 2c30e9d7 Alexander Schreiber
  """Testcase for TCP version of ping - against non listen(2)ing port"""
666 2c30e9d7 Alexander Schreiber
667 2c30e9d7 Alexander Schreiber
  def setUp(self):
668 2c30e9d7 Alexander Schreiber
    self.deaflistener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
669 16abfbc2 Alexander Schreiber
    self.deaflistener.bind((constants.LOCALHOST_IP_ADDRESS, 0))
670 2c30e9d7 Alexander Schreiber
    self.deaflistenerport = self.deaflistener.getsockname()[1]
671 2c30e9d7 Alexander Schreiber
672 2c30e9d7 Alexander Schreiber
  def tearDown(self):
673 2c30e9d7 Alexander Schreiber
    del self.deaflistener
674 2c30e9d7 Alexander Schreiber
    del self.deaflistenerport
675 2c30e9d7 Alexander Schreiber
676 2c30e9d7 Alexander Schreiber
  def testTcpPingToLocalHostAcceptDeaf(self):
677 16abfbc2 Alexander Schreiber
    self.failIf(TcpPing(constants.LOCALHOST_IP_ADDRESS,
678 2c30e9d7 Alexander Schreiber
                        self.deaflistenerport,
679 16abfbc2 Alexander Schreiber
                        timeout=constants.TCP_PING_TIMEOUT,
680 b15d625f Iustin Pop
                        live_port_needed=True,
681 b15d625f Iustin Pop
                        source=constants.LOCALHOST_IP_ADDRESS,
682 b15d625f Iustin Pop
                        ), # need successful connect(2)
683 2c30e9d7 Alexander Schreiber
                "successfully connected to deaf listener")
684 2c30e9d7 Alexander Schreiber
685 b15d625f Iustin Pop
    self.failIf(TcpPing(constants.LOCALHOST_IP_ADDRESS,
686 b15d625f Iustin Pop
                        self.deaflistenerport,
687 b15d625f Iustin Pop
                        timeout=constants.TCP_PING_TIMEOUT,
688 b15d625f Iustin Pop
                        live_port_needed=True,
689 b15d625f Iustin Pop
                        ), # need successful connect(2)
690 b15d625f Iustin Pop
                "successfully connected to deaf listener (no source addr)")
691 b15d625f Iustin Pop
692 2c30e9d7 Alexander Schreiber
  def testTcpPingToLocalHostNoAccept(self):
693 16abfbc2 Alexander Schreiber
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
694 2c30e9d7 Alexander Schreiber
                         self.deaflistenerport,
695 16abfbc2 Alexander Schreiber
                         timeout=constants.TCP_PING_TIMEOUT,
696 b15d625f Iustin Pop
                         live_port_needed=False,
697 b15d625f Iustin Pop
                         source=constants.LOCALHOST_IP_ADDRESS,
698 b15d625f Iustin Pop
                         ), # ECONNREFUSED is OK
699 2c30e9d7 Alexander Schreiber
                 "failed to ping alive host on deaf port")
700 2c30e9d7 Alexander Schreiber
701 b15d625f Iustin Pop
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
702 b15d625f Iustin Pop
                         self.deaflistenerport,
703 b15d625f Iustin Pop
                         timeout=constants.TCP_PING_TIMEOUT,
704 b15d625f Iustin Pop
                         live_port_needed=False,
705 b15d625f Iustin Pop
                         ), # ECONNREFUSED is OK
706 b15d625f Iustin Pop
                 "failed to ping alive host on deaf port (no source addr)")
707 b15d625f Iustin Pop
708 2c30e9d7 Alexander Schreiber
709 caad16e2 Iustin Pop
class TestOwnIpAddress(unittest.TestCase):
710 caad16e2 Iustin Pop
  """Testcase for OwnIpAddress"""
711 caad16e2 Iustin Pop
712 caad16e2 Iustin Pop
  def testOwnLoopback(self):
713 caad16e2 Iustin Pop
    """check having the loopback ip"""
714 caad16e2 Iustin Pop
    self.failUnless(OwnIpAddress(constants.LOCALHOST_IP_ADDRESS),
715 caad16e2 Iustin Pop
                    "Should own the loopback address")
716 caad16e2 Iustin Pop
717 caad16e2 Iustin Pop
  def testNowOwnAddress(self):
718 caad16e2 Iustin Pop
    """check that I don't own an address"""
719 caad16e2 Iustin Pop
720 caad16e2 Iustin Pop
    # network 192.0.2.0/24 is reserved for test/documentation as per
721 caad16e2 Iustin Pop
    # rfc 3330, so we *should* not have an address of this range... if
722 caad16e2 Iustin Pop
    # this fails, we should extend the test to multiple addresses
723 caad16e2 Iustin Pop
    DST_IP = "192.0.2.1"
724 caad16e2 Iustin Pop
    self.failIf(OwnIpAddress(DST_IP), "Should not own IP address %s" % DST_IP)
725 caad16e2 Iustin Pop
726 caad16e2 Iustin Pop
727 eedbda4b Michael Hanselmann
class TestListVisibleFiles(unittest.TestCase):
728 eedbda4b Michael Hanselmann
  """Test case for ListVisibleFiles"""
729 eedbda4b Michael Hanselmann
730 eedbda4b Michael Hanselmann
  def setUp(self):
731 eedbda4b Michael Hanselmann
    self.path = tempfile.mkdtemp()
732 eedbda4b Michael Hanselmann
733 eedbda4b Michael Hanselmann
  def tearDown(self):
734 eedbda4b Michael Hanselmann
    shutil.rmtree(self.path)
735 eedbda4b Michael Hanselmann
736 eedbda4b Michael Hanselmann
  def _test(self, files, expected):
737 eedbda4b Michael Hanselmann
    # Sort a copy
738 eedbda4b Michael Hanselmann
    expected = expected[:]
739 eedbda4b Michael Hanselmann
    expected.sort()
740 eedbda4b Michael Hanselmann
741 eedbda4b Michael Hanselmann
    for name in files:
742 eedbda4b Michael Hanselmann
      f = open(os.path.join(self.path, name), 'w')
743 eedbda4b Michael Hanselmann
      try:
744 eedbda4b Michael Hanselmann
        f.write("Test\n")
745 eedbda4b Michael Hanselmann
      finally:
746 eedbda4b Michael Hanselmann
        f.close()
747 eedbda4b Michael Hanselmann
748 eedbda4b Michael Hanselmann
    found = ListVisibleFiles(self.path)
749 eedbda4b Michael Hanselmann
    found.sort()
750 eedbda4b Michael Hanselmann
751 eedbda4b Michael Hanselmann
    self.assertEqual(found, expected)
752 eedbda4b Michael Hanselmann
753 eedbda4b Michael Hanselmann
  def testAllVisible(self):
754 eedbda4b Michael Hanselmann
    files = ["a", "b", "c"]
755 eedbda4b Michael Hanselmann
    expected = files
756 eedbda4b Michael Hanselmann
    self._test(files, expected)
757 eedbda4b Michael Hanselmann
758 eedbda4b Michael Hanselmann
  def testNoneVisible(self):
759 eedbda4b Michael Hanselmann
    files = [".a", ".b", ".c"]
760 eedbda4b Michael Hanselmann
    expected = []
761 eedbda4b Michael Hanselmann
    self._test(files, expected)
762 eedbda4b Michael Hanselmann
763 eedbda4b Michael Hanselmann
  def testSomeVisible(self):
764 eedbda4b Michael Hanselmann
    files = ["a", "b", ".c"]
765 eedbda4b Michael Hanselmann
    expected = ["a", "b"]
766 eedbda4b Michael Hanselmann
    self._test(files, expected)
767 eedbda4b Michael Hanselmann
768 eedbda4b Michael Hanselmann
769 24818e8f Michael Hanselmann
class TestNewUUID(unittest.TestCase):
770 24818e8f Michael Hanselmann
  """Test case for NewUUID"""
771 59072e7e Michael Hanselmann
772 59072e7e Michael Hanselmann
  _re_uuid = re.compile('^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-'
773 59072e7e Michael Hanselmann
                        '[a-f0-9]{4}-[a-f0-9]{12}$')
774 59072e7e Michael Hanselmann
775 59072e7e Michael Hanselmann
  def runTest(self):
776 24818e8f Michael Hanselmann
    self.failUnless(self._re_uuid.match(utils.NewUUID()))
777 59072e7e Michael Hanselmann
778 59072e7e Michael Hanselmann
779 f7414041 Michael Hanselmann
class TestUniqueSequence(unittest.TestCase):
780 f7414041 Michael Hanselmann
  """Test case for UniqueSequence"""
781 f7414041 Michael Hanselmann
782 f7414041 Michael Hanselmann
  def _test(self, input, expected):
783 f7414041 Michael Hanselmann
    self.assertEqual(utils.UniqueSequence(input), expected)
784 f7414041 Michael Hanselmann
785 f7414041 Michael Hanselmann
  def runTest(self):
786 f7414041 Michael Hanselmann
    # Ordered input
787 f7414041 Michael Hanselmann
    self._test([1, 2, 3], [1, 2, 3])
788 f7414041 Michael Hanselmann
    self._test([1, 1, 2, 2, 3, 3], [1, 2, 3])
789 f7414041 Michael Hanselmann
    self._test([1, 2, 2, 3], [1, 2, 3])
790 f7414041 Michael Hanselmann
    self._test([1, 2, 3, 3], [1, 2, 3])
791 f7414041 Michael Hanselmann
792 f7414041 Michael Hanselmann
    # Unordered input
793 f7414041 Michael Hanselmann
    self._test([1, 2, 3, 1, 2, 3], [1, 2, 3])
794 f7414041 Michael Hanselmann
    self._test([1, 1, 2, 3, 3, 1, 2], [1, 2, 3])
795 f7414041 Michael Hanselmann
796 f7414041 Michael Hanselmann
    # Strings
797 f7414041 Michael Hanselmann
    self._test(["a", "a"], ["a"])
798 f7414041 Michael Hanselmann
    self._test(["a", "b"], ["a", "b"])
799 f7414041 Michael Hanselmann
    self._test(["a", "b", "a"], ["a", "b"])
800 f7414041 Michael Hanselmann
801 a87b4824 Michael Hanselmann
802 7b4126b7 Iustin Pop
class TestFirstFree(unittest.TestCase):
803 7b4126b7 Iustin Pop
  """Test case for the FirstFree function"""
804 7b4126b7 Iustin Pop
805 7b4126b7 Iustin Pop
  def test(self):
806 7b4126b7 Iustin Pop
    """Test FirstFree"""
807 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([0, 1, 3]), 2)
808 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([]), None)
809 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([3, 4, 6]), 0)
810 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([3, 4, 6], base=3), 5)
811 7b4126b7 Iustin Pop
    self.failUnlessRaises(AssertionError, FirstFree, [0, 3, 4, 6], base=3)
812 f7414041 Michael Hanselmann
813 a87b4824 Michael Hanselmann
814 f65f63ef Iustin Pop
class TestTailFile(testutils.GanetiTestCase):
815 f65f63ef Iustin Pop
  """Test case for the TailFile function"""
816 f65f63ef Iustin Pop
817 f65f63ef Iustin Pop
  def testEmpty(self):
818 f65f63ef Iustin Pop
    fname = self._CreateTempFile()
819 f65f63ef Iustin Pop
    self.failUnlessEqual(TailFile(fname), [])
820 f65f63ef Iustin Pop
    self.failUnlessEqual(TailFile(fname, lines=25), [])
821 f65f63ef Iustin Pop
822 f65f63ef Iustin Pop
  def testAllLines(self):
823 f65f63ef Iustin Pop
    data = ["test %d" % i for i in range(30)]
824 f65f63ef Iustin Pop
    for i in range(30):
825 f65f63ef Iustin Pop
      fname = self._CreateTempFile()
826 f65f63ef Iustin Pop
      fd = open(fname, "w")
827 f65f63ef Iustin Pop
      fd.write("\n".join(data[:i]))
828 f65f63ef Iustin Pop
      if i > 0:
829 f65f63ef Iustin Pop
        fd.write("\n")
830 f65f63ef Iustin Pop
      fd.close()
831 f65f63ef Iustin Pop
      self.failUnlessEqual(TailFile(fname, lines=i), data[:i])
832 f65f63ef Iustin Pop
833 f65f63ef Iustin Pop
  def testPartialLines(self):
834 f65f63ef Iustin Pop
    data = ["test %d" % i for i in range(30)]
835 f65f63ef Iustin Pop
    fname = self._CreateTempFile()
836 f65f63ef Iustin Pop
    fd = open(fname, "w")
837 f65f63ef Iustin Pop
    fd.write("\n".join(data))
838 f65f63ef Iustin Pop
    fd.write("\n")
839 f65f63ef Iustin Pop
    fd.close()
840 f65f63ef Iustin Pop
    for i in range(1, 30):
841 f65f63ef Iustin Pop
      self.failUnlessEqual(TailFile(fname, lines=i), data[-i:])
842 f65f63ef Iustin Pop
843 f65f63ef Iustin Pop
  def testBigFile(self):
844 f65f63ef Iustin Pop
    data = ["test %d" % i for i in range(30)]
845 f65f63ef Iustin Pop
    fname = self._CreateTempFile()
846 f65f63ef Iustin Pop
    fd = open(fname, "w")
847 f65f63ef Iustin Pop
    fd.write("X" * 1048576)
848 f65f63ef Iustin Pop
    fd.write("\n")
849 f65f63ef Iustin Pop
    fd.write("\n".join(data))
850 f65f63ef Iustin Pop
    fd.write("\n")
851 f65f63ef Iustin Pop
    fd.close()
852 f65f63ef Iustin Pop
    for i in range(1, 30):
853 f65f63ef Iustin Pop
      self.failUnlessEqual(TailFile(fname, lines=i), data[-i:])
854 f65f63ef Iustin Pop
855 f65f63ef Iustin Pop
856 a87b4824 Michael Hanselmann
class TestFileLock(unittest.TestCase):
857 a87b4824 Michael Hanselmann
  """Test case for the FileLock class"""
858 a87b4824 Michael Hanselmann
859 a87b4824 Michael Hanselmann
  def setUp(self):
860 a87b4824 Michael Hanselmann
    self.tmpfile = tempfile.NamedTemporaryFile()
861 a87b4824 Michael Hanselmann
    self.lock = utils.FileLock(self.tmpfile.name)
862 a87b4824 Michael Hanselmann
863 a87b4824 Michael Hanselmann
  def testSharedNonblocking(self):
864 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=False)
865 a87b4824 Michael Hanselmann
    self.lock.Close()
866 a87b4824 Michael Hanselmann
867 a87b4824 Michael Hanselmann
  def testExclusiveNonblocking(self):
868 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=False)
869 a87b4824 Michael Hanselmann
    self.lock.Close()
870 a87b4824 Michael Hanselmann
871 a87b4824 Michael Hanselmann
  def testUnlockNonblocking(self):
872 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=False)
873 a87b4824 Michael Hanselmann
    self.lock.Close()
874 a87b4824 Michael Hanselmann
875 a87b4824 Michael Hanselmann
  def testSharedBlocking(self):
876 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=True)
877 a87b4824 Michael Hanselmann
    self.lock.Close()
878 a87b4824 Michael Hanselmann
879 a87b4824 Michael Hanselmann
  def testExclusiveBlocking(self):
880 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=True)
881 a87b4824 Michael Hanselmann
    self.lock.Close()
882 a87b4824 Michael Hanselmann
883 a87b4824 Michael Hanselmann
  def testUnlockBlocking(self):
884 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=True)
885 a87b4824 Michael Hanselmann
    self.lock.Close()
886 a87b4824 Michael Hanselmann
887 a87b4824 Michael Hanselmann
  def testSharedExclusiveUnlock(self):
888 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=False)
889 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=False)
890 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=False)
891 a87b4824 Michael Hanselmann
    self.lock.Close()
892 a87b4824 Michael Hanselmann
893 a87b4824 Michael Hanselmann
  def testExclusiveSharedUnlock(self):
894 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=False)
895 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=False)
896 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=False)
897 a87b4824 Michael Hanselmann
    self.lock.Close()
898 a87b4824 Michael Hanselmann
899 a87b4824 Michael Hanselmann
  def testCloseShared(self):
900 a87b4824 Michael Hanselmann
    self.lock.Close()
901 a87b4824 Michael Hanselmann
    self.assertRaises(AssertionError, self.lock.Shared, blocking=False)
902 a87b4824 Michael Hanselmann
903 a87b4824 Michael Hanselmann
  def testCloseExclusive(self):
904 a87b4824 Michael Hanselmann
    self.lock.Close()
905 a87b4824 Michael Hanselmann
    self.assertRaises(AssertionError, self.lock.Exclusive, blocking=False)
906 a87b4824 Michael Hanselmann
907 a87b4824 Michael Hanselmann
  def testCloseUnlock(self):
908 a87b4824 Michael Hanselmann
    self.lock.Close()
909 a87b4824 Michael Hanselmann
    self.assertRaises(AssertionError, self.lock.Unlock, blocking=False)
910 a87b4824 Michael Hanselmann
911 a87b4824 Michael Hanselmann
912 739be818 Michael Hanselmann
class TestTimeFunctions(unittest.TestCase):
913 739be818 Michael Hanselmann
  """Test case for time functions"""
914 739be818 Michael Hanselmann
915 739be818 Michael Hanselmann
  def runTest(self):
916 739be818 Michael Hanselmann
    self.assertEqual(utils.SplitTime(1), (1, 0))
917 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(1.5), (1, 500000))
918 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(1218448917.4809151), (1218448917, 480915))
919 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.48012), (123, 480120))
920 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.9996), (123, 999600))
921 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.9995), (123, 999500))
922 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.9994), (123, 999400))
923 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.999999999), (123, 999999))
924 45bc5e4a Michael Hanselmann
925 45bc5e4a Michael Hanselmann
    self.assertRaises(AssertionError, utils.SplitTime, -1)
926 739be818 Michael Hanselmann
927 739be818 Michael Hanselmann
    self.assertEqual(utils.MergeTime((1, 0)), 1.0)
928 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.MergeTime((1, 500000)), 1.5)
929 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.MergeTime((1218448917, 500000)), 1218448917.5)
930 739be818 Michael Hanselmann
931 4d4a651d Michael Hanselmann
    self.assertEqual(round(utils.MergeTime((1218448917, 481000)), 3),
932 4d4a651d Michael Hanselmann
                     1218448917.481)
933 45bc5e4a Michael Hanselmann
    self.assertEqual(round(utils.MergeTime((1, 801000)), 3), 1.801)
934 739be818 Michael Hanselmann
935 739be818 Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (0, -1))
936 45bc5e4a Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (0, 1000000))
937 45bc5e4a Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (0, 9999999))
938 739be818 Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (-1, 0))
939 739be818 Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (-9999, 0))
940 739be818 Michael Hanselmann
941 739be818 Michael Hanselmann
942 a2d2e1a7 Iustin Pop
class FieldSetTestCase(unittest.TestCase):
943 a2d2e1a7 Iustin Pop
  """Test case for FieldSets"""
944 a2d2e1a7 Iustin Pop
945 a2d2e1a7 Iustin Pop
  def testSimpleMatch(self):
946 a2d2e1a7 Iustin Pop
    f = utils.FieldSet("a", "b", "c", "def")
947 a2d2e1a7 Iustin Pop
    self.failUnless(f.Matches("a"))
948 a2d2e1a7 Iustin Pop
    self.failIf(f.Matches("d"), "Substring matched")
949 a2d2e1a7 Iustin Pop
    self.failIf(f.Matches("defghi"), "Prefix string matched")
950 a2d2e1a7 Iustin Pop
    self.failIf(f.NonMatching(["b", "c"]))
951 a2d2e1a7 Iustin Pop
    self.failIf(f.NonMatching(["a", "b", "c", "def"]))
952 a2d2e1a7 Iustin Pop
    self.failUnless(f.NonMatching(["a", "d"]))
953 a2d2e1a7 Iustin Pop
954 a2d2e1a7 Iustin Pop
  def testRegexMatch(self):
955 a2d2e1a7 Iustin Pop
    f = utils.FieldSet("a", "b([0-9]+)", "c")
956 a2d2e1a7 Iustin Pop
    self.failUnless(f.Matches("b1"))
957 a2d2e1a7 Iustin Pop
    self.failUnless(f.Matches("b99"))
958 a2d2e1a7 Iustin Pop
    self.failIf(f.Matches("b/1"))
959 a2d2e1a7 Iustin Pop
    self.failIf(f.NonMatching(["b12", "c"]))
960 a2d2e1a7 Iustin Pop
    self.failUnless(f.NonMatching(["a", "1"]))
961 a2d2e1a7 Iustin Pop
962 a5728081 Guido Trotter
class TestForceDictType(unittest.TestCase):
963 a5728081 Guido Trotter
  """Test case for ForceDictType"""
964 a5728081 Guido Trotter
965 a5728081 Guido Trotter
  def setUp(self):
966 a5728081 Guido Trotter
    self.key_types = {
967 a5728081 Guido Trotter
      'a': constants.VTYPE_INT,
968 a5728081 Guido Trotter
      'b': constants.VTYPE_BOOL,
969 a5728081 Guido Trotter
      'c': constants.VTYPE_STRING,
970 a5728081 Guido Trotter
      'd': constants.VTYPE_SIZE,
971 a5728081 Guido Trotter
      }
972 a5728081 Guido Trotter
973 a5728081 Guido Trotter
  def _fdt(self, dict, allowed_values=None):
974 a5728081 Guido Trotter
    if allowed_values is None:
975 a5728081 Guido Trotter
      ForceDictType(dict, self.key_types)
976 a5728081 Guido Trotter
    else:
977 a5728081 Guido Trotter
      ForceDictType(dict, self.key_types, allowed_values=allowed_values)
978 a5728081 Guido Trotter
979 a5728081 Guido Trotter
    return dict
980 a5728081 Guido Trotter
981 a5728081 Guido Trotter
  def testSimpleDict(self):
982 a5728081 Guido Trotter
    self.assertEqual(self._fdt({}), {})
983 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'a': 1}), {'a': 1})
984 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'a': '1'}), {'a': 1})
985 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'a': 1, 'b': 1}), {'a':1, 'b': True})
986 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 1, 'c': 'foo'}), {'b': True, 'c': 'foo'})
987 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 1, 'c': False}), {'b': True, 'c': ''})
988 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 'false'}), {'b': False})
989 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 'False'}), {'b': False})
990 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 'true'}), {'b': True})
991 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 'True'}), {'b': True})
992 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'d': '4'}), {'d': 4})
993 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'d': '4M'}), {'d': 4})
994 a5728081 Guido Trotter
995 a5728081 Guido Trotter
  def testErrors(self):
996 a5728081 Guido Trotter
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {'a': 'astring'})
997 a5728081 Guido Trotter
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {'c': True})
998 a5728081 Guido Trotter
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {'d': 'astring'})
999 a5728081 Guido Trotter
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {'d': '4 L'})
1000 a5728081 Guido Trotter
1001 a2d2e1a7 Iustin Pop
1002 da961187 Guido Trotter
class TestIsAbsNormPath(unittest.TestCase):
1003 da961187 Guido Trotter
  """Testing case for IsProcessAlive"""
1004 da961187 Guido Trotter
1005 da961187 Guido Trotter
  def _pathTestHelper(self, path, result):
1006 da961187 Guido Trotter
    if result:
1007 da961187 Guido Trotter
      self.assert_(IsNormAbsPath(path),
1008 17c61836 Guido Trotter
          "Path %s should result absolute and normalized" % path)
1009 da961187 Guido Trotter
    else:
1010 da961187 Guido Trotter
      self.assert_(not IsNormAbsPath(path),
1011 17c61836 Guido Trotter
          "Path %s should not result absolute and normalized" % path)
1012 da961187 Guido Trotter
1013 da961187 Guido Trotter
  def testBase(self):
1014 da961187 Guido Trotter
    self._pathTestHelper('/etc', True)
1015 da961187 Guido Trotter
    self._pathTestHelper('/srv', True)
1016 da961187 Guido Trotter
    self._pathTestHelper('etc', False)
1017 da961187 Guido Trotter
    self._pathTestHelper('/etc/../root', False)
1018 da961187 Guido Trotter
    self._pathTestHelper('/etc/', False)
1019 da961187 Guido Trotter
1020 af0413bb Guido Trotter
1021 d392fa34 Iustin Pop
class TestSafeEncode(unittest.TestCase):
1022 d392fa34 Iustin Pop
  """Test case for SafeEncode"""
1023 d392fa34 Iustin Pop
1024 d392fa34 Iustin Pop
  def testAscii(self):
1025 d392fa34 Iustin Pop
    for txt in [string.digits, string.letters, string.punctuation]:
1026 d392fa34 Iustin Pop
      self.failUnlessEqual(txt, SafeEncode(txt))
1027 d392fa34 Iustin Pop
1028 d392fa34 Iustin Pop
  def testDoubleEncode(self):
1029 d392fa34 Iustin Pop
    for i in range(255):
1030 d392fa34 Iustin Pop
      txt = SafeEncode(chr(i))
1031 d392fa34 Iustin Pop
      self.failUnlessEqual(txt, SafeEncode(txt))
1032 d392fa34 Iustin Pop
1033 d392fa34 Iustin Pop
  def testUnicode(self):
1034 d392fa34 Iustin Pop
    # 1024 is high enough to catch non-direct ASCII mappings
1035 d392fa34 Iustin Pop
    for i in range(1024):
1036 d392fa34 Iustin Pop
      txt = SafeEncode(unichr(i))
1037 d392fa34 Iustin Pop
      self.failUnlessEqual(txt, SafeEncode(txt))
1038 d392fa34 Iustin Pop
1039 d392fa34 Iustin Pop
1040 3b813dd2 Iustin Pop
class TestFormatTime(unittest.TestCase):
1041 3b813dd2 Iustin Pop
  """Testing case for FormatTime"""
1042 3b813dd2 Iustin Pop
1043 3b813dd2 Iustin Pop
  def testNone(self):
1044 3b813dd2 Iustin Pop
    self.failUnlessEqual(FormatTime(None), "N/A")
1045 3b813dd2 Iustin Pop
1046 3b813dd2 Iustin Pop
  def testInvalid(self):
1047 3b813dd2 Iustin Pop
    self.failUnlessEqual(FormatTime(()), "N/A")
1048 3b813dd2 Iustin Pop
1049 3b813dd2 Iustin Pop
  def testNow(self):
1050 3b813dd2 Iustin Pop
    # tests that we accept time.time input
1051 3b813dd2 Iustin Pop
    FormatTime(time.time())
1052 3b813dd2 Iustin Pop
    # tests that we accept int input
1053 3b813dd2 Iustin Pop
    FormatTime(int(time.time()))
1054 3b813dd2 Iustin Pop
1055 3b813dd2 Iustin Pop
1056 a8083063 Iustin Pop
if __name__ == '__main__':
1057 25231ec5 Michael Hanselmann
  testutils.GanetiTestProgram()