Statistics
| Branch: | Tag: | Revision:

root / test / ganeti.utils_unittest.py @ 936f3c59

History | View | Annotate | Download (35 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 6e797216 Michael Hanselmann
299 6e797216 Michael Hanselmann
  def testSimpleRename2(self):
300 6e797216 Michael Hanselmann
    """Simple rename 2"""
301 6e797216 Michael Hanselmann
    utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "xyz"),
302 6e797216 Michael Hanselmann
                     mkdir=True)
303 6e797216 Michael Hanselmann
304 6e797216 Michael Hanselmann
  def testRenameMkdir(self):
305 6e797216 Michael Hanselmann
    """Rename with mkdir"""
306 6e797216 Michael Hanselmann
    utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "test/xyz"),
307 6e797216 Michael Hanselmann
                     mkdir=True)
308 6e797216 Michael Hanselmann
309 6e797216 Michael Hanselmann
310 a8083063 Iustin Pop
class TestMatchNameComponent(unittest.TestCase):
311 a8083063 Iustin Pop
  """Test case for the MatchNameComponent function"""
312 a8083063 Iustin Pop
313 a8083063 Iustin Pop
  def testEmptyList(self):
314 a8083063 Iustin Pop
    """Test that there is no match against an empty list"""
315 a8083063 Iustin Pop
316 a8083063 Iustin Pop
    self.failUnlessEqual(MatchNameComponent("", []), None)
317 a8083063 Iustin Pop
    self.failUnlessEqual(MatchNameComponent("test", []), None)
318 a8083063 Iustin Pop
319 a8083063 Iustin Pop
  def testSingleMatch(self):
320 a8083063 Iustin Pop
    """Test that a single match is performed correctly"""
321 a8083063 Iustin Pop
    mlist = ["test1.example.com", "test2.example.com", "test3.example.com"]
322 a8083063 Iustin Pop
    for key in "test2", "test2.example", "test2.example.com":
323 a8083063 Iustin Pop
      self.failUnlessEqual(MatchNameComponent(key, mlist), mlist[1])
324 a8083063 Iustin Pop
325 a8083063 Iustin Pop
  def testMultipleMatches(self):
326 a8083063 Iustin Pop
    """Test that a multiple match is returned as None"""
327 a8083063 Iustin Pop
    mlist = ["test1.example.com", "test1.example.org", "test1.example.net"]
328 a8083063 Iustin Pop
    for key in "test1", "test1.example":
329 a8083063 Iustin Pop
      self.failUnlessEqual(MatchNameComponent(key, mlist), None)
330 a8083063 Iustin Pop
331 3a541d90 Iustin Pop
  def testFullMatch(self):
332 3a541d90 Iustin Pop
    """Test that a full match is returned correctly"""
333 3a541d90 Iustin Pop
    key1 = "test1"
334 3a541d90 Iustin Pop
    key2 = "test1.example"
335 3a541d90 Iustin Pop
    mlist = [key2, key2 + ".com"]
336 3a541d90 Iustin Pop
    self.failUnlessEqual(MatchNameComponent(key1, mlist), None)
337 3a541d90 Iustin Pop
    self.failUnlessEqual(MatchNameComponent(key2, mlist), key2)
338 3a541d90 Iustin Pop
339 256eb94b Guido Trotter
  def testCaseInsensitivePartialMatch(self):
340 256eb94b Guido Trotter
    """Test for the case_insensitive keyword"""
341 256eb94b Guido Trotter
    mlist = ["test1.example.com", "test2.example.net"]
342 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("test2", mlist, case_sensitive=False),
343 256eb94b Guido Trotter
                     "test2.example.net")
344 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("Test2", mlist, case_sensitive=False),
345 256eb94b Guido Trotter
                     "test2.example.net")
346 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("teSt2", mlist, case_sensitive=False),
347 256eb94b Guido Trotter
                     "test2.example.net")
348 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("TeSt2", mlist, case_sensitive=False),
349 256eb94b Guido Trotter
                     "test2.example.net")
350 256eb94b Guido Trotter
351 256eb94b Guido Trotter
352 256eb94b Guido Trotter
  def testCaseInsensitiveFullMatch(self):
353 256eb94b Guido Trotter
    mlist = ["ts1.ex", "ts1.ex.org", "ts2.ex", "Ts2.ex"]
354 256eb94b Guido Trotter
    # Between the two ts1 a full string match non-case insensitive should work
355 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("Ts1", mlist, case_sensitive=False),
356 256eb94b Guido Trotter
                     None)
357 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("Ts1.ex", mlist, case_sensitive=False),
358 256eb94b Guido Trotter
                     "ts1.ex")
359 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("ts1.ex", mlist, case_sensitive=False),
360 256eb94b Guido Trotter
                     "ts1.ex")
361 256eb94b Guido Trotter
    # Between the two ts2 only case differs, so only case-match works
362 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("ts2.ex", mlist, case_sensitive=False),
363 256eb94b Guido Trotter
                     "ts2.ex")
364 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("Ts2.ex", mlist, case_sensitive=False),
365 256eb94b Guido Trotter
                     "Ts2.ex")
366 256eb94b Guido Trotter
    self.assertEqual(MatchNameComponent("TS2.ex", mlist, case_sensitive=False),
367 256eb94b Guido Trotter
                     None)
368 256eb94b Guido Trotter
369 a8083063 Iustin Pop
370 a8083063 Iustin Pop
class TestFormatUnit(unittest.TestCase):
371 a8083063 Iustin Pop
  """Test case for the FormatUnit function"""
372 a8083063 Iustin Pop
373 a8083063 Iustin Pop
  def testMiB(self):
374 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1, 'h'), '1M')
375 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(100, 'h'), '100M')
376 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1023, 'h'), '1023M')
377 9fbfbb7b Iustin Pop
378 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1, 'm'), '1')
379 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(100, 'm'), '100')
380 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1023, 'm'), '1023')
381 9fbfbb7b Iustin Pop
382 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024, 'm'), '1024')
383 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1536, 'm'), '1536')
384 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(17133, 'm'), '17133')
385 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024 - 1, 'm'), '1048575')
386 a8083063 Iustin Pop
387 a8083063 Iustin Pop
  def testGiB(self):
