Statistics
| Branch: | Tag: | Revision:

root / test / ganeti.utils_unittest.py @ d868edb4

History | View | Annotate | Download (26.9 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 a8083063 Iustin Pop
37 a8083063 Iustin Pop
import ganeti
38 c9c4f19e Michael Hanselmann
import testutils
39 16abfbc2 Alexander Schreiber
from ganeti import constants
40 59072e7e Michael Hanselmann
from ganeti import utils
41 e5392d79 Iustin Pop
from ganeti.utils import IsProcessAlive, RunCmd, \
42 a8083063 Iustin Pop
     RemoveFile, CheckDict, MatchNameComponent, FormatUnit, \
43 a8083063 Iustin Pop
     ParseUnit, AddAuthorizedKey, RemoveAuthorizedKey, \
44 899d2a81 Michael Hanselmann
     ShellQuote, ShellQuoteArgs, TcpPing, ListVisibleFiles, \
45 caad16e2 Iustin Pop
     SetEtcHostsEntry, RemoveEtcHostsEntry, FirstFree, OwnIpAddress
46 b2a1f511 Iustin Pop
from ganeti.errors import LockError, UnitParseError, GenericError, \
47 b2a1f511 Iustin Pop
     ProgrammerError
48 a8083063 Iustin Pop
49 d9f311d7 Iustin Pop
50 a8083063 Iustin Pop
class TestIsProcessAlive(unittest.TestCase):
51 a8083063 Iustin Pop
  """Testing case for IsProcessAlive"""
52 740c5aab Guido Trotter
53 a8083063 Iustin Pop
  def testExists(self):
54 a8083063 Iustin Pop
    mypid = os.getpid()
55 a8083063 Iustin Pop
    self.assert_(IsProcessAlive(mypid),
56 a8083063 Iustin Pop
                 "can't find myself running")
57 a8083063 Iustin Pop
58 a8083063 Iustin Pop
  def testNotExisting(self):
59 09352fa4 Iustin Pop
    pid_non_existing = os.fork()
60 09352fa4 Iustin Pop
    if pid_non_existing == 0:
61 09352fa4 Iustin Pop
      os._exit(0)
62 09352fa4 Iustin Pop
    elif pid_non_existing < 0:
63 09352fa4 Iustin Pop
      raise SystemError("can't fork")
64 09352fa4 Iustin Pop
    os.waitpid(pid_non_existing, 0)
65 09352fa4 Iustin Pop
    self.assert_(not IsProcessAlive(pid_non_existing),
66 09352fa4 Iustin Pop
                 "nonexisting process detected")
67 a8083063 Iustin Pop
68 d9f311d7 Iustin Pop
69 af99afa6 Guido Trotter
class TestPidFileFunctions(unittest.TestCase):
70 d9f311d7 Iustin Pop
  """Tests for WritePidFile, RemovePidFile and ReadPidFile"""
71 af99afa6 Guido Trotter
72 af99afa6 Guido Trotter
  def setUp(self):
73 af99afa6 Guido Trotter
    self.dir = tempfile.mkdtemp()
74 af99afa6 Guido Trotter
    self.f_dpn = lambda name: os.path.join(self.dir, "%s.pid" % name)
75 53beffbb Iustin Pop
    utils.DaemonPidFileName = self.f_dpn
76 af99afa6 Guido Trotter
77 af99afa6 Guido Trotter
  def testPidFileFunctions(self):
78 d9f311d7 Iustin Pop
    pid_file = self.f_dpn('test')
79 af99afa6 Guido Trotter
    utils.WritePidFile('test')
80 d9f311d7 Iustin Pop
    self.failUnless(os.path.exists(pid_file),
81 d9f311d7 Iustin Pop
                    "PID file should have been created")
82 d9f311d7 Iustin Pop
    read_pid = utils.ReadPidFile(pid_file)
83 d9f311d7 Iustin Pop
    self.failUnlessEqual(read_pid, os.getpid())
84 d9f311d7 Iustin Pop
    self.failUnless(utils.IsProcessAlive(read_pid))
85 d9f311d7 Iustin Pop
    self.failUnlessRaises(GenericError, utils.WritePidFile, 'test')
86 d9f311d7 Iustin Pop
    utils.RemovePidFile('test')
87 d9f311d7 Iustin Pop
    self.failIf(os.path.exists(pid_file),
88 d9f311d7 Iustin Pop
                "PID file should not exist anymore")
89 d9f311d7 Iustin Pop
    self.failUnlessEqual(utils.ReadPidFile(pid_file), 0,
90 d9f311d7 Iustin Pop
                         "ReadPidFile should return 0 for missing pid file")
91 d9f311d7 Iustin Pop
    fh = open(pid_file, "w")
92 d9f311d7 Iustin Pop
    fh.write("blah\n")
93 d9f311d7 Iustin Pop
    fh.close()
94 d9f311d7 Iustin Pop
    self.failUnlessEqual(utils.ReadPidFile(pid_file), 0,
95 d9f311d7 Iustin Pop
                         "ReadPidFile should return 0 for invalid pid file")
96 af99afa6 Guido Trotter
    utils.RemovePidFile('test')
97 d9f311d7 Iustin Pop
    self.failIf(os.path.exists(pid_file),
98 d9f311d7 Iustin Pop
                "PID file should not exist anymore")
99 af99afa6 Guido Trotter
100 b2a1f511 Iustin Pop
  def testKill(self):
101 b2a1f511 Iustin Pop
    pid_file = self.f_dpn('child')
102 b2a1f511 Iustin Pop
    r_fd, w_fd = os.pipe()
103 b2a1f511 Iustin Pop
    new_pid = os.fork()
104 b2a1f511 Iustin Pop
    if new_pid == 0: #child
105 b2a1f511 Iustin Pop
      utils.WritePidFile('child')
106 b2a1f511 Iustin Pop
      os.write(w_fd, 'a')
107 b2a1f511 Iustin Pop
      signal.pause()
108 b2a1f511 Iustin Pop
      os._exit(0)
109 b2a1f511 Iustin Pop
      return
110 b2a1f511 Iustin Pop
    # else we are in the parent
111 b2a1f511 Iustin Pop
    # wait until the child has written the pid file
112 b2a1f511 Iustin Pop
    os.read(r_fd, 1)
113 b2a1f511 Iustin Pop
    read_pid = utils.ReadPidFile(pid_file)
114 b2a1f511 Iustin Pop
    self.failUnlessEqual(read_pid, new_pid)
115 b2a1f511 Iustin Pop
    self.failUnless(utils.IsProcessAlive(new_pid))
116 ff5251bc Iustin Pop
    utils.KillProcess(new_pid, waitpid=True)
117 b2a1f511 Iustin Pop
    self.failIf(utils.IsProcessAlive(new_pid))
118 b2a1f511 Iustin Pop
    utils.RemovePidFile('child')
119 b2a1f511 Iustin Pop
    self.failUnlessRaises(ProgrammerError, utils.KillProcess, 0)
120 b2a1f511 Iustin Pop
121 af99afa6 Guido Trotter
  def tearDown(self):
122 d9f311d7 Iustin Pop
    for name in os.listdir(self.dir):
123 d9f311d7 Iustin Pop
      os.unlink(os.path.join(self.dir, name))
124 af99afa6 Guido Trotter
    os.rmdir(self.dir)
125 af99afa6 Guido Trotter
126 a8083063 Iustin Pop
127 36117c2b Iustin Pop
class TestRunCmd(testutils.GanetiTestCase):
128 a8083063 Iustin Pop
  """Testing case for the RunCmd function"""
129 a8083063 Iustin Pop
130 a8083063 Iustin Pop
  def setUp(self):
131 a8083063 Iustin Pop
    self.magic = time.ctime() + " ganeti test"
132 36117c2b Iustin Pop
    fh, self.fname = tempfile.mkstemp()
133 36117c2b Iustin Pop
    os.close(fh)
134 36117c2b Iustin Pop
135 36117c2b Iustin Pop
  def tearDown(self):
136 36117c2b Iustin Pop
    if self.fname:
137 36117c2b Iustin Pop
      utils.RemoveFile(self.fname)
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 a8083063 Iustin Pop
class TestCheckdict(unittest.TestCase):
281 a8083063 Iustin Pop
  """Test case for the CheckDict function"""
282 a8083063 Iustin Pop
283 a8083063 Iustin Pop
  def testAdd(self):
284 a8083063 Iustin Pop
    """Test that CheckDict adds a missing key with the correct value"""
285 a8083063 Iustin Pop
286 a8083063 Iustin Pop
    tgt = {'a':1}
287 a8083063 Iustin Pop
    tmpl = {'b': 2}
288 a8083063 Iustin Pop
    CheckDict(tgt, tmpl)
289 a8083063 Iustin Pop
    if 'b' not in tgt or tgt['b'] != 2:
290 a8083063 Iustin Pop
      self.fail("Failed to update dict")
291 a8083063 Iustin Pop
292 a8083063 Iustin Pop
293 a8083063 Iustin Pop
  def testNoUpdate(self):
294 a8083063 Iustin Pop
    """Test that CheckDict does not overwrite an existing key"""
295 a8083063 Iustin Pop
    tgt = {'a':1, 'b': 3}
296 a8083063 Iustin Pop
    tmpl = {'b': 2}
297 a8083063 Iustin Pop
    CheckDict(tgt, tmpl)
298 a8083063 Iustin Pop
    self.failUnlessEqual(tgt['b'], 3)
299 a8083063 Iustin Pop
300 a8083063 Iustin Pop
301 a8083063 Iustin Pop
class TestMatchNameComponent(unittest.TestCase):
302 a8083063 Iustin Pop
  """Test case for the MatchNameComponent function"""
303 a8083063 Iustin Pop
304 a8083063 Iustin Pop
  def testEmptyList(self):
305 a8083063 Iustin Pop
    """Test that there is no match against an empty list"""
306 a8083063 Iustin Pop
307 a8083063 Iustin Pop
    self.failUnlessEqual(MatchNameComponent("", []), None)
308 a8083063 Iustin Pop
    self.failUnlessEqual(MatchNameComponent("test", []), None)
309 a8083063 Iustin Pop
310 a8083063 Iustin Pop
  def testSingleMatch(self):
311 a8083063 Iustin Pop
    """Test that a single match is performed correctly"""
312 a8083063 Iustin Pop
    mlist = ["test1.example.com", "test2.example.com", "test3.example.com"]
313 a8083063 Iustin Pop
    for key in "test2", "test2.example", "test2.example.com":
314 a8083063 Iustin Pop
      self.failUnlessEqual(MatchNameComponent(key, mlist), mlist[1])
315 a8083063 Iustin Pop
316 a8083063 Iustin Pop
  def testMultipleMatches(self):
317 a8083063 Iustin Pop
    """Test that a multiple match is returned as None"""
318 a8083063 Iustin Pop
    mlist = ["test1.example.com", "test1.example.org", "test1.example.net"]
319 a8083063 Iustin Pop
    for key in "test1", "test1.example":
320 a8083063 Iustin Pop
      self.failUnlessEqual(MatchNameComponent(key, mlist), None)
321 a8083063 Iustin Pop
322 a8083063 Iustin Pop
323 a8083063 Iustin Pop
class TestFormatUnit(unittest.TestCase):
324 a8083063 Iustin Pop
  """Test case for the FormatUnit function"""
325 a8083063 Iustin Pop
326 a8083063 Iustin Pop
  def testMiB(self):
327 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(1), '1M')
328 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(100), '100M')
329 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(1023), '1023M')
330 a8083063 Iustin Pop
331 a8083063 Iustin Pop
  def testGiB(self):