388 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024, 'h'), '1.0G')
389 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1536, 'h'), '1.5G')
390 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(17133, 'h'), '16.7G')
391 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024 - 1, 'h'), '1024.0G')
392 9fbfbb7b Iustin Pop
393 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024, 'g'), '1.0')
394 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1536, 'g'), '1.5')
395 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(17133, 'g'), '16.7')
396 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024 - 1, 'g'), '1024.0')
397 9fbfbb7b Iustin Pop
398 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024, 'g'), '1024.0')
399 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(5120 * 1024, 'g'), '5120.0')
400 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(29829 * 1024, 'g'), '29829.0')
401 a8083063 Iustin Pop
402 a8083063 Iustin Pop
  def testTiB(self):
403 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024, 'h'), '1.0T')
404 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(5120 * 1024, 'h'), '5.0T')
405 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(29829 * 1024, 'h'), '29.1T')
406 a8083063 Iustin Pop
407 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024, 't'), '1.0')
408 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(5120 * 1024, 't'), '5.0')
409 9fbfbb7b Iustin Pop
    self.assertEqual(FormatUnit(29829 * 1024, 't'), '29.1')
410 a8083063 Iustin Pop
411 a8083063 Iustin Pop
class TestParseUnit(unittest.TestCase):
412 a8083063 Iustin Pop
  """Test case for the ParseUnit function"""
413 a8083063 Iustin Pop
414 a8083063 Iustin Pop
  SCALES = (('', 1),
415 a8083063 Iustin Pop
            ('M', 1), ('G', 1024), ('T', 1024 * 1024),
416 a8083063 Iustin Pop
            ('MB', 1), ('GB', 1024), ('TB', 1024 * 1024),
417 a8083063 Iustin Pop
            ('MiB', 1), ('GiB', 1024), ('TiB', 1024 * 1024))
418 a8083063 Iustin Pop
419 a8083063 Iustin Pop
  def testRounding(self):
420 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('0'), 0)
421 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1'), 4)
422 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('2'), 4)
423 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('3'), 4)
424 a8083063 Iustin Pop
425 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('124'), 124)
426 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('125'), 128)
427 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('126'), 128)
428 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('127'), 128)
429 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('128'), 128)
430 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('129'), 132)
431 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('130'), 132)
432 a8083063 Iustin Pop
433 a8083063 Iustin Pop
  def testFloating(self):
434 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('0'), 0)
435 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('0.5'), 4)
436 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.75'), 4)
437 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.99'), 4)
438 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('2.00'), 4)
439 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('2.01'), 4)
440 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('3.99'), 4)
441 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('4.00'), 4)
442 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('4.01'), 8)
443 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.5G'), 1536)
444 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.8G'), 1844)
445 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('8.28T'), 8682212)
446 a8083063 Iustin Pop
447 a8083063 Iustin Pop
  def testSuffixes(self):
448 a8083063 Iustin Pop
    for sep in ('', ' ', '   ', "\t", "\t "):
449 a8083063 Iustin Pop
      for suffix, scale in TestParseUnit.SCALES:
450 a8083063 Iustin Pop
        for func in (lambda x: x, str.lower, str.upper):
451 667479d5 Michael Hanselmann
          self.assertEqual(ParseUnit('1024' + sep + func(suffix)),
452 667479d5 Michael Hanselmann
                           1024 * scale)
453 a8083063 Iustin Pop
454 a8083063 Iustin Pop
  def testInvalidInput(self):
455 a8083063 Iustin Pop
    for sep in ('-', '_', ',', 'a'):
456 a8083063 Iustin Pop
      for suffix, _ in TestParseUnit.SCALES:
457 a8083063 Iustin Pop
        self.assertRaises(UnitParseError, ParseUnit, '1' + sep + suffix)
458 a8083063 Iustin Pop
459 a8083063 Iustin Pop
    for suffix, _ in TestParseUnit.SCALES:
460 a8083063 Iustin Pop
      self.assertRaises(UnitParseError, ParseUnit, '1,3' + suffix)
461 a8083063 Iustin Pop
462 a8083063 Iustin Pop
463 c9c4f19e Michael Hanselmann
class TestSshKeys(testutils.GanetiTestCase):
464 a8083063 Iustin Pop
  """Test case for the AddAuthorizedKey function"""
465 a8083063 Iustin Pop
466 a8083063 Iustin Pop
  KEY_A = 'ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a'
467 a8083063 Iustin Pop
  KEY_B = ('command="/usr/bin/fooserver -t --verbose",from="1.2.3.4" '
468 a8083063 Iustin Pop
           'ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b')
469 a8083063 Iustin Pop
470 ebe8ef17 Michael Hanselmann
  def setUp(self):
471 51596eb2 Iustin Pop
    testutils.GanetiTestCase.setUp(self)
472 51596eb2 Iustin Pop
    self.tmpname = self._CreateTempFile()
473 51596eb2 Iustin Pop
    handle = open(self.tmpname, 'w')
474 a8083063 Iustin Pop
    try:
475 51596eb2 Iustin Pop
      handle.write("%s\n" % TestSshKeys.KEY_A)
476 51596eb2 Iustin Pop
      handle.write("%s\n" % TestSshKeys.KEY_B)
477 51596eb2 Iustin Pop
    finally:
478 51596eb2 Iustin Pop
      handle.close()
479 a8083063 Iustin Pop
480 a8083063 Iustin Pop
  def testAddingNewKey(self):
481 ebe8ef17 Michael Hanselmann
    AddAuthorizedKey(self.tmpname, 'ssh-dss AAAAB3NzaC1kc3MAAACB root@test')
482 a8083063 Iustin Pop
483 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
484 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
485 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
486 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n"
487 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1kc3MAAACB root@test\n")
488 a8083063 Iustin Pop
489 f89f17a8 Michael Hanselmann
  def testAddingAlmostButNotCompletelyTheSameKey(self):
490 ebe8ef17 Michael Hanselmann
    AddAuthorizedKey(self.tmpname,
491 ebe8ef17 Michael Hanselmann
        'ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@test')
492 ebe8ef17 Michael Hanselmann
493 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
494 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
495 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
496 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n"
497 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@test\n")
498 a8083063 Iustin Pop
499 a8083063 Iustin Pop
  def testAddingExistingKeyWithSomeMoreSpaces(self):
500 ebe8ef17 Michael Hanselmann
    AddAuthorizedKey(self.tmpname,
501 ebe8ef17 Michael Hanselmann
        'ssh-dss  AAAAB3NzaC1w5256closdj32mZaQU   root@key-a')
502 a8083063 Iustin Pop
503 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
504 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
505 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
506 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
507 a8083063 Iustin Pop
508 a8083063 Iustin Pop
  def testRemovingExistingKeyWithSomeMoreSpaces(self):
509 ebe8ef17 Michael Hanselmann
    RemoveAuthorizedKey(self.tmpname,
510 ebe8ef17 Michael Hanselmann
        'ssh-dss  AAAAB3NzaC1w5256closdj32mZaQU   root@key-a')
511 a8083063 Iustin Pop
512 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
513 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
514 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
515 a8083063 Iustin Pop
516 a8083063 Iustin Pop
  def testRemovingNonExistingKey(self):
517 ebe8ef17 Michael Hanselmann
    RemoveAuthorizedKey(self.tmpname,
518 ebe8ef17 Michael Hanselmann
        'ssh-dss  AAAAB3Nsdfj230xxjxJjsjwjsjdjU   root@test')
519 a8083063 Iustin Pop
520 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
521 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
522 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
523 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
524 a8083063 Iustin Pop
525 a8083063 Iustin Pop
526 c9c4f19e Michael Hanselmann
class TestEtcHosts(testutils.GanetiTestCase):
527 899d2a81 Michael Hanselmann
  """Test functions modifying /etc/hosts"""
528 899d2a81 Michael Hanselmann
529 ebe8ef17 Michael Hanselmann
  def setUp(self):
530 51596eb2 Iustin Pop
    testutils.GanetiTestCase.setUp(self)
531 51596eb2 Iustin Pop
    self.tmpname = self._CreateTempFile()
532 51596eb2 Iustin Pop
    handle = open(self.tmpname, 'w')
533 899d2a81 Michael Hanselmann
    try:
534 51596eb2 Iustin Pop
      handle.write('# This is a test file for /etc/hosts\n')
535 51596eb2 Iustin Pop
      handle.write('127.0.0.1\tlocalhost\n')
536 51596eb2 Iustin Pop
      handle.write('192.168.1.1 router gw\n')
537 51596eb2 Iustin Pop
    finally:
538 51596eb2 Iustin Pop
      handle.close()
539 899d2a81 Michael Hanselmann
540 9440aeab Michael Hanselmann
  def testSettingNewIp(self):
541 ebe8ef17 Michael Hanselmann
    SetEtcHostsEntry(self.tmpname, '1.2.3.4', 'myhost.domain.tld', ['myhost'])
542 899d2a81 Michael Hanselmann
543 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
544 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
545 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
546 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router gw\n"
547 ebe8ef17 Michael Hanselmann
      "1.2.3.4\tmyhost.domain.tld myhost\n")
548 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
549 899d2a81 Michael Hanselmann
550 9440aeab Michael Hanselmann
  def testSettingExistingIp(self):
551 ebe8ef17 Michael Hanselmann
    SetEtcHostsEntry(self.tmpname, '192.168.1.1', 'myhost.domain.tld',
552 ebe8ef17 Michael Hanselmann
                     ['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\tmyhost.domain.tld myhost\n")
558 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
559 899d2a81 Michael Hanselmann
560 7fbb1f65 Michael Hanselmann
  def testSettingDuplicateName(self):
561 7fbb1f65 Michael Hanselmann
    SetEtcHostsEntry(self.tmpname, '1.2.3.4', 'myhost', ['myhost'])
562 7fbb1f65 Michael Hanselmann
563 7fbb1f65 Michael Hanselmann
    self.assertFileContent(self.tmpname,
564 7fbb1f65 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
565 7fbb1f65 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
566 7fbb1f65 Michael Hanselmann
      "192.168.1.1 router gw\n"
567 7fbb1f65 Michael Hanselmann
      "1.2.3.4\tmyhost\n")
568 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
569 7fbb1f65 Michael Hanselmann
570 899d2a81 Michael Hanselmann
  def testRemovingExistingHost(self):
571 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'router')
572 899d2a81 Michael Hanselmann
573 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
574 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
575 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
576 ebe8ef17 Michael Hanselmann
      "192.168.1.1 gw\n")
577 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
578 899d2a81 Michael Hanselmann
579 899d2a81 Michael Hanselmann
  def testRemovingSingleExistingHost(self):
580 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'localhost')
581 899d2a81 Michael Hanselmann
582 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
583 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
584 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router gw\n")
585 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
586 899d2a81 Michael Hanselmann
587 899d2a81 Michael Hanselmann
  def testRemovingNonExistingHost(self):
588 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'myhost')
589 899d2a81 Michael Hanselmann
590 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
591 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
592 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
593 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router gw\n")
594 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
595 899d2a81 Michael Hanselmann
596 9440aeab Michael Hanselmann
  def testRemovingAlias(self):
597 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'gw')
598 9440aeab Michael Hanselmann
599 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
600 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
601 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
602 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router\n")
603 9b977740 Guido Trotter
    self.assertFileMode(self.tmpname, 0644)
604 9440aeab Michael Hanselmann
605 899d2a81 Michael Hanselmann
606 a8083063 Iustin Pop
class TestShellQuoting(unittest.TestCase):
607 a8083063 Iustin Pop
  """Test case for shell quoting functions"""
608 a8083063 Iustin Pop
609 a8083063 Iustin Pop
  def testShellQuote(self):
610 a8083063 Iustin Pop
    self.assertEqual(ShellQuote('abc'), "abc")
611 a8083063 Iustin Pop
    self.assertEqual(ShellQuote('ab"c'), "'ab\"c'")
612 a8083063 Iustin Pop
    self.assertEqual(ShellQuote("a'bc"), "'a'\\''bc'")
613 a8083063 Iustin Pop
    self.assertEqual(ShellQuote("a b c"), "'a b c'")