332 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(1024), '1.0G')
333 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(1536), '1.5G')
334 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(17133), '16.7G')
335 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024 - 1), '1024.0G')
336 a8083063 Iustin Pop
337 a8083063 Iustin Pop
  def testTiB(self):
338 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(1024 * 1024), '1.0T')
339 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(5120 * 1024), '5.0T')
340 a8083063 Iustin Pop
    self.assertEqual(FormatUnit(29829 * 1024), '29.1T')
341 a8083063 Iustin Pop
342 a8083063 Iustin Pop
343 a8083063 Iustin Pop
class TestParseUnit(unittest.TestCase):
344 a8083063 Iustin Pop
  """Test case for the ParseUnit function"""
345 a8083063 Iustin Pop
346 a8083063 Iustin Pop
  SCALES = (('', 1),
347 a8083063 Iustin Pop
            ('M', 1), ('G', 1024), ('T', 1024 * 1024),
348 a8083063 Iustin Pop
            ('MB', 1), ('GB', 1024), ('TB', 1024 * 1024),
349 a8083063 Iustin Pop
            ('MiB', 1), ('GiB', 1024), ('TiB', 1024 * 1024))
350 a8083063 Iustin Pop
351 a8083063 Iustin Pop
  def testRounding(self):
352 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('0'), 0)
353 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1'), 4)
354 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('2'), 4)
355 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('3'), 4)
356 a8083063 Iustin Pop
357 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('124'), 124)
358 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('125'), 128)
359 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('126'), 128)
360 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('127'), 128)
361 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('128'), 128)
362 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('129'), 132)
363 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('130'), 132)
364 a8083063 Iustin Pop
365 a8083063 Iustin Pop
  def testFloating(self):
366 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('0'), 0)
367 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('0.5'), 4)
368 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.75'), 4)
369 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.99'), 4)
370 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('2.00'), 4)
371 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('2.01'), 4)
372 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('3.99'), 4)
373 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('4.00'), 4)
374 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('4.01'), 8)
375 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.5G'), 1536)
376 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('1.8G'), 1844)
377 a8083063 Iustin Pop
    self.assertEqual(ParseUnit('8.28T'), 8682212)
378 a8083063 Iustin Pop
379 a8083063 Iustin Pop
  def testSuffixes(self):
380 a8083063 Iustin Pop
    for sep in ('', ' ', '   ', "\t", "\t "):
381 a8083063 Iustin Pop
      for suffix, scale in TestParseUnit.SCALES:
382 a8083063 Iustin Pop
        for func in (lambda x: x, str.lower, str.upper):
383 667479d5 Michael Hanselmann
          self.assertEqual(ParseUnit('1024' + sep + func(suffix)),
384 667479d5 Michael Hanselmann
                           1024 * scale)
385 a8083063 Iustin Pop
386 a8083063 Iustin Pop
  def testInvalidInput(self):
387 a8083063 Iustin Pop
    for sep in ('-', '_', ',', 'a'):
388 a8083063 Iustin Pop
      for suffix, _ in TestParseUnit.SCALES:
389 a8083063 Iustin Pop
        self.assertRaises(UnitParseError, ParseUnit, '1' + sep + suffix)
390 a8083063 Iustin Pop
391 a8083063 Iustin Pop
    for suffix, _ in TestParseUnit.SCALES:
392 a8083063 Iustin Pop
      self.assertRaises(UnitParseError, ParseUnit, '1,3' + suffix)
393 a8083063 Iustin Pop
394 a8083063 Iustin Pop
395 c9c4f19e Michael Hanselmann
class TestSshKeys(testutils.GanetiTestCase):
396 a8083063 Iustin Pop
  """Test case for the AddAuthorizedKey function"""
397 a8083063 Iustin Pop
398 a8083063 Iustin Pop
  KEY_A = 'ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a'
399 a8083063 Iustin Pop
  KEY_B = ('command="/usr/bin/fooserver -t --verbose",from="1.2.3.4" '
400 a8083063 Iustin Pop
           'ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b')
401 a8083063 Iustin Pop
402 ebe8ef17 Michael Hanselmann
  def setUp(self):
403 ebe8ef17 Michael Hanselmann
    (fd, self.tmpname) = tempfile.mkstemp(prefix='ganeti-test')
404 a8083063 Iustin Pop
    try:
405 ebe8ef17 Michael Hanselmann
      handle = os.fdopen(fd, 'w')
406 ebe8ef17 Michael Hanselmann
      try:
407 ebe8ef17 Michael Hanselmann
        handle.write("%s\n" % TestSshKeys.KEY_A)
408 ebe8ef17 Michael Hanselmann
        handle.write("%s\n" % TestSshKeys.KEY_B)
409 ebe8ef17 Michael Hanselmann
      finally:
410 ebe8ef17 Michael Hanselmann
        handle.close()
411 ebe8ef17 Michael Hanselmann
    except:
412 ebe8ef17 Michael Hanselmann
      utils.RemoveFile(self.tmpname)
413 ebe8ef17 Michael Hanselmann
      raise
414 a8083063 Iustin Pop
415 ebe8ef17 Michael Hanselmann
  def tearDown(self):