614 a8083063 Iustin Pop
    self.assertEqual(ShellQuote("a b\\ c"), "'a b\\ c'")
615 a8083063 Iustin Pop
616 a8083063 Iustin Pop
  def testShellQuoteArgs(self):
617 a8083063 Iustin Pop
    self.assertEqual(ShellQuoteArgs(['a', 'b', 'c']), "a b c")
618 a8083063 Iustin Pop
    self.assertEqual(ShellQuoteArgs(['a', 'b"', 'c']), "a 'b\"' c")
619 a8083063 Iustin Pop
    self.assertEqual(ShellQuoteArgs(['a', 'b\'', 'c']), "a 'b'\\\''' c")
620 a8083063 Iustin Pop
621 a8083063 Iustin Pop
622 2c30e9d7 Alexander Schreiber
class TestTcpPing(unittest.TestCase):
623 2c30e9d7 Alexander Schreiber
  """Testcase for TCP version of ping - against listen(2)ing port"""
624 2c30e9d7 Alexander Schreiber
625 2c30e9d7 Alexander Schreiber
  def setUp(self):
626 2c30e9d7 Alexander Schreiber
    self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
627 16abfbc2 Alexander Schreiber
    self.listener.bind((constants.LOCALHOST_IP_ADDRESS, 0))
628 2c30e9d7 Alexander Schreiber
    self.listenerport = self.listener.getsockname()[1]
629 2c30e9d7 Alexander Schreiber
    self.listener.listen(1)
630 2c30e9d7 Alexander Schreiber
631 2c30e9d7 Alexander Schreiber
  def tearDown(self):
632 2c30e9d7 Alexander Schreiber
    self.listener.shutdown(socket.SHUT_RDWR)
633 2c30e9d7 Alexander Schreiber
    del self.listener
634 2c30e9d7 Alexander Schreiber
    del self.listenerport
635 2c30e9d7 Alexander Schreiber
636 2c30e9d7 Alexander Schreiber
  def testTcpPingToLocalHostAccept(self):
637 16abfbc2 Alexander Schreiber
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
638 2c30e9d7 Alexander Schreiber
                         self.listenerport,
639 2c30e9d7 Alexander Schreiber
                         timeout=10,
640 b15d625f Iustin Pop
                         live_port_needed=True,
641 b15d625f Iustin Pop
                         source=constants.LOCALHOST_IP_ADDRESS,
642 b15d625f Iustin Pop
                         ),
643 2c30e9d7 Alexander Schreiber
                 "failed to connect to test listener")
644 2c30e9d7 Alexander Schreiber
645 b15d625f Iustin Pop
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
646 b15d625f Iustin Pop
                         self.listenerport,
647 b15d625f Iustin Pop
                         timeout=10,
648 b15d625f Iustin Pop
                         live_port_needed=True,
649 b15d625f Iustin Pop
                         ),
650 b15d625f Iustin Pop
                 "failed to connect to test listener (no source)")
651 b15d625f Iustin Pop
652 2c30e9d7 Alexander Schreiber
653 2c30e9d7 Alexander Schreiber
class TestTcpPingDeaf(unittest.TestCase):
654 2c30e9d7 Alexander Schreiber
  """Testcase for TCP version of ping - against non listen(2)ing port"""
655 2c30e9d7 Alexander Schreiber
656 2c30e9d7 Alexander Schreiber
  def setUp(self):
657 2c30e9d7 Alexander Schreiber
    self.deaflistener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
658 16abfbc2 Alexander Schreiber
    self.deaflistener.bind((constants.LOCALHOST_IP_ADDRESS, 0))
659 2c30e9d7 Alexander Schreiber
    self.deaflistenerport = self.deaflistener.getsockname()[1]
660 2c30e9d7 Alexander Schreiber
661 2c30e9d7 Alexander Schreiber
  def tearDown(self):
662 2c30e9d7 Alexander Schreiber
    del self.deaflistener
663 2c30e9d7 Alexander Schreiber
    del self.deaflistenerport
664 2c30e9d7 Alexander Schreiber
665 2c30e9d7 Alexander Schreiber
  def testTcpPingToLocalHostAcceptDeaf(self):
666 16abfbc2 Alexander Schreiber
    self.failIf(TcpPing(constants.LOCALHOST_IP_ADDRESS,
667 2c30e9d7 Alexander Schreiber
                        self.deaflistenerport,
668 16abfbc2 Alexander Schreiber
                        timeout=constants.TCP_PING_TIMEOUT,
669 b15d625f Iustin Pop
                        live_port_needed=True,
670 b15d625f Iustin Pop
                        source=constants.LOCALHOST_IP_ADDRESS,
671 b15d625f Iustin Pop
                        ), # need successful connect(2)
672 2c30e9d7 Alexander Schreiber
                "successfully connected to deaf listener")
673 2c30e9d7 Alexander Schreiber
674 b15d625f Iustin Pop
    self.failIf(TcpPing(constants.LOCALHOST_IP_ADDRESS,
675 b15d625f Iustin Pop
                        self.deaflistenerport,
676 b15d625f Iustin Pop
                        timeout=constants.TCP_PING_TIMEOUT,
677 b15d625f Iustin Pop
                        live_port_needed=True,
678 b15d625f Iustin Pop
                        ), # need successful connect(2)
679 b15d625f Iustin Pop
                "successfully connected to deaf listener (no source addr)")
680 b15d625f Iustin Pop
681 2c30e9d7 Alexander Schreiber
  def testTcpPingToLocalHostNoAccept(self):
682 16abfbc2 Alexander Schreiber
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
683 2c30e9d7 Alexander Schreiber
                         self.deaflistenerport,
684 16abfbc2 Alexander Schreiber
                         timeout=constants.TCP_PING_TIMEOUT,
685 b15d625f Iustin Pop
                         live_port_needed=False,
686 b15d625f Iustin Pop
                         source=constants.LOCALHOST_IP_ADDRESS,
687 b15d625f Iustin Pop
                         ), # ECONNREFUSED is OK
688 2c30e9d7 Alexander Schreiber
                 "failed to ping alive host on deaf port")
689 2c30e9d7 Alexander Schreiber
690 b15d625f Iustin Pop
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
691 b15d625f Iustin Pop
                         self.deaflistenerport,