416 ebe8ef17 Michael Hanselmann
    utils.RemoveFile(self.tmpname)
417 ebe8ef17 Michael Hanselmann
    del self.tmpname
418 a8083063 Iustin Pop
419 a8083063 Iustin Pop
  def testAddingNewKey(self):
420 ebe8ef17 Michael Hanselmann
    AddAuthorizedKey(self.tmpname, 'ssh-dss AAAAB3NzaC1kc3MAAACB root@test')
421 a8083063 Iustin Pop
422 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
423 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
424 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
425 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n"
426 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1kc3MAAACB root@test\n")
427 a8083063 Iustin Pop
428 f89f17a8 Michael Hanselmann
  def testAddingAlmostButNotCompletelyTheSameKey(self):
429 ebe8ef17 Michael Hanselmann
    AddAuthorizedKey(self.tmpname,
430 ebe8ef17 Michael Hanselmann
        'ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@test')
431 ebe8ef17 Michael Hanselmann
432 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
433 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
434 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
435 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n"
436 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@test\n")
437 a8083063 Iustin Pop
438 a8083063 Iustin Pop
  def testAddingExistingKeyWithSomeMoreSpaces(self):
439 ebe8ef17 Michael Hanselmann
    AddAuthorizedKey(self.tmpname,
440 ebe8ef17 Michael Hanselmann
        'ssh-dss  AAAAB3NzaC1w5256closdj32mZaQU   root@key-a')
441 a8083063 Iustin Pop
442 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
443 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
444 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
445 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
446 a8083063 Iustin Pop
447 a8083063 Iustin Pop
  def testRemovingExistingKeyWithSomeMoreSpaces(self):
448 ebe8ef17 Michael Hanselmann
    RemoveAuthorizedKey(self.tmpname,
449 ebe8ef17 Michael Hanselmann
        'ssh-dss  AAAAB3NzaC1w5256closdj32mZaQU   root@key-a')
450 a8083063 Iustin Pop
451 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
452 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
453 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
454 a8083063 Iustin Pop
455 a8083063 Iustin Pop
  def testRemovingNonExistingKey(self):
456 ebe8ef17 Michael Hanselmann
    RemoveAuthorizedKey(self.tmpname,
457 ebe8ef17 Michael Hanselmann
        'ssh-dss  AAAAB3Nsdfj230xxjxJjsjwjsjdjU   root@test')
458 a8083063 Iustin Pop
459 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
460 ebe8ef17 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
461 ebe8ef17 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="1.2.3.4"'
462 ebe8ef17 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
463 a8083063 Iustin Pop
464 a8083063 Iustin Pop
465 c9c4f19e Michael Hanselmann
class TestEtcHosts(testutils.GanetiTestCase):
466 899d2a81 Michael Hanselmann
  """Test functions modifying /etc/hosts"""
467 899d2a81 Michael Hanselmann
468 ebe8ef17 Michael Hanselmann
  def setUp(self):
469 ebe8ef17 Michael Hanselmann
    (fd, self.tmpname) = tempfile.mkstemp(prefix='ganeti-test')
470 899d2a81 Michael Hanselmann
    try:
471 ebe8ef17 Michael Hanselmann
      handle = os.fdopen(fd, 'w')
472 ebe8ef17 Michael Hanselmann
      try:
473 ebe8ef17 Michael Hanselmann
        handle.write('# This is a test file for /etc/hosts\n')
474 ebe8ef17 Michael Hanselmann
        handle.write('127.0.0.1\tlocalhost\n')
475 ebe8ef17 Michael Hanselmann
        handle.write('192.168.1.1 router gw\n')
476 ebe8ef17 Michael Hanselmann
      finally:
477 ebe8ef17 Michael Hanselmann
        handle.close()
478 ebe8ef17 Michael Hanselmann
    except:
479 ebe8ef17 Michael Hanselmann
      utils.RemoveFile(self.tmpname)
480 ebe8ef17 Michael Hanselmann
      raise
481 899d2a81 Michael Hanselmann
482 ebe8ef17 Michael Hanselmann
  def tearDown(self):
483 ebe8ef17 Michael Hanselmann
    utils.RemoveFile(self.tmpname)
484 ebe8ef17 Michael Hanselmann
    del self.tmpname
485 899d2a81 Michael Hanselmann
486 9440aeab Michael Hanselmann
  def testSettingNewIp(self):
487 ebe8ef17 Michael Hanselmann
    SetEtcHostsEntry(self.tmpname, '1.2.3.4', 'myhost.domain.tld', ['myhost'])
488 899d2a81 Michael Hanselmann
489 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
490 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
491 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
492 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router gw\n"
493 ebe8ef17 Michael Hanselmann
      "1.2.3.4\tmyhost.domain.tld myhost\n")
494 899d2a81 Michael Hanselmann
495 9440aeab Michael Hanselmann
  def testSettingExistingIp(self):
496 ebe8ef17 Michael Hanselmann
    SetEtcHostsEntry(self.tmpname, '192.168.1.1', 'myhost.domain.tld',
497 ebe8ef17 Michael Hanselmann
                     ['myhost'])
498 899d2a81 Michael Hanselmann
499 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
500 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
501 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
502 ebe8ef17 Michael Hanselmann
      "192.168.1.1\tmyhost.domain.tld myhost\n")
503 899d2a81 Michael Hanselmann
504 7fbb1f65 Michael Hanselmann
  def testSettingDuplicateName(self):
505 7fbb1f65 Michael Hanselmann
    SetEtcHostsEntry(self.tmpname, '1.2.3.4', 'myhost', ['myhost'])