692 b15d625f Iustin Pop
                         timeout=constants.TCP_PING_TIMEOUT,
693 b15d625f Iustin Pop
                         live_port_needed=False,
694 b15d625f Iustin Pop
                         ), # ECONNREFUSED is OK
695 b15d625f Iustin Pop
                 "failed to ping alive host on deaf port (no source addr)")
696 b15d625f Iustin Pop
697 2c30e9d7 Alexander Schreiber
698 caad16e2 Iustin Pop
class TestOwnIpAddress(unittest.TestCase):
699 caad16e2 Iustin Pop
  """Testcase for OwnIpAddress"""
700 caad16e2 Iustin Pop
701 caad16e2 Iustin Pop
  def testOwnLoopback(self):
702 caad16e2 Iustin Pop
    """check having the loopback ip"""
703 caad16e2 Iustin Pop
    self.failUnless(OwnIpAddress(constants.LOCALHOST_IP_ADDRESS),
704 caad16e2 Iustin Pop
                    "Should own the loopback address")
705 caad16e2 Iustin Pop
706 caad16e2 Iustin Pop
  def testNowOwnAddress(self):
707 caad16e2 Iustin Pop
    """check that I don't own an address"""
708 caad16e2 Iustin Pop
709 caad16e2 Iustin Pop
    # network 192.0.2.0/24 is reserved for test/documentation as per
710 caad16e2 Iustin Pop
    # rfc 3330, so we *should* not have an address of this range... if
711 caad16e2 Iustin Pop
    # this fails, we should extend the test to multiple addresses
712 caad16e2 Iustin Pop
    DST_IP = "192.0.2.1"
713 caad16e2 Iustin Pop
    self.failIf(OwnIpAddress(DST_IP), "Should not own IP address %s" % DST_IP)
714 caad16e2 Iustin Pop
715 caad16e2 Iustin Pop
716 eedbda4b Michael Hanselmann
class TestListVisibleFiles(unittest.TestCase):
717 eedbda4b Michael Hanselmann
  """Test case for ListVisibleFiles"""
718 eedbda4b Michael Hanselmann
719 eedbda4b Michael Hanselmann
  def setUp(self):
720 eedbda4b Michael Hanselmann
    self.path = tempfile.mkdtemp()
721 eedbda4b Michael Hanselmann
722 eedbda4b Michael Hanselmann
  def tearDown(self):
723 eedbda4b Michael Hanselmann
    shutil.rmtree(self.path)
724 eedbda4b Michael Hanselmann
725 eedbda4b Michael Hanselmann
  def _test(self, files, expected):
726 eedbda4b Michael Hanselmann
    # Sort a copy
727 eedbda4b Michael Hanselmann
    expected = expected[:]
728 eedbda4b Michael Hanselmann
    expected.sort()
729 eedbda4b Michael Hanselmann
730 eedbda4b Michael Hanselmann
    for name in files:
731 eedbda4b Michael Hanselmann
      f = open(os.path.join(self.path, name), 'w')
732 eedbda4b Michael Hanselmann
      try:
733 eedbda4b Michael Hanselmann
        f.write("Test\n")
734 eedbda4b Michael Hanselmann
      finally:
735 eedbda4b Michael Hanselmann
        f.close()
736 eedbda4b Michael Hanselmann
737 eedbda4b Michael Hanselmann
    found = ListVisibleFiles(self.path)
738 eedbda4b Michael Hanselmann
    found.sort()
739 eedbda4b Michael Hanselmann
740 eedbda4b Michael Hanselmann
    self.assertEqual(found, expected)
741 eedbda4b Michael Hanselmann
742 eedbda4b Michael Hanselmann
  def testAllVisible(self):
743 eedbda4b Michael Hanselmann
    files = ["a", "b", "c"]
744 eedbda4b Michael Hanselmann
    expected = files
745 eedbda4b Michael Hanselmann
    self._test(files, expected)
746 eedbda4b Michael Hanselmann
747 eedbda4b Michael Hanselmann
  def testNoneVisible(self):
748 eedbda4b Michael Hanselmann
    files = [".a", ".b", ".c"]
749 eedbda4b Michael Hanselmann
    expected = []
750 eedbda4b Michael Hanselmann
    self._test(files, expected)
751 eedbda4b Michael Hanselmann
752 eedbda4b Michael Hanselmann
  def testSomeVisible(self):
753 eedbda4b Michael Hanselmann
    files = ["a", "b", ".c"]
754 eedbda4b Michael Hanselmann
    expected = ["a", "b"]
755 eedbda4b Michael Hanselmann
    self._test(files, expected)
756 eedbda4b Michael Hanselmann
757 eedbda4b Michael Hanselmann
758 24818e8f Michael Hanselmann
class TestNewUUID(unittest.TestCase):
759 24818e8f Michael Hanselmann
  """Test case for NewUUID"""
760 59072e7e Michael Hanselmann
761 59072e7e Michael Hanselmann
  _re_uuid = re.compile('^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-'
762 59072e7e Michael Hanselmann
                        '[a-f0-9]{4}-[a-f0-9]{12}$')
763 59072e7e Michael Hanselmann
764 59072e7e Michael Hanselmann
  def runTest(self):
765 24818e8f Michael Hanselmann
    self.failUnless(self._re_uuid.match(utils.NewUUID()))
766 59072e7e Michael Hanselmann
767 59072e7e Michael Hanselmann
768 f7414041 Michael Hanselmann
class TestUniqueSequence(unittest.TestCase):
769 f7414041 Michael Hanselmann
  """Test case for UniqueSequence"""
770 f7414041 Michael Hanselmann
771 f7414041 Michael Hanselmann
  def _test(self, input, expected):
772 f7414041 Michael Hanselmann
    self.assertEqual(utils.UniqueSequence(input), expected)
773 f7414041 Michael Hanselmann
774 f7414041 Michael Hanselmann
  def runTest(self):
775 f7414041 Michael Hanselmann
    # Ordered input
776 f7414041 Michael Hanselmann
    self._test([1, 2, 3], [1, 2, 3])
777 f7414041 Michael Hanselmann
    self._test([1, 1, 2, 2, 3, 3], [1, 2, 3])
778 f7414041 Michael Hanselmann
    self._test([1, 2, 2, 3], [1, 2, 3])
779 f7414041 Michael Hanselmann
    self._test([1, 2, 3, 3], [1, 2, 3])
780 f7414041 Michael Hanselmann
781 f7414041 Michael Hanselmann
    # Unordered input
782 f7414041 Michael Hanselmann
    self._test([1, 2, 3, 1, 2, 3], [1, 2, 3])
783 f7414041 Michael Hanselmann
    self._test([1, 1, 2, 3, 3, 1, 2], [1, 2, 3])
784 f7414041 Michael Hanselmann
785 f7414041 Michael Hanselmann
    # Strings
786 f7414041 Michael Hanselmann
    self._test(["a", "a"], ["a"])
787 f7414041 Michael Hanselmann
    self._test(["a", "b"], ["a", "b"])
788 f7414041 Michael Hanselmann
    self._test(["a", "b", "a"], ["a", "b"])
789 f7414041 Michael Hanselmann
790 a87b4824 Michael Hanselmann
791 7b4126b7 Iustin Pop
class TestFirstFree(unittest.TestCase):
792 7b4126b7 Iustin Pop
  """Test case for the FirstFree function"""
793 7b4126b7 Iustin Pop
794 7b4126b7 Iustin Pop
  def test(self):
795 7b4126b7 Iustin Pop
    """Test FirstFree"""
796 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([0, 1, 3]), 2)
797 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([]), None)
798 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([3, 4, 6]), 0)
799 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([3, 4, 6], base=3), 5)
800 7b4126b7 Iustin Pop
    self.failUnlessRaises(AssertionError, FirstFree, [0, 3, 4, 6], base=3)
801 f7414041 Michael Hanselmann
802 a87b4824 Michael Hanselmann
803 f65f63ef Iustin Pop
class TestTailFile(testutils.GanetiTestCase):
804 f65f63ef Iustin Pop
  """Test case for the TailFile function"""
805 f65f63ef Iustin Pop
806 f65f63ef Iustin Pop
  def testEmpty(self):
807 f65f63ef Iustin Pop
    fname = self._CreateTempFile()
808 f65f63ef Iustin Pop
    self.failUnlessEqual(TailFile(fname), [])
809 f65f63ef Iustin Pop
    self.failUnlessEqual(TailFile(fname, lines=25), [])
810 f65f63ef Iustin Pop
811 f65f63ef Iustin Pop
  def testAllLines(self):
812 f65f63ef Iustin Pop
    data = ["test %d" % i for i in range(30)]
813 f65f63ef Iustin Pop
    for i in range(30):
814 f65f63ef Iustin Pop
      fname = self._CreateTempFile()
815 f65f63ef Iustin Pop
      fd = open(fname, "w")
816 f65f63ef Iustin Pop
      fd.write("\n".join(data[:i]))
817 f65f63ef Iustin Pop
      if i > 0:
818 f65f63ef Iustin Pop
        fd.write("\n")
819 f65f63ef Iustin Pop
      fd.close()
820 f65f63ef Iustin Pop
      self.failUnlessEqual(TailFile(fname, lines=i), data[:i])
821 f65f63ef Iustin Pop
822 f65f63ef Iustin Pop
  def testPartialLines(self):
823 f65f63ef Iustin Pop
    data = ["test %d" % i for i in range(30)]
824 f65f63ef Iustin Pop
    fname = self._CreateTempFile()
825 f65f63ef Iustin Pop
    fd = open(fname, "w")
826 f65f63ef Iustin Pop
    fd.write("\n".join(data))
827 f65f63ef Iustin Pop
    fd.write("\n")
828 f65f63ef Iustin Pop
    fd.close()
829 f65f63ef Iustin Pop
    for i in range(1, 30):
830 f65f63ef Iustin Pop
      self.failUnlessEqual(TailFile(fname, lines=i), data[-i:])
831 f65f63ef Iustin Pop
832 f65f63ef Iustin Pop
  def testBigFile(self):
833 f65f63ef Iustin Pop
    data = ["test %d" % i for i in range(30)]
834 f65f63ef Iustin Pop
    fname = self._CreateTempFile()
835 f65f63ef Iustin Pop
    fd = open(fname, "w")
836 f65f63ef Iustin Pop
    fd.write("X" * 1048576)
837 f65f63ef Iustin Pop
    fd.write("\n")
838 f65f63ef Iustin Pop
    fd.write("\n".join(data))
839 f65f63ef Iustin Pop
    fd.write("\n")
840 f65f63ef Iustin Pop
    fd.close()
841 f65f63ef Iustin Pop
    for i in range(1, 30):
842 f65f63ef Iustin Pop
      self.failUnlessEqual(TailFile(fname, lines=i), data[-i:])
843 f65f63ef Iustin Pop
844 f65f63ef Iustin Pop
845 a87b4824 Michael Hanselmann
class TestFileLock(unittest.TestCase):
846 a87b4824 Michael Hanselmann
  """Test case for the FileLock class"""
847 a87b4824 Michael Hanselmann
848 a87b4824 Michael Hanselmann
  def setUp(self):
849 a87b4824 Michael Hanselmann
    self.tmpfile = tempfile.NamedTemporaryFile()
850 a87b4824 Michael Hanselmann
    self.lock = utils.FileLock(self.tmpfile.name)
851 a87b4824 Michael Hanselmann
852 a87b4824 Michael Hanselmann
  def testSharedNonblocking(self):
853 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=False)
854 a87b4824 Michael Hanselmann
    self.lock.Close()
855 a87b4824 Michael Hanselmann
856 a87b4824 Michael Hanselmann
  def testExclusiveNonblocking(self):
857 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=False)
858 a87b4824 Michael Hanselmann
    self.lock.Close()
859 a87b4824 Michael Hanselmann
860 a87b4824 Michael Hanselmann
  def testUnlockNonblocking(self):
861 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=False)
862 a87b4824 Michael Hanselmann
    self.lock.Close()
863 a87b4824 Michael Hanselmann
864 a87b4824 Michael Hanselmann
  def testSharedBlocking(self):