506 7fbb1f65 Michael Hanselmann
507 7fbb1f65 Michael Hanselmann
    self.assertFileContent(self.tmpname,
508 7fbb1f65 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
509 7fbb1f65 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
510 7fbb1f65 Michael Hanselmann
      "192.168.1.1 router gw\n"
511 7fbb1f65 Michael Hanselmann
      "1.2.3.4\tmyhost\n")
512 7fbb1f65 Michael Hanselmann
513 899d2a81 Michael Hanselmann
  def testRemovingExistingHost(self):
514 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'router')
515 899d2a81 Michael Hanselmann
516 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
517 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
518 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
519 ebe8ef17 Michael Hanselmann
      "192.168.1.1 gw\n")
520 899d2a81 Michael Hanselmann
521 899d2a81 Michael Hanselmann
  def testRemovingSingleExistingHost(self):
522 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'localhost')
523 899d2a81 Michael Hanselmann
524 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
525 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
526 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router gw\n")
527 899d2a81 Michael Hanselmann
528 899d2a81 Michael Hanselmann
  def testRemovingNonExistingHost(self):
529 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'myhost')
530 899d2a81 Michael Hanselmann
531 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
532 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
533 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
534 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router gw\n")
535 899d2a81 Michael Hanselmann
536 9440aeab Michael Hanselmann
  def testRemovingAlias(self):
537 ebe8ef17 Michael Hanselmann
    RemoveEtcHostsEntry(self.tmpname, 'gw')
538 9440aeab Michael Hanselmann
539 ebe8ef17 Michael Hanselmann
    self.assertFileContent(self.tmpname,
540 ebe8ef17 Michael Hanselmann
      "# This is a test file for /etc/hosts\n"
541 ebe8ef17 Michael Hanselmann
      "127.0.0.1\tlocalhost\n"
542 ebe8ef17 Michael Hanselmann
      "192.168.1.1 router\n")
543 9440aeab Michael Hanselmann
544 899d2a81 Michael Hanselmann
545 a8083063 Iustin Pop
class TestShellQuoting(unittest.TestCase):
546 a8083063 Iustin Pop
  """Test case for shell quoting functions"""
547 a8083063 Iustin Pop
548 a8083063 Iustin Pop
  def testShellQuote(self):
549 a8083063 Iustin Pop
    self.assertEqual(ShellQuote('abc'), "abc")
550 a8083063 Iustin Pop
    self.assertEqual(ShellQuote('ab"c'), "'ab\"c'")
551 a8083063 Iustin Pop
    self.assertEqual(ShellQuote("a'bc"), "'a'\\''bc'")
552 a8083063 Iustin Pop
    self.assertEqual(ShellQuote("a b c"), "'a b c'")
553 a8083063 Iustin Pop
    self.assertEqual(ShellQuote("a b\\ c"), "'a b\\ c'")
554 a8083063 Iustin Pop
555 a8083063 Iustin Pop
  def testShellQuoteArgs(self):
556 a8083063 Iustin Pop
    self.assertEqual(ShellQuoteArgs(['a', 'b', 'c']), "a b c")
557 a8083063 Iustin Pop
    self.assertEqual(ShellQuoteArgs(['a', 'b"', 'c']), "a 'b\"' c")
558 a8083063 Iustin Pop
    self.assertEqual(ShellQuoteArgs(['a', 'b\'', 'c']), "a 'b'\\\''' c")
559 a8083063 Iustin Pop
560 a8083063 Iustin Pop
561 2c30e9d7 Alexander Schreiber
class TestTcpPing(unittest.TestCase):
562 2c30e9d7 Alexander Schreiber
  """Testcase for TCP version of ping - against listen(2)ing port"""
563 2c30e9d7 Alexander Schreiber
564 2c30e9d7 Alexander Schreiber
  def setUp(self):
565 2c30e9d7 Alexander Schreiber
    self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
566 16abfbc2 Alexander Schreiber
    self.listener.bind((constants.LOCALHOST_IP_ADDRESS, 0))
567 2c30e9d7 Alexander Schreiber
    self.listenerport = self.listener.getsockname()[1]
568 2c30e9d7 Alexander Schreiber
    self.listener.listen(1)
569 2c30e9d7 Alexander Schreiber
570 2c30e9d7 Alexander Schreiber
  def tearDown(self):
571 2c30e9d7 Alexander Schreiber
    self.listener.shutdown(socket.SHUT_RDWR)
572 2c30e9d7 Alexander Schreiber
    del self.listener
573 2c30e9d7 Alexander Schreiber
    del self.listenerport
574 2c30e9d7 Alexander Schreiber
575 2c30e9d7 Alexander Schreiber
  def testTcpPingToLocalHostAccept(self):
576 16abfbc2 Alexander Schreiber
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
577 2c30e9d7 Alexander Schreiber
                         self.listenerport,
578 2c30e9d7 Alexander Schreiber
                         timeout=10,
579 b15d625f Iustin Pop
                         live_port_needed=True,
580 b15d625f Iustin Pop
                         source=constants.LOCALHOST_IP_ADDRESS,
581 b15d625f Iustin Pop
                         ),
582 2c30e9d7 Alexander Schreiber
                 "failed to connect to test listener")
583 2c30e9d7 Alexander Schreiber
584 b15d625f Iustin Pop
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
585 b15d625f Iustin Pop
                         self.listenerport,
586 b15d625f Iustin Pop
                         timeout=10,
587 b15d625f Iustin Pop
                         live_port_needed=True,
588 b15d625f Iustin Pop
                         ),
589 b15d625f Iustin Pop
                 "failed to connect to test listener (no source)")
590 b15d625f Iustin Pop
591 2c30e9d7 Alexander Schreiber
592 2c30e9d7 Alexander Schreiber
class TestTcpPingDeaf(unittest.TestCase):
593 2c30e9d7 Alexander Schreiber
  """Testcase for TCP version of ping - against non listen(2)ing port"""
594 2c30e9d7 Alexander Schreiber
595 2c30e9d7 Alexander Schreiber
  def setUp(self):
596 2c30e9d7 Alexander Schreiber
    self.deaflistener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
597 16abfbc2 Alexander Schreiber
    self.deaflistener.bind((constants.LOCALHOST_IP_ADDRESS, 0))
598 2c30e9d7 Alexander Schreiber
    self.deaflistenerport = self.deaflistener.getsockname()[1]
599 2c30e9d7 Alexander Schreiber
600 2c30e9d7 Alexander Schreiber
  def tearDown(self):
601 2c30e9d7 Alexander Schreiber
    del self.deaflistener
602 2c30e9d7 Alexander Schreiber
    del self.deaflistenerport
603 2c30e9d7 Alexander Schreiber
604 2c30e9d7 Alexander Schreiber
  def testTcpPingToLocalHostAcceptDeaf(self):
605 16abfbc2 Alexander Schreiber
    self.failIf(TcpPing(constants.LOCALHOST_IP_ADDRESS,
606 2c30e9d7 Alexander Schreiber
                        self.deaflistenerport,
607 16abfbc2 Alexander Schreiber
                        timeout=constants.TCP_PING_TIMEOUT,
608 b15d625f Iustin Pop
                        live_port_needed=True,
609 b15d625f Iustin Pop
                        source=constants.LOCALHOST_IP_ADDRESS,
610 b15d625f Iustin Pop
                        ), # need successful connect(2)
611 2c30e9d7 Alexander Schreiber
                "successfully connected to deaf listener")
612 2c30e9d7 Alexander Schreiber
613 b15d625f Iustin Pop
    self.failIf(TcpPing(constants.LOCALHOST_IP_ADDRESS,
614 b15d625f Iustin Pop
                        self.deaflistenerport,
615 b15d625f Iustin Pop
                        timeout=constants.TCP_PING_TIMEOUT,
616 b15d625f Iustin Pop
                        live_port_needed=True,
617 b15d625f Iustin Pop
                        ), # need successful connect(2)
618 b15d625f Iustin Pop
                "successfully connected to deaf listener (no source addr)")
619 b15d625f Iustin Pop
620 2c30e9d7 Alexander Schreiber
  def testTcpPingToLocalHostNoAccept(self):
621 16abfbc2 Alexander Schreiber
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
622 2c30e9d7 Alexander Schreiber
                         self.deaflistenerport,
623 16abfbc2 Alexander Schreiber
                         timeout=constants.TCP_PING_TIMEOUT,
624 b15d625f Iustin Pop
                         live_port_needed=False,
625 b15d625f Iustin Pop
                         source=constants.LOCALHOST_IP_ADDRESS,
626 b15d625f Iustin Pop
                         ), # ECONNREFUSED is OK
627 2c30e9d7 Alexander Schreiber
                 "failed to ping alive host on deaf port")
628 2c30e9d7 Alexander Schreiber
629 b15d625f Iustin Pop
    self.assert_(TcpPing(constants.LOCALHOST_IP_ADDRESS,
630 b15d625f Iustin Pop
                         self.deaflistenerport,
631 b15d625f Iustin Pop
                         timeout=constants.TCP_PING_TIMEOUT,
632 b15d625f Iustin Pop
                         live_port_needed=False,
633 b15d625f Iustin Pop
                         ), # ECONNREFUSED is OK
634 b15d625f Iustin Pop
                 "failed to ping alive host on deaf port (no source addr)")
635 b15d625f Iustin Pop
636 2c30e9d7 Alexander Schreiber
637 caad16e2 Iustin Pop
class TestOwnIpAddress(unittest.TestCase):
638 caad16e2 Iustin Pop
  """Testcase for OwnIpAddress"""
639 caad16e2 Iustin Pop
640 caad16e2 Iustin Pop
  def testOwnLoopback(self):
641 caad16e2 Iustin Pop
    """check having the loopback ip"""
642 caad16e2 Iustin Pop
    self.failUnless(OwnIpAddress(constants.LOCALHOST_IP_ADDRESS),
643 caad16e2 Iustin Pop
                    "Should own the loopback address")
644 caad16e2 Iustin Pop
645 caad16e2 Iustin Pop
  def testNowOwnAddress(self):
646 caad16e2 Iustin Pop
    """check that I don't own an address"""
647 caad16e2 Iustin Pop
648 caad16e2 Iustin Pop
    # network 192.0.2.0/24 is reserved for test/documentation as per
649 caad16e2 Iustin Pop
    # rfc 3330, so we *should* not have an address of this range... if
650 caad16e2 Iustin Pop
    # this fails, we should extend the test to multiple addresses
651 caad16e2 Iustin Pop
    DST_IP = "192.0.2.1"
652 caad16e2 Iustin Pop
    self.failIf(OwnIpAddress(DST_IP), "Should not own IP address %s" % DST_IP)
653 caad16e2 Iustin Pop
654 caad16e2 Iustin Pop
655 eedbda4b Michael Hanselmann
class TestListVisibleFiles(unittest.TestCase):
656 eedbda4b Michael Hanselmann
  """Test case for ListVisibleFiles"""
657 eedbda4b Michael Hanselmann
658 eedbda4b Michael Hanselmann
  def setUp(self):
659 eedbda4b Michael Hanselmann
    self.path = tempfile.mkdtemp()
660 eedbda4b Michael Hanselmann
661 eedbda4b Michael Hanselmann
  def tearDown(self):