865 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=True)
866 a87b4824 Michael Hanselmann
    self.lock.Close()
867 a87b4824 Michael Hanselmann
868 a87b4824 Michael Hanselmann
  def testExclusiveBlocking(self):
869 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=True)
870 a87b4824 Michael Hanselmann
    self.lock.Close()
871 a87b4824 Michael Hanselmann
872 a87b4824 Michael Hanselmann
  def testUnlockBlocking(self):
873 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=True)
874 a87b4824 Michael Hanselmann
    self.lock.Close()
875 a87b4824 Michael Hanselmann
876 a87b4824 Michael Hanselmann
  def testSharedExclusiveUnlock(self):
877 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=False)
878 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=False)
879 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=False)
880 a87b4824 Michael Hanselmann
    self.lock.Close()
881 a87b4824 Michael Hanselmann
882 a87b4824 Michael Hanselmann
  def testExclusiveSharedUnlock(self):
883 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=False)
884 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=False)
885 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=False)
886 a87b4824 Michael Hanselmann
    self.lock.Close()
887 a87b4824 Michael Hanselmann
888 a87b4824 Michael Hanselmann
  def testCloseShared(self):
889 a87b4824 Michael Hanselmann
    self.lock.Close()
890 a87b4824 Michael Hanselmann
    self.assertRaises(AssertionError, self.lock.Shared, blocking=False)
891 a87b4824 Michael Hanselmann
892 a87b4824 Michael Hanselmann
  def testCloseExclusive(self):
893 a87b4824 Michael Hanselmann
    self.lock.Close()
894 a87b4824 Michael Hanselmann
    self.assertRaises(AssertionError, self.lock.Exclusive, blocking=False)
895 a87b4824 Michael Hanselmann
896 a87b4824 Michael Hanselmann
  def testCloseUnlock(self):
897 a87b4824 Michael Hanselmann
    self.lock.Close()
898 a87b4824 Michael Hanselmann
    self.assertRaises(AssertionError, self.lock.Unlock, blocking=False)
899 a87b4824 Michael Hanselmann
900 a87b4824 Michael Hanselmann
901 739be818 Michael Hanselmann
class TestTimeFunctions(unittest.TestCase):
902 739be818 Michael Hanselmann
  """Test case for time functions"""
903 739be818 Michael Hanselmann
904 739be818 Michael Hanselmann
  def runTest(self):
905 739be818 Michael Hanselmann
    self.assertEqual(utils.SplitTime(1), (1, 0))
906 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(1.5), (1, 500000))
907 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(1218448917.4809151), (1218448917, 480915))
908 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.48012), (123, 480120))
909 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.9996), (123, 999600))
910 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.9995), (123, 999500))
911 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.9994), (123, 999400))
912 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.999999999), (123, 999999))
913 45bc5e4a Michael Hanselmann
914 45bc5e4a Michael Hanselmann
    self.assertRaises(AssertionError, utils.SplitTime, -1)
915 739be818 Michael Hanselmann
916 739be818 Michael Hanselmann
    self.assertEqual(utils.MergeTime((1, 0)), 1.0)
917 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.MergeTime((1, 500000)), 1.5)
918 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.MergeTime((1218448917, 500000)), 1218448917.5)
919 739be818 Michael Hanselmann
920 4d4a651d Michael Hanselmann
    self.assertEqual(round(utils.MergeTime((1218448917, 481000)), 3),
921 4d4a651d Michael Hanselmann
                     1218448917.481)
922 45bc5e4a Michael Hanselmann
    self.assertEqual(round(utils.MergeTime((1, 801000)), 3), 1.801)
923 739be818 Michael Hanselmann
924 739be818 Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (0, -1))
925 45bc5e4a Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (0, 1000000))
926 45bc5e4a Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (0, 9999999))
927 739be818 Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (-1, 0))
928 739be818 Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (-9999, 0))
929 739be818 Michael Hanselmann
930 739be818 Michael Hanselmann
931 a2d2e1a7 Iustin Pop
class FieldSetTestCase(unittest.TestCase):
932 a2d2e1a7 Iustin Pop
  """Test case for FieldSets"""
933 a2d2e1a7 Iustin Pop
934 a2d2e1a7 Iustin Pop
  def testSimpleMatch(self):
935 a2d2e1a7 Iustin Pop
    f = utils.FieldSet("a", "b", "c", "def")
936 a2d2e1a7 Iustin Pop
    self.failUnless(f.Matches("a"))
937 a2d2e1a7 Iustin Pop
    self.failIf(f.Matches("d"), "Substring matched")
938 a2d2e1a7 Iustin Pop
    self.failIf(f.Matches("defghi"), "Prefix string matched")
939 a2d2e1a7 Iustin Pop
    self.failIf(f.NonMatching(["b", "c"]))
940 a2d2e1a7 Iustin Pop
    self.failIf(f.NonMatching(["a", "b", "c", "def"]))
941 a2d2e1a7 Iustin Pop
    self.failUnless(f.NonMatching(["a", "d"]))
942 a2d2e1a7 Iustin Pop
943 a2d2e1a7 Iustin Pop
  def testRegexMatch(self):
944 a2d2e1a7 Iustin Pop
    f = utils.FieldSet("a", "b([0-9]+)", "c")
945 a2d2e1a7 Iustin Pop
    self.failUnless(f.Matches("b1"))
946 a2d2e1a7 Iustin Pop
    self.failUnless(f.Matches("b99"))
947 a2d2e1a7 Iustin Pop
    self.failIf(f.Matches("b/1"))
948 a2d2e1a7 Iustin Pop
    self.failIf(f.NonMatching(["b12", "c"]))
949 a2d2e1a7 Iustin Pop
    self.failUnless(f.NonMatching(["a", "1"]))
950 a2d2e1a7 Iustin Pop
951 a5728081 Guido Trotter
class TestForceDictType(unittest.TestCase):
952 a5728081 Guido Trotter
  """Test case for ForceDictType"""
953 a5728081 Guido Trotter
954 a5728081 Guido Trotter
  def setUp(self):