662 eedbda4b Michael Hanselmann
    shutil.rmtree(self.path)
663 eedbda4b Michael Hanselmann
664 eedbda4b Michael Hanselmann
  def _test(self, files, expected):
665 eedbda4b Michael Hanselmann
    # Sort a copy
666 eedbda4b Michael Hanselmann
    expected = expected[:]
667 eedbda4b Michael Hanselmann
    expected.sort()
668 eedbda4b Michael Hanselmann
669 eedbda4b Michael Hanselmann
    for name in files:
670 eedbda4b Michael Hanselmann
      f = open(os.path.join(self.path, name), 'w')
671 eedbda4b Michael Hanselmann
      try:
672 eedbda4b Michael Hanselmann
        f.write("Test\n")
673 eedbda4b Michael Hanselmann
      finally:
674 eedbda4b Michael Hanselmann
        f.close()
675 eedbda4b Michael Hanselmann
676 eedbda4b Michael Hanselmann
    found = ListVisibleFiles(self.path)
677 eedbda4b Michael Hanselmann
    found.sort()
678 eedbda4b Michael Hanselmann
679 eedbda4b Michael Hanselmann
    self.assertEqual(found, expected)
680 eedbda4b Michael Hanselmann
681 eedbda4b Michael Hanselmann
  def testAllVisible(self):
682 eedbda4b Michael Hanselmann
    files = ["a", "b", "c"]
683 eedbda4b Michael Hanselmann
    expected = files
684 eedbda4b Michael Hanselmann
    self._test(files, expected)
685 eedbda4b Michael Hanselmann
686 eedbda4b Michael Hanselmann
  def testNoneVisible(self):
687 eedbda4b Michael Hanselmann
    files = [".a", ".b", ".c"]
688 eedbda4b Michael Hanselmann
    expected = []
689 eedbda4b Michael Hanselmann
    self._test(files, expected)
690 eedbda4b Michael Hanselmann
691 eedbda4b Michael Hanselmann
  def testSomeVisible(self):
692 eedbda4b Michael Hanselmann
    files = ["a", "b", ".c"]
693 eedbda4b Michael Hanselmann
    expected = ["a", "b"]
694 eedbda4b Michael Hanselmann
    self._test(files, expected)
695 eedbda4b Michael Hanselmann
696 eedbda4b Michael Hanselmann
697 24818e8f Michael Hanselmann
class TestNewUUID(unittest.TestCase):
698 24818e8f Michael Hanselmann
  """Test case for NewUUID"""
699 59072e7e Michael Hanselmann
700 59072e7e Michael Hanselmann
  _re_uuid = re.compile('^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-'
701 59072e7e Michael Hanselmann
                        '[a-f0-9]{4}-[a-f0-9]{12}$')
702 59072e7e Michael Hanselmann
703 59072e7e Michael Hanselmann
  def runTest(self):
704 24818e8f Michael Hanselmann
    self.failUnless(self._re_uuid.match(utils.NewUUID()))
705 59072e7e Michael Hanselmann
706 59072e7e Michael Hanselmann
707 f7414041 Michael Hanselmann
class TestUniqueSequence(unittest.TestCase):
708 f7414041 Michael Hanselmann
  """Test case for UniqueSequence"""
709 f7414041 Michael Hanselmann
710 f7414041 Michael Hanselmann
  def _test(self, input, expected):
711 f7414041 Michael Hanselmann
    self.assertEqual(utils.UniqueSequence(input), expected)
712 f7414041 Michael Hanselmann
713 f7414041 Michael Hanselmann
  def runTest(self):
714 f7414041 Michael Hanselmann
    # Ordered input
715 f7414041 Michael Hanselmann
    self._test([1, 2, 3], [1, 2, 3])
716 f7414041 Michael Hanselmann
    self._test([1, 1, 2, 2, 3, 3], [1, 2, 3])
717 f7414041 Michael Hanselmann
    self._test([1, 2, 2, 3], [1, 2, 3])
718 f7414041 Michael Hanselmann
    self._test([1, 2, 3, 3], [1, 2, 3])
719 f7414041 Michael Hanselmann
720 f7414041 Michael Hanselmann
    # Unordered input
721 f7414041 Michael Hanselmann
    self._test([1, 2, 3, 1, 2, 3], [1, 2, 3])
722 f7414041 Michael Hanselmann
    self._test([1, 1, 2, 3, 3, 1, 2], [1, 2, 3])
723 f7414041 Michael Hanselmann
724 f7414041 Michael Hanselmann
    # Strings
725 f7414041 Michael Hanselmann
    self._test(["a", "a"], ["a"])
726 f7414041 Michael Hanselmann
    self._test(["a", "b"], ["a", "b"])
727 f7414041 Michael Hanselmann
    self._test(["a", "b", "a"], ["a", "b"])
728 f7414041 Michael Hanselmann
729 a87b4824 Michael Hanselmann
730 7b4126b7 Iustin Pop
class TestFirstFree(unittest.TestCase):
731 7b4126b7 Iustin Pop
  """Test case for the FirstFree function"""
732 7b4126b7 Iustin Pop
733 7b4126b7 Iustin Pop
  def test(self):
734 7b4126b7 Iustin Pop
    """Test FirstFree"""
735 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([0, 1, 3]), 2)
736 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([]), None)
737 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([3, 4, 6]), 0)
738 7b4126b7 Iustin Pop
    self.failUnlessEqual(FirstFree([3, 4, 6], base=3), 5)
739 7b4126b7 Iustin Pop
    self.failUnlessRaises(AssertionError, FirstFree, [0, 3, 4, 6], base=3)
740 f7414041 Michael Hanselmann
741 a87b4824 Michael Hanselmann
742 a87b4824 Michael Hanselmann
class TestFileLock(unittest.TestCase):
743 a87b4824 Michael Hanselmann
  """Test case for the FileLock class"""
744 a87b4824 Michael Hanselmann
745 a87b4824 Michael Hanselmann
  def setUp(self):
746 a87b4824 Michael Hanselmann
    self.tmpfile = tempfile.NamedTemporaryFile()
747 a87b4824 Michael Hanselmann
    self.lock = utils.FileLock(self.tmpfile.name)
748 a87b4824 Michael Hanselmann
749 a87b4824 Michael Hanselmann
  def testSharedNonblocking(self):
750 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=False)
751 a87b4824 Michael Hanselmann
    self.lock.Close()
752 a87b4824 Michael Hanselmann
753 a87b4824 Michael Hanselmann
  def testExclusiveNonblocking(self):
754 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=False)
755 a87b4824 Michael Hanselmann
    self.lock.Close()
756 a87b4824 Michael Hanselmann
757 a87b4824 Michael Hanselmann
  def testUnlockNonblocking(self):
758 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=False)
759 a87b4824 Michael Hanselmann
    self.lock.Close()
760 a87b4824 Michael Hanselmann
761 a87b4824 Michael Hanselmann
  def testSharedBlocking(self):
762 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=True)
763 a87b4824 Michael Hanselmann
    self.lock.Close()
764 a87b4824 Michael Hanselmann
765 a87b4824 Michael Hanselmann
  def testExclusiveBlocking(self):
766 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=True)
767 a87b4824 Michael Hanselmann
    self.lock.Close()
768 a87b4824 Michael Hanselmann
769 a87b4824 Michael Hanselmann
  def testUnlockBlocking(self):
770 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=True)
771 a87b4824 Michael Hanselmann
    self.lock.Close()
772 a87b4824 Michael Hanselmann
773 a87b4824 Michael Hanselmann
  def testSharedExclusiveUnlock(self):
774 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=False)
775 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=False)
776 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=False)
777 a87b4824 Michael Hanselmann
    self.lock.Close()
778 a87b4824 Michael Hanselmann
779 a87b4824 Michael Hanselmann
  def testExclusiveSharedUnlock(self):
780 a87b4824 Michael Hanselmann
    self.lock.Exclusive(blocking=False)
781 a87b4824 Michael Hanselmann
    self.lock.Shared(blocking=False)
782 a87b4824 Michael Hanselmann
    self.lock.Unlock(blocking=False)
783 a87b4824 Michael Hanselmann
    self.lock.Close()
784 a87b4824 Michael Hanselmann
785 a87b4824 Michael Hanselmann
  def testCloseShared(self):
786 a87b4824 Michael Hanselmann
    self.lock.Close()
787 a87b4824 Michael Hanselmann
    self.assertRaises(AssertionError, self.lock.Shared, blocking=False)
788 a87b4824 Michael Hanselmann
789 a87b4824 Michael Hanselmann
  def testCloseExclusive(self):
790 a87b4824 Michael Hanselmann
    self.lock.Close()
791 a87b4824 Michael Hanselmann
    self.assertRaises(AssertionError, self.lock.Exclusive, blocking=False)
792 a87b4824 Michael Hanselmann
793 a87b4824 Michael Hanselmann
  def testCloseUnlock(self):
794 a87b4824 Michael Hanselmann
    self.lock.Close()
795 a87b4824 Michael Hanselmann
    self.assertRaises(AssertionError, self.lock.Unlock, blocking=False)
796 a87b4824 Michael Hanselmann
797 a87b4824 Michael Hanselmann
798 739be818 Michael Hanselmann
class TestTimeFunctions(unittest.TestCase):
799 739be818 Michael Hanselmann
  """Test case for time functions"""
800 739be818 Michael Hanselmann
801 739be818 Michael Hanselmann
  def runTest(self):
802 739be818 Michael Hanselmann
    self.assertEqual(utils.SplitTime(1), (1, 0))
803 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(1.5), (1, 500000))
804 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(1218448917.4809151), (1218448917, 480915))
805 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.48012), (123, 480120))
806 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.9996), (123, 999600))
807 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.9995), (123, 999500))
808 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.9994), (123, 999400))
809 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.SplitTime(123.999999999), (123, 999999))
810 45bc5e4a Michael Hanselmann
811 45bc5e4a Michael Hanselmann
    self.assertRaises(AssertionError, utils.SplitTime, -1)
812 739be818 Michael Hanselmann
813 739be818 Michael Hanselmann
    self.assertEqual(utils.MergeTime((1, 0)), 1.0)
814 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.MergeTime((1, 500000)), 1.5)
815 45bc5e4a Michael Hanselmann
    self.assertEqual(utils.MergeTime((1218448917, 500000)), 1218448917.5)
816 739be818 Michael Hanselmann
817 45bc5e4a Michael Hanselmann
    self.assertEqual(round(utils.MergeTime((1218448917, 481000)), 3), 1218448917.481)
818 45bc5e4a Michael Hanselmann
    self.assertEqual(round(utils.MergeTime((1, 801000)), 3), 1.801)
819 739be818 Michael Hanselmann
820 739be818 Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (0, -1))
821 45bc5e4a Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (0, 1000000))
822 45bc5e4a Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (0, 9999999))
823 739be818 Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (-1, 0))
824 739be818 Michael Hanselmann
    self.assertRaises(AssertionError, utils.MergeTime, (-9999, 0))
825 739be818 Michael Hanselmann
826 739be818 Michael Hanselmann
827 a8083063 Iustin Pop
if __name__ == '__main__':
828 a8083063 Iustin Pop
  unittest.main()