955 a5728081 Guido Trotter
    self.key_types = {
956 a5728081 Guido Trotter
      'a': constants.VTYPE_INT,
957 a5728081 Guido Trotter
      'b': constants.VTYPE_BOOL,
958 a5728081 Guido Trotter
      'c': constants.VTYPE_STRING,
959 a5728081 Guido Trotter
      'd': constants.VTYPE_SIZE,
960 a5728081 Guido Trotter
      }
961 a5728081 Guido Trotter
962 a5728081 Guido Trotter
  def _fdt(self, dict, allowed_values=None):
963 a5728081 Guido Trotter
    if allowed_values is None:
964 a5728081 Guido Trotter
      ForceDictType(dict, self.key_types)
965 a5728081 Guido Trotter
    else:
966 a5728081 Guido Trotter
      ForceDictType(dict, self.key_types, allowed_values=allowed_values)
967 a5728081 Guido Trotter
968 a5728081 Guido Trotter
    return dict
969 a5728081 Guido Trotter
970 a5728081 Guido Trotter
  def testSimpleDict(self):
971 a5728081 Guido Trotter
    self.assertEqual(self._fdt({}), {})
972 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'a': 1}), {'a': 1})
973 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'a': '1'}), {'a': 1})
974 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'a': 1, 'b': 1}), {'a':1, 'b': True})
975 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 1, 'c': 'foo'}), {'b': True, 'c': 'foo'})
976 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 1, 'c': False}), {'b': True, 'c': ''})
977 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 'false'}), {'b': False})
978 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 'False'}), {'b': False})
979 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 'true'}), {'b': True})
980 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'b': 'True'}), {'b': True})
981 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'d': '4'}), {'d': 4})
982 a5728081 Guido Trotter
    self.assertEqual(self._fdt({'d': '4M'}), {'d': 4})
983 a5728081 Guido Trotter
984 a5728081 Guido Trotter
  def testErrors(self):
985 a5728081 Guido Trotter
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {'a': 'astring'})
986 a5728081 Guido Trotter
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {'c': True})
987 a5728081 Guido Trotter
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {'d': 'astring'})
988 a5728081 Guido Trotter
    self.assertRaises(errors.TypeEnforcementError, self._fdt, {'d': '4 L'})
989 a5728081 Guido Trotter
990 a2d2e1a7 Iustin Pop
991 da961187 Guido Trotter
class TestIsAbsNormPath(unittest.TestCase):
992 da961187 Guido Trotter
  """Testing case for IsProcessAlive"""
993 da961187 Guido Trotter
994 da961187 Guido Trotter
  def _pathTestHelper(self, path, result):
995 da961187 Guido Trotter
    if result:
996 da961187 Guido Trotter
      self.assert_(IsNormAbsPath(path),
997 17c61836 Guido Trotter
          "Path %s should result absolute and normalized" % path)
998 da961187 Guido Trotter
    else:
999 da961187 Guido Trotter
      self.assert_(not IsNormAbsPath(path),
1000 17c61836 Guido Trotter
          "Path %s should not result absolute and normalized" % path)
1001 da961187 Guido Trotter
1002 da961187 Guido Trotter
  def testBase(self):
1003 da961187 Guido Trotter
    self._pathTestHelper('/etc', True)
1004 da961187 Guido Trotter
    self._pathTestHelper('/srv', True)
1005 da961187 Guido Trotter
    self._pathTestHelper('etc', False)
1006 da961187 Guido Trotter
    self._pathTestHelper('/etc/../root', False)
1007 da961187 Guido Trotter
    self._pathTestHelper('/etc/', False)
1008 da961187 Guido Trotter
1009 af0413bb Guido Trotter
1010 d392fa34 Iustin Pop
class TestSafeEncode(unittest.TestCase):
1011 d392fa34 Iustin Pop
  """Test case for SafeEncode"""
1012 d392fa34 Iustin Pop
1013 d392fa34 Iustin Pop
  def testAscii(self):
1014 d392fa34 Iustin Pop
    for txt in [string.digits, string.letters, string.punctuation]:
1015 d392fa34 Iustin Pop
      self.failUnlessEqual(txt, SafeEncode(txt))
1016 d392fa34 Iustin Pop
1017 d392fa34 Iustin Pop
  def testDoubleEncode(self):
1018 d392fa34 Iustin Pop
    for i in range(255):
1019 d392fa34 Iustin Pop
      txt = SafeEncode(chr(i))
1020 d392fa34 Iustin Pop
      self.failUnlessEqual(txt, SafeEncode(txt))
1021 d392fa34 Iustin Pop
1022 d392fa34 Iustin Pop
  def testUnicode(self):
1023 d392fa34 Iustin Pop
    # 1024 is high enough to catch non-direct ASCII mappings
1024 d392fa34 Iustin Pop
    for i in range(1024):
1025 d392fa34 Iustin Pop
      txt = SafeEncode(unichr(i))
1026 d392fa34 Iustin Pop
      self.failUnlessEqual(txt, SafeEncode(txt))
1027 d392fa34 Iustin Pop
1028 d392fa34 Iustin Pop
1029 3b813dd2 Iustin Pop
class TestFormatTime(unittest.TestCase):
1030 3b813dd2 Iustin Pop
  """Testing case for FormatTime"""
1031 3b813dd2 Iustin Pop
1032 3b813dd2 Iustin Pop
  def testNone(self):
1033 3b813dd2 Iustin Pop
    self.failUnlessEqual(FormatTime(None), "N/A")
1034 3b813dd2 Iustin Pop
1035 3b813dd2 Iustin Pop
  def testInvalid(self):
1036 3b813dd2 Iustin Pop
    self.failUnlessEqual(FormatTime(()), "N/A")
1037 3b813dd2 Iustin Pop
1038 3b813dd2 Iustin Pop
  def testNow(self):
1039 3b813dd2 Iustin Pop
    # tests that we accept time.time input
1040 3b813dd2 Iustin Pop
    FormatTime(time.time())
1041 3b813dd2 Iustin Pop
    # tests that we accept int input
1042 3b813dd2 Iustin Pop
    FormatTime(int(time.time()))
1043 3b813dd2 Iustin Pop
1044 3b813dd2 Iustin Pop
1045 a8083063 Iustin Pop
if __name__ == '__main__':
1046 a8083063 Iustin Pop
  unittest.main()