Statistics
| Branch: | Tag: | Revision:

root / test / ganeti.utils.io_unittest.py @ 7578ab0a

History | View | Annotate | Download (22.5 kB)

1 3865ca48 Michael Hanselmann
#!/usr/bin/python
2 3865ca48 Michael Hanselmann
#
3 3865ca48 Michael Hanselmann
4 3865ca48 Michael Hanselmann
# Copyright (C) 2006, 2007, 2010, 2011 Google Inc.
5 3865ca48 Michael Hanselmann
#
6 3865ca48 Michael Hanselmann
# This program is free software; you can redistribute it and/or modify
7 3865ca48 Michael Hanselmann
# it under the terms of the GNU General Public License as published by
8 3865ca48 Michael Hanselmann
# the Free Software Foundation; either version 2 of the License, or
9 3865ca48 Michael Hanselmann
# (at your option) any later version.
10 3865ca48 Michael Hanselmann
#
11 3865ca48 Michael Hanselmann
# This program is distributed in the hope that it will be useful, but
12 3865ca48 Michael Hanselmann
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 3865ca48 Michael Hanselmann
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 3865ca48 Michael Hanselmann
# General Public License for more details.
15 3865ca48 Michael Hanselmann
#
16 3865ca48 Michael Hanselmann
# You should have received a copy of the GNU General Public License
17 3865ca48 Michael Hanselmann
# along with this program; if not, write to the Free Software
18 3865ca48 Michael Hanselmann
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 3865ca48 Michael Hanselmann
# 02110-1301, USA.
20 3865ca48 Michael Hanselmann
21 3865ca48 Michael Hanselmann
22 3865ca48 Michael Hanselmann
"""Script for testing ganeti.utils.io"""
23 3865ca48 Michael Hanselmann
24 3865ca48 Michael Hanselmann
import os
25 3865ca48 Michael Hanselmann
import tempfile
26 3865ca48 Michael Hanselmann
import unittest
27 3865ca48 Michael Hanselmann
import shutil
28 3865ca48 Michael Hanselmann
import glob
29 3865ca48 Michael Hanselmann
import time
30 3ae8dd03 Michael Hanselmann
import signal
31 3865ca48 Michael Hanselmann
32 3865ca48 Michael Hanselmann
from ganeti import constants
33 3865ca48 Michael Hanselmann
from ganeti import utils
34 3865ca48 Michael Hanselmann
from ganeti import compat
35 3865ca48 Michael Hanselmann
from ganeti import errors
36 3865ca48 Michael Hanselmann
37 3865ca48 Michael Hanselmann
import testutils
38 3865ca48 Michael Hanselmann
39 3865ca48 Michael Hanselmann
40 3865ca48 Michael Hanselmann
class TestReadFile(testutils.GanetiTestCase):
41 3865ca48 Michael Hanselmann
  def testReadAll(self):
42 3865ca48 Michael Hanselmann
    data = utils.ReadFile(self._TestDataFilename("cert1.pem"))
43 3865ca48 Michael Hanselmann
    self.assertEqual(len(data), 814)
44 3865ca48 Michael Hanselmann
45 3865ca48 Michael Hanselmann
    h = compat.md5_hash()
46 3865ca48 Michael Hanselmann
    h.update(data)
47 3865ca48 Michael Hanselmann
    self.assertEqual(h.hexdigest(), "a491efb3efe56a0535f924d5f8680fd4")
48 3865ca48 Michael Hanselmann
49 3865ca48 Michael Hanselmann
  def testReadSize(self):
50 3865ca48 Michael Hanselmann
    data = utils.ReadFile(self._TestDataFilename("cert1.pem"),
51 3865ca48 Michael Hanselmann
                          size=100)
52 3865ca48 Michael Hanselmann
    self.assertEqual(len(data), 100)
53 3865ca48 Michael Hanselmann
54 3865ca48 Michael Hanselmann
    h = compat.md5_hash()
55 3865ca48 Michael Hanselmann
    h.update(data)
56 3865ca48 Michael Hanselmann
    self.assertEqual(h.hexdigest(), "893772354e4e690b9efd073eed433ce7")
57 3865ca48 Michael Hanselmann
58 3865ca48 Michael Hanselmann
  def testError(self):
59 3865ca48 Michael Hanselmann
    self.assertRaises(EnvironmentError, utils.ReadFile,
60 3865ca48 Michael Hanselmann
                      "/dev/null/does-not-exist")
61 3865ca48 Michael Hanselmann
62 3865ca48 Michael Hanselmann
63 3865ca48 Michael Hanselmann
class TestReadOneLineFile(testutils.GanetiTestCase):
64 3865ca48 Michael Hanselmann
  def setUp(self):
65 3865ca48 Michael Hanselmann
    testutils.GanetiTestCase.setUp(self)
66 3865ca48 Michael Hanselmann
67 3865ca48 Michael Hanselmann
  def testDefault(self):
68 3865ca48 Michael Hanselmann
    data = utils.ReadOneLineFile(self._TestDataFilename("cert1.pem"))
69 3865ca48 Michael Hanselmann
    self.assertEqual(len(data), 27)
70 3865ca48 Michael Hanselmann
    self.assertEqual(data, "-----BEGIN CERTIFICATE-----")
71 3865ca48 Michael Hanselmann
72 3865ca48 Michael Hanselmann
  def testNotStrict(self):
73 3865ca48 Michael Hanselmann
    data = utils.ReadOneLineFile(self._TestDataFilename("cert1.pem"),
74 3865ca48 Michael Hanselmann
                                 strict=False)
75 3865ca48 Michael Hanselmann
    self.assertEqual(len(data), 27)
76 3865ca48 Michael Hanselmann
    self.assertEqual(data, "-----BEGIN CERTIFICATE-----")
77 3865ca48 Michael Hanselmann
78 3865ca48 Michael Hanselmann
  def testStrictFailure(self):
79 3865ca48 Michael Hanselmann
    self.assertRaises(errors.GenericError, utils.ReadOneLineFile,
80 3865ca48 Michael Hanselmann
                      self._TestDataFilename("cert1.pem"), strict=True)
81 3865ca48 Michael Hanselmann
82 3865ca48 Michael Hanselmann
  def testLongLine(self):
83 3865ca48 Michael Hanselmann
    dummydata = (1024 * "Hello World! ")
84 3865ca48 Michael Hanselmann
    myfile = self._CreateTempFile()
85 3865ca48 Michael Hanselmann
    utils.WriteFile(myfile, data=dummydata)
86 3865ca48 Michael Hanselmann
    datastrict = utils.ReadOneLineFile(myfile, strict=True)
87 3865ca48 Michael Hanselmann
    datalax = utils.ReadOneLineFile(myfile, strict=False)
88 3865ca48 Michael Hanselmann
    self.assertEqual(dummydata, datastrict)
89 3865ca48 Michael Hanselmann
    self.assertEqual(dummydata, datalax)
90 3865ca48 Michael Hanselmann
91 3865ca48 Michael Hanselmann
  def testNewline(self):
92 3865ca48 Michael Hanselmann
    myfile = self._CreateTempFile()
93 3865ca48 Michael Hanselmann
    myline = "myline"
94 3865ca48 Michael Hanselmann
    for nl in ["", "\n", "\r\n"]:
95 3865ca48 Michael Hanselmann
      dummydata = "%s%s" % (myline, nl)
96 3865ca48 Michael Hanselmann
      utils.WriteFile(myfile, data=dummydata)
97 3865ca48 Michael Hanselmann
      datalax = utils.ReadOneLineFile(myfile, strict=False)
98 3865ca48 Michael Hanselmann
      self.assertEqual(myline, datalax)
99 3865ca48 Michael Hanselmann
      datastrict = utils.ReadOneLineFile(myfile, strict=True)
100 3865ca48 Michael Hanselmann
      self.assertEqual(myline, datastrict)
101 3865ca48 Michael Hanselmann
102 3865ca48 Michael Hanselmann
  def testWhitespaceAndMultipleLines(self):
103 3865ca48 Michael Hanselmann
    myfile = self._CreateTempFile()
104 3865ca48 Michael Hanselmann
    for nl in ["", "\n", "\r\n"]:
105 3865ca48 Michael Hanselmann
      for ws in [" ", "\t", "\t\t  \t", "\t "]:
106 3865ca48 Michael Hanselmann
        dummydata = (1024 * ("Foo bar baz %s%s" % (ws, nl)))
107 3865ca48 Michael Hanselmann
        utils.WriteFile(myfile, data=dummydata)
108 3865ca48 Michael Hanselmann
        datalax = utils.ReadOneLineFile(myfile, strict=False)
109 3865ca48 Michael Hanselmann
        if nl:
110 3865ca48 Michael Hanselmann
          self.assert_(set("\r\n") & set(dummydata))
111 3865ca48 Michael Hanselmann
          self.assertRaises(errors.GenericError, utils.ReadOneLineFile,
112 3865ca48 Michael Hanselmann
                            myfile, strict=True)
113 3865ca48 Michael Hanselmann
          explen = len("Foo bar baz ") + len(ws)
114 3865ca48 Michael Hanselmann
          self.assertEqual(len(datalax), explen)
115 3865ca48 Michael Hanselmann
          self.assertEqual(datalax, dummydata[:explen])
116 3865ca48 Michael Hanselmann
          self.assertFalse(set("\r\n") & set(datalax))
117 3865ca48 Michael Hanselmann
        else:
118 3865ca48 Michael Hanselmann
          datastrict = utils.ReadOneLineFile(myfile, strict=True)
119 3865ca48 Michael Hanselmann
          self.assertEqual(dummydata, datastrict)
120 3865ca48 Michael Hanselmann
          self.assertEqual(dummydata, datalax)
121 3865ca48 Michael Hanselmann
122 3865ca48 Michael Hanselmann
  def testEmptylines(self):
123 3865ca48 Michael Hanselmann
    myfile = self._CreateTempFile()
124 3865ca48 Michael Hanselmann
    myline = "myline"
125 3865ca48 Michael Hanselmann
    for nl in ["\n", "\r\n"]:
126 3865ca48 Michael Hanselmann
      for ol in ["", "otherline"]:
127 3865ca48 Michael Hanselmann
        dummydata = "%s%s%s%s%s%s" % (nl, nl, myline, nl, ol, nl)
128 3865ca48 Michael Hanselmann
        utils.WriteFile(myfile, data=dummydata)
129 3865ca48 Michael Hanselmann
        self.assert_(set("\r\n") & set(dummydata))
130 3865ca48 Michael Hanselmann
        datalax = utils.ReadOneLineFile(myfile, strict=False)
131 3865ca48 Michael Hanselmann
        self.assertEqual(myline, datalax)
132 3865ca48 Michael Hanselmann
        if ol:
133 3865ca48 Michael Hanselmann
          self.assertRaises(errors.GenericError, utils.ReadOneLineFile,
134 3865ca48 Michael Hanselmann
                            myfile, strict=True)
135 3865ca48 Michael Hanselmann
        else:
136 3865ca48 Michael Hanselmann
          datastrict = utils.ReadOneLineFile(myfile, strict=True)
137 3865ca48 Michael Hanselmann
          self.assertEqual(myline, datastrict)
138 3865ca48 Michael Hanselmann
139 3865ca48 Michael Hanselmann
  def testEmptyfile(self):
140 3865ca48 Michael Hanselmann
    myfile = self._CreateTempFile()
141 3865ca48 Michael Hanselmann
    self.assertRaises(errors.GenericError, utils.ReadOneLineFile, myfile)
142 3865ca48 Michael Hanselmann
143 3865ca48 Michael Hanselmann
144 3865ca48 Michael Hanselmann
class TestTimestampForFilename(unittest.TestCase):
145 3865ca48 Michael Hanselmann
  def test(self):
146 3865ca48 Michael Hanselmann
    self.assert_("." not in utils.TimestampForFilename())
147 3865ca48 Michael Hanselmann
    self.assert_(":" not in utils.TimestampForFilename())
148 3865ca48 Michael Hanselmann
149 3865ca48 Michael Hanselmann
150 3865ca48 Michael Hanselmann
class TestCreateBackup(testutils.GanetiTestCase):
151 3865ca48 Michael Hanselmann
  def setUp(self):
152 3865ca48 Michael Hanselmann
    testutils.GanetiTestCase.setUp(self)
153 3865ca48 Michael Hanselmann
154 3865ca48 Michael Hanselmann
    self.tmpdir = tempfile.mkdtemp()
155 3865ca48 Michael Hanselmann
156 3865ca48 Michael Hanselmann
  def tearDown(self):
157 3865ca48 Michael Hanselmann
    testutils.GanetiTestCase.tearDown(self)
158 3865ca48 Michael Hanselmann
159 3865ca48 Michael Hanselmann
    shutil.rmtree(self.tmpdir)
160 3865ca48 Michael Hanselmann
161 3865ca48 Michael Hanselmann
  def testEmpty(self):
162 3865ca48 Michael Hanselmann
    filename = utils.PathJoin(self.tmpdir, "config.data")
163 3865ca48 Michael Hanselmann
    utils.WriteFile(filename, data="")
164 3865ca48 Michael Hanselmann
    bname = utils.CreateBackup(filename)
165 3865ca48 Michael Hanselmann
    self.assertFileContent(bname, "")
166 3865ca48 Michael Hanselmann
    self.assertEqual(len(glob.glob("%s*" % filename)), 2)
167 3865ca48 Michael Hanselmann
    utils.CreateBackup(filename)
168 3865ca48 Michael Hanselmann
    self.assertEqual(len(glob.glob("%s*" % filename)), 3)
169 3865ca48 Michael Hanselmann
    utils.CreateBackup(filename)
170 3865ca48 Michael Hanselmann
    self.assertEqual(len(glob.glob("%s*" % filename)), 4)
171 3865ca48 Michael Hanselmann
172 3865ca48 Michael Hanselmann
    fifoname = utils.PathJoin(self.tmpdir, "fifo")
173 3865ca48 Michael Hanselmann
    os.mkfifo(fifoname)
174 3865ca48 Michael Hanselmann
    self.assertRaises(errors.ProgrammerError, utils.CreateBackup, fifoname)
175 3865ca48 Michael Hanselmann
176 3865ca48 Michael Hanselmann
  def testContent(self):
177 3865ca48 Michael Hanselmann
    bkpcount = 0
178 3865ca48 Michael Hanselmann
    for data in ["", "X", "Hello World!\n" * 100, "Binary data\0\x01\x02\n"]:
179 3865ca48 Michael Hanselmann
      for rep in [1, 2, 10, 127]:
180 3865ca48 Michael Hanselmann
        testdata = data * rep
181 3865ca48 Michael Hanselmann
182 3865ca48 Michael Hanselmann
        filename = utils.PathJoin(self.tmpdir, "test.data_")
183 3865ca48 Michael Hanselmann
        utils.WriteFile(filename, data=testdata)
184 3865ca48 Michael Hanselmann
        self.assertFileContent(filename, testdata)
185 3865ca48 Michael Hanselmann
186 3865ca48 Michael Hanselmann
        for _ in range(3):
187 3865ca48 Michael Hanselmann
          bname = utils.CreateBackup(filename)
188 3865ca48 Michael Hanselmann
          bkpcount += 1
189 3865ca48 Michael Hanselmann
          self.assertFileContent(bname, testdata)
190 3865ca48 Michael Hanselmann
          self.assertEqual(len(glob.glob("%s*" % filename)), 1 + bkpcount)
191 3865ca48 Michael Hanselmann
192 3865ca48 Michael Hanselmann
193 3865ca48 Michael Hanselmann
class TestListVisibleFiles(unittest.TestCase):
194 3865ca48 Michael Hanselmann
  """Test case for ListVisibleFiles"""
195 3865ca48 Michael Hanselmann
196 3865ca48 Michael Hanselmann
  def setUp(self):
197 3865ca48 Michael Hanselmann
    self.path = tempfile.mkdtemp()
198 3865ca48 Michael Hanselmann
199 3865ca48 Michael Hanselmann
  def tearDown(self):
200 3865ca48 Michael Hanselmann
    shutil.rmtree(self.path)
201 3865ca48 Michael Hanselmann
202 3865ca48 Michael Hanselmann
  def _CreateFiles(self, files):
203 3865ca48 Michael Hanselmann
    for name in files:
204 3865ca48 Michael Hanselmann
      utils.WriteFile(os.path.join(self.path, name), data="test")
205 3865ca48 Michael Hanselmann
206 3865ca48 Michael Hanselmann
  def _test(self, files, expected):
207 3865ca48 Michael Hanselmann
    self._CreateFiles(files)
208 3865ca48 Michael Hanselmann
    found = utils.ListVisibleFiles(self.path)
209 3865ca48 Michael Hanselmann
    self.assertEqual(set(found), set(expected))
210 3865ca48 Michael Hanselmann
211 3865ca48 Michael Hanselmann
  def testAllVisible(self):
212 3865ca48 Michael Hanselmann
    files = ["a", "b", "c"]
213 3865ca48 Michael Hanselmann
    expected = files
214 3865ca48 Michael Hanselmann
    self._test(files, expected)
215 3865ca48 Michael Hanselmann
216 3865ca48 Michael Hanselmann
  def testNoneVisible(self):
217 3865ca48 Michael Hanselmann
    files = [".a", ".b", ".c"]
218 3865ca48 Michael Hanselmann
    expected = []
219 3865ca48 Michael Hanselmann
    self._test(files, expected)
220 3865ca48 Michael Hanselmann
221 3865ca48 Michael Hanselmann
  def testSomeVisible(self):
222 3865ca48 Michael Hanselmann
    files = ["a", "b", ".c"]
223 3865ca48 Michael Hanselmann
    expected = ["a", "b"]
224 3865ca48 Michael Hanselmann
    self._test(files, expected)
225 3865ca48 Michael Hanselmann
226 3865ca48 Michael Hanselmann
  def testNonAbsolutePath(self):
227 3865ca48 Michael Hanselmann
    self.failUnlessRaises(errors.ProgrammerError, utils.ListVisibleFiles,
228 3865ca48 Michael Hanselmann
                          "abc")
229 3865ca48 Michael Hanselmann
230 3865ca48 Michael Hanselmann
  def testNonNormalizedPath(self):
231 3865ca48 Michael Hanselmann
    self.failUnlessRaises(errors.ProgrammerError, utils.ListVisibleFiles,
232 3865ca48 Michael Hanselmann
                          "/bin/../tmp")
233 3865ca48 Michael Hanselmann
234 3865ca48 Michael Hanselmann
235 3865ca48 Michael Hanselmann
class TestWriteFile(unittest.TestCase):
236 3865ca48 Michael Hanselmann
  def setUp(self):
237 3865ca48 Michael Hanselmann
    self.tfile = tempfile.NamedTemporaryFile()
238 3865ca48 Michael Hanselmann
    self.did_pre = False
239 3865ca48 Michael Hanselmann
    self.did_post = False
240 3865ca48 Michael Hanselmann
    self.did_write = False
241 3865ca48 Michael Hanselmann
242 3865ca48 Michael Hanselmann
  def markPre(self, fd):
243 3865ca48 Michael Hanselmann
    self.did_pre = True
244 3865ca48 Michael Hanselmann
245 3865ca48 Michael Hanselmann
  def markPost(self, fd):
246 3865ca48 Michael Hanselmann
    self.did_post = True
247 3865ca48 Michael Hanselmann
248 3865ca48 Michael Hanselmann
  def markWrite(self, fd):
249 3865ca48 Michael Hanselmann
    self.did_write = True
250 3865ca48 Michael Hanselmann
251 3865ca48 Michael Hanselmann
  def testWrite(self):
252 3865ca48 Michael Hanselmann
    data = "abc"
253 3865ca48 Michael Hanselmann
    utils.WriteFile(self.tfile.name, data=data)
254 3865ca48 Michael Hanselmann
    self.assertEqual(utils.ReadFile(self.tfile.name), data)
255 3865ca48 Michael Hanselmann
256 3865ca48 Michael Hanselmann
  def testErrors(self):
257 3865ca48 Michael Hanselmann
    self.assertRaises(errors.ProgrammerError, utils.WriteFile,
258 3865ca48 Michael Hanselmann
                      self.tfile.name, data="test", fn=lambda fd: None)
259 3865ca48 Michael Hanselmann
    self.assertRaises(errors.ProgrammerError, utils.WriteFile, self.tfile.name)
260 3865ca48 Michael Hanselmann
    self.assertRaises(errors.ProgrammerError, utils.WriteFile,
261 3865ca48 Michael Hanselmann
                      self.tfile.name, data="test", atime=0)
262 3865ca48 Michael Hanselmann
263 3865ca48 Michael Hanselmann
  def testCalls(self):
264 3865ca48 Michael Hanselmann
    utils.WriteFile(self.tfile.name, fn=self.markWrite,
265 3865ca48 Michael Hanselmann
                    prewrite=self.markPre, postwrite=self.markPost)
266 3865ca48 Michael Hanselmann
    self.assertTrue(self.did_pre)
267 3865ca48 Michael Hanselmann
    self.assertTrue(self.did_post)
268 3865ca48 Michael Hanselmann
    self.assertTrue(self.did_write)
269 3865ca48 Michael Hanselmann
270 3865ca48 Michael Hanselmann
  def testDryRun(self):
271 3865ca48 Michael Hanselmann
    orig = "abc"
272 3865ca48 Michael Hanselmann
    self.tfile.write(orig)
273 3865ca48 Michael Hanselmann
    self.tfile.flush()
274 3865ca48 Michael Hanselmann
    utils.WriteFile(self.tfile.name, data="hello", dry_run=True)
275 3865ca48 Michael Hanselmann
    self.assertEqual(utils.ReadFile(self.tfile.name), orig)
276 3865ca48 Michael Hanselmann
277 3865ca48 Michael Hanselmann
  def testTimes(self):
278 3865ca48 Michael Hanselmann
    f = self.tfile.name
279 3865ca48 Michael Hanselmann
    for at, mt in [(0, 0), (1000, 1000), (2000, 3000),
280 3865ca48 Michael Hanselmann
                   (int(time.time()), 5000)]:
281 3865ca48 Michael Hanselmann
      utils.WriteFile(f, data="hello", atime=at, mtime=mt)
282 3865ca48 Michael Hanselmann
      st = os.stat(f)
283 3865ca48 Michael Hanselmann
      self.assertEqual(st.st_atime, at)
284 3865ca48 Michael Hanselmann
      self.assertEqual(st.st_mtime, mt)
285 3865ca48 Michael Hanselmann
286 3865ca48 Michael Hanselmann
  def testNoClose(self):
287 3865ca48 Michael Hanselmann
    data = "hello"
288 3865ca48 Michael Hanselmann
    self.assertEqual(utils.WriteFile(self.tfile.name, data="abc"), None)
289 3865ca48 Michael Hanselmann
    fd = utils.WriteFile(self.tfile.name, data=data, close=False)
290 3865ca48 Michael Hanselmann
    try:
291 3865ca48 Michael Hanselmann
      os.lseek(fd, 0, 0)
292 3865ca48 Michael Hanselmann
      self.assertEqual(os.read(fd, 4096), data)
293 3865ca48 Michael Hanselmann
    finally:
294 3865ca48 Michael Hanselmann
      os.close(fd)
295 3865ca48 Michael Hanselmann
296 3865ca48 Michael Hanselmann
297 3865ca48 Michael Hanselmann
class TestFileID(testutils.GanetiTestCase):
298 3865ca48 Michael Hanselmann
  def testEquality(self):
299 3865ca48 Michael Hanselmann
    name = self._CreateTempFile()
300 3865ca48 Michael Hanselmann
    oldi = utils.GetFileID(path=name)
301 3865ca48 Michael Hanselmann
    self.failUnless(utils.VerifyFileID(oldi, oldi))
302 3865ca48 Michael Hanselmann
303 3865ca48 Michael Hanselmann
  def testUpdate(self):
304 3865ca48 Michael Hanselmann
    name = self._CreateTempFile()
305 3865ca48 Michael Hanselmann
    oldi = utils.GetFileID(path=name)
306 3865ca48 Michael Hanselmann
    os.utime(name, None)
307 3865ca48 Michael Hanselmann
    fd = os.open(name, os.O_RDWR)
308 3865ca48 Michael Hanselmann
    try:
309 3865ca48 Michael Hanselmann
      newi = utils.GetFileID(fd=fd)
310 3865ca48 Michael Hanselmann
      self.failUnless(utils.VerifyFileID(oldi, newi))
311 3865ca48 Michael Hanselmann
      self.failUnless(utils.VerifyFileID(newi, oldi))
312 3865ca48 Michael Hanselmann
    finally:
313 3865ca48 Michael Hanselmann
      os.close(fd)
314 3865ca48 Michael Hanselmann
315 3865ca48 Michael Hanselmann
  def testWriteFile(self):
316 3865ca48 Michael Hanselmann
    name = self._CreateTempFile()
317 3865ca48 Michael Hanselmann
    oldi = utils.GetFileID(path=name)
318 3865ca48 Michael Hanselmann
    mtime = oldi[2]
319 3865ca48 Michael Hanselmann
    os.utime(name, (mtime + 10, mtime + 10))
320 3865ca48 Michael Hanselmann
    self.assertRaises(errors.LockError, utils.SafeWriteFile, name,
321 3865ca48 Michael Hanselmann
                      oldi, data="")
322 3865ca48 Michael Hanselmann
    os.utime(name, (mtime - 10, mtime - 10))
323 3865ca48 Michael Hanselmann
    utils.SafeWriteFile(name, oldi, data="")
324 3865ca48 Michael Hanselmann
    oldi = utils.GetFileID(path=name)
325 3865ca48 Michael Hanselmann
    mtime = oldi[2]
326 3865ca48 Michael Hanselmann
    os.utime(name, (mtime + 10, mtime + 10))
327 3865ca48 Michael Hanselmann
    # this doesn't raise, since we passed None
328 3865ca48 Michael Hanselmann
    utils.SafeWriteFile(name, None, data="")
329 3865ca48 Michael Hanselmann
330 3865ca48 Michael Hanselmann
  def testError(self):
331 3865ca48 Michael Hanselmann
    t = tempfile.NamedTemporaryFile()
332 3865ca48 Michael Hanselmann
    self.assertRaises(errors.ProgrammerError, utils.GetFileID,
333 3865ca48 Michael Hanselmann
                      path=t.name, fd=t.fileno())
334 3865ca48 Michael Hanselmann
335 3865ca48 Michael Hanselmann
336 3865ca48 Michael Hanselmann
class TestRemoveFile(unittest.TestCase):
337 3865ca48 Michael Hanselmann
  """Test case for the RemoveFile function"""
338 3865ca48 Michael Hanselmann
339 3865ca48 Michael Hanselmann
  def setUp(self):
340 3865ca48 Michael Hanselmann
    """Create a temp dir and file for each case"""
341 3865ca48 Michael Hanselmann
    self.tmpdir = tempfile.mkdtemp('', 'ganeti-unittest-')
342 3865ca48 Michael Hanselmann
    fd, self.tmpfile = tempfile.mkstemp('', '', self.tmpdir)
343 3865ca48 Michael Hanselmann
    os.close(fd)
344 3865ca48 Michael Hanselmann
345 3865ca48 Michael Hanselmann
  def tearDown(self):
346 3865ca48 Michael Hanselmann
    if os.path.exists(self.tmpfile):
347 3865ca48 Michael Hanselmann
      os.unlink(self.tmpfile)
348 3865ca48 Michael Hanselmann
    os.rmdir(self.tmpdir)
349 3865ca48 Michael Hanselmann
350 3865ca48 Michael Hanselmann
  def testIgnoreDirs(self):
351 3865ca48 Michael Hanselmann
    """Test that RemoveFile() ignores directories"""
352 3865ca48 Michael Hanselmann
    self.assertEqual(None, utils.RemoveFile(self.tmpdir))
353 3865ca48 Michael Hanselmann
354 3865ca48 Michael Hanselmann
  def testIgnoreNotExisting(self):
355 3865ca48 Michael Hanselmann
    """Test that RemoveFile() ignores non-existing files"""
356 3865ca48 Michael Hanselmann
    utils.RemoveFile(self.tmpfile)
357 3865ca48 Michael Hanselmann
    utils.RemoveFile(self.tmpfile)
358 3865ca48 Michael Hanselmann
359 3865ca48 Michael Hanselmann
  def testRemoveFile(self):
360 3865ca48 Michael Hanselmann
    """Test that RemoveFile does remove a file"""
361 3865ca48 Michael Hanselmann
    utils.RemoveFile(self.tmpfile)
362 3865ca48 Michael Hanselmann
    if os.path.exists(self.tmpfile):
363 3865ca48 Michael Hanselmann
      self.fail("File '%s' not removed" % self.tmpfile)
364 3865ca48 Michael Hanselmann
365 3865ca48 Michael Hanselmann
  def testRemoveSymlink(self):
366 3865ca48 Michael Hanselmann
    """Test that RemoveFile does remove symlinks"""
367 3865ca48 Michael Hanselmann
    symlink = self.tmpdir + "/symlink"
368 3865ca48 Michael Hanselmann
    os.symlink("no-such-file", symlink)
369 3865ca48 Michael Hanselmann
    utils.RemoveFile(symlink)
370 3865ca48 Michael Hanselmann
    if os.path.exists(symlink):
371 3865ca48 Michael Hanselmann
      self.fail("File '%s' not removed" % symlink)
372 3865ca48 Michael Hanselmann
    os.symlink(self.tmpfile, symlink)
373 3865ca48 Michael Hanselmann
    utils.RemoveFile(symlink)
374 3865ca48 Michael Hanselmann
    if os.path.exists(symlink):
375 3865ca48 Michael Hanselmann
      self.fail("File '%s' not removed" % symlink)
376 3865ca48 Michael Hanselmann
377 3865ca48 Michael Hanselmann
378 3865ca48 Michael Hanselmann
class TestRemoveDir(unittest.TestCase):
379 3865ca48 Michael Hanselmann
  def setUp(self):
380 3865ca48 Michael Hanselmann
    self.tmpdir = tempfile.mkdtemp()
381 3865ca48 Michael Hanselmann
382 3865ca48 Michael Hanselmann
  def tearDown(self):
383 3865ca48 Michael Hanselmann
    try:
384 3865ca48 Michael Hanselmann
      shutil.rmtree(self.tmpdir)
385 3865ca48 Michael Hanselmann
    except EnvironmentError:
386 3865ca48 Michael Hanselmann
      pass
387 3865ca48 Michael Hanselmann
388 3865ca48 Michael Hanselmann
  def testEmptyDir(self):
389 3865ca48 Michael Hanselmann
    utils.RemoveDir(self.tmpdir)
390 3865ca48 Michael Hanselmann
    self.assertFalse(os.path.isdir(self.tmpdir))
391 3865ca48 Michael Hanselmann
392 3865ca48 Michael Hanselmann
  def testNonEmptyDir(self):
393 3865ca48 Michael Hanselmann
    self.tmpfile = os.path.join(self.tmpdir, "test1")
394 3865ca48 Michael Hanselmann
    open(self.tmpfile, "w").close()
395 3865ca48 Michael Hanselmann
    self.assertRaises(EnvironmentError, utils.RemoveDir, self.tmpdir)
396 3865ca48 Michael Hanselmann
397 3865ca48 Michael Hanselmann
398 3865ca48 Michael Hanselmann
class TestRename(unittest.TestCase):
399 3865ca48 Michael Hanselmann
  """Test case for RenameFile"""
400 3865ca48 Michael Hanselmann
401 3865ca48 Michael Hanselmann
  def setUp(self):
402 3865ca48 Michael Hanselmann
    """Create a temporary directory"""
403 3865ca48 Michael Hanselmann
    self.tmpdir = tempfile.mkdtemp()
404 3865ca48 Michael Hanselmann
    self.tmpfile = os.path.join(self.tmpdir, "test1")
405 3865ca48 Michael Hanselmann
406 3865ca48 Michael Hanselmann
    # Touch the file
407 3865ca48 Michael Hanselmann
    open(self.tmpfile, "w").close()
408 3865ca48 Michael Hanselmann
409 3865ca48 Michael Hanselmann
  def tearDown(self):
410 3865ca48 Michael Hanselmann
    """Remove temporary directory"""
411 3865ca48 Michael Hanselmann
    shutil.rmtree(self.tmpdir)
412 3865ca48 Michael Hanselmann
413 3865ca48 Michael Hanselmann
  def testSimpleRename1(self):
414 3865ca48 Michael Hanselmann
    """Simple rename 1"""
415 3865ca48 Michael Hanselmann
    utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "xyz"))
416 3865ca48 Michael Hanselmann
    self.assert_(os.path.isfile(os.path.join(self.tmpdir, "xyz")))
417 3865ca48 Michael Hanselmann
418 3865ca48 Michael Hanselmann
  def testSimpleRename2(self):
419 3865ca48 Michael Hanselmann
    """Simple rename 2"""
420 3865ca48 Michael Hanselmann
    utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "xyz"),
421 3865ca48 Michael Hanselmann
                     mkdir=True)
422 3865ca48 Michael Hanselmann
    self.assert_(os.path.isfile(os.path.join(self.tmpdir, "xyz")))
423 3865ca48 Michael Hanselmann
424 3865ca48 Michael Hanselmann
  def testRenameMkdir(self):
425 3865ca48 Michael Hanselmann
    """Rename with mkdir"""
426 3865ca48 Michael Hanselmann
    utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "test/xyz"),
427 3865ca48 Michael Hanselmann
                     mkdir=True)
428 3865ca48 Michael Hanselmann
    self.assert_(os.path.isdir(os.path.join(self.tmpdir, "test")))
429 3865ca48 Michael Hanselmann
    self.assert_(os.path.isfile(os.path.join(self.tmpdir, "test/xyz")))
430 3865ca48 Michael Hanselmann
431 3865ca48 Michael Hanselmann
    utils.RenameFile(os.path.join(self.tmpdir, "test/xyz"),
432 3865ca48 Michael Hanselmann
                     os.path.join(self.tmpdir, "test/foo/bar/baz"),
433 3865ca48 Michael Hanselmann
                     mkdir=True)
434 3865ca48 Michael Hanselmann
    self.assert_(os.path.isdir(os.path.join(self.tmpdir, "test")))
435 3865ca48 Michael Hanselmann
    self.assert_(os.path.isdir(os.path.join(self.tmpdir, "test/foo/bar")))
436 3865ca48 Michael Hanselmann
    self.assert_(os.path.isfile(os.path.join(self.tmpdir, "test/foo/bar/baz")))
437 3865ca48 Michael Hanselmann
438 3865ca48 Michael Hanselmann
439 3865ca48 Michael Hanselmann
class TestMakedirs(unittest.TestCase):
440 3865ca48 Michael Hanselmann
  def setUp(self):
441 3865ca48 Michael Hanselmann
    self.tmpdir = tempfile.mkdtemp()
442 3865ca48 Michael Hanselmann
443 3865ca48 Michael Hanselmann
  def tearDown(self):
444 3865ca48 Michael Hanselmann
    shutil.rmtree(self.tmpdir)
445 3865ca48 Michael Hanselmann
446 3865ca48 Michael Hanselmann
  def testNonExisting(self):
447 3865ca48 Michael Hanselmann
    path = utils.PathJoin(self.tmpdir, "foo")
448 3865ca48 Michael Hanselmann
    utils.Makedirs(path)
449 3865ca48 Michael Hanselmann
    self.assert_(os.path.isdir(path))
450 3865ca48 Michael Hanselmann
451 3865ca48 Michael Hanselmann
  def testExisting(self):
452 3865ca48 Michael Hanselmann
    path = utils.PathJoin(self.tmpdir, "foo")
453 3865ca48 Michael Hanselmann
    os.mkdir(path)
454 3865ca48 Michael Hanselmann
    utils.Makedirs(path)
455 3865ca48 Michael Hanselmann
    self.assert_(os.path.isdir(path))
456 3865ca48 Michael Hanselmann
457 3865ca48 Michael Hanselmann
  def testRecursiveNonExisting(self):
458 3865ca48 Michael Hanselmann
    path = utils.PathJoin(self.tmpdir, "foo/bar/baz")
459 3865ca48 Michael Hanselmann
    utils.Makedirs(path)
460 3865ca48 Michael Hanselmann
    self.assert_(os.path.isdir(path))
461 3865ca48 Michael Hanselmann
462 3865ca48 Michael Hanselmann
  def testRecursiveExisting(self):
463 3865ca48 Michael Hanselmann
    path = utils.PathJoin(self.tmpdir, "B/moo/xyz")
464 3865ca48 Michael Hanselmann
    self.assertFalse(os.path.exists(path))
465 3865ca48 Michael Hanselmann
    os.mkdir(utils.PathJoin(self.tmpdir, "B"))
466 3865ca48 Michael Hanselmann
    utils.Makedirs(path)
467 3865ca48 Michael Hanselmann
    self.assert_(os.path.isdir(path))
468 3865ca48 Michael Hanselmann
469 3865ca48 Michael Hanselmann
470 3865ca48 Michael Hanselmann
class TestEnsureDirs(unittest.TestCase):
471 3865ca48 Michael Hanselmann
  """Tests for EnsureDirs"""
472 3865ca48 Michael Hanselmann
473 3865ca48 Michael Hanselmann
  def setUp(self):
474 3865ca48 Michael Hanselmann
    self.dir = tempfile.mkdtemp()
475 3865ca48 Michael Hanselmann
    self.old_umask = os.umask(0777)
476 3865ca48 Michael Hanselmann
477 3865ca48 Michael Hanselmann
  def testEnsureDirs(self):
478 3865ca48 Michael Hanselmann
    utils.EnsureDirs([
479 3865ca48 Michael Hanselmann
        (utils.PathJoin(self.dir, "foo"), 0777),
480 3865ca48 Michael Hanselmann
        (utils.PathJoin(self.dir, "bar"), 0000),
481 3865ca48 Michael Hanselmann
        ])
482 3865ca48 Michael Hanselmann
    self.assertEquals(os.stat(utils.PathJoin(self.dir, "foo"))[0] & 0777, 0777)
483 3865ca48 Michael Hanselmann
    self.assertEquals(os.stat(utils.PathJoin(self.dir, "bar"))[0] & 0777, 0000)
484 3865ca48 Michael Hanselmann
485 3865ca48 Michael Hanselmann
  def tearDown(self):
486 3865ca48 Michael Hanselmann
    os.rmdir(utils.PathJoin(self.dir, "foo"))
487 3865ca48 Michael Hanselmann
    os.rmdir(utils.PathJoin(self.dir, "bar"))
488 3865ca48 Michael Hanselmann
    os.rmdir(self.dir)
489 3865ca48 Michael Hanselmann
    os.umask(self.old_umask)
490 3865ca48 Michael Hanselmann
491 3865ca48 Michael Hanselmann
492 3865ca48 Michael Hanselmann
class TestIsNormAbsPath(unittest.TestCase):
493 3865ca48 Michael Hanselmann
  """Testing case for IsNormAbsPath"""
494 3865ca48 Michael Hanselmann
495 3865ca48 Michael Hanselmann
  def _pathTestHelper(self, path, result):
496 3865ca48 Michael Hanselmann
    if result:
497 3865ca48 Michael Hanselmann
      self.assert_(utils.IsNormAbsPath(path),
498 3865ca48 Michael Hanselmann
          "Path %s should result absolute and normalized" % path)
499 3865ca48 Michael Hanselmann
    else:
500 3865ca48 Michael Hanselmann
      self.assertFalse(utils.IsNormAbsPath(path),
501 3865ca48 Michael Hanselmann
          "Path %s should not result absolute and normalized" % path)
502 3865ca48 Michael Hanselmann
503 3865ca48 Michael Hanselmann
  def testBase(self):
504 3865ca48 Michael Hanselmann
    self._pathTestHelper("/etc", True)
505 3865ca48 Michael Hanselmann
    self._pathTestHelper("/srv", True)
506 3865ca48 Michael Hanselmann
    self._pathTestHelper("etc", False)
507 3865ca48 Michael Hanselmann
    self._pathTestHelper("/etc/../root", False)
508 3865ca48 Michael Hanselmann
    self._pathTestHelper("/etc/", False)
509 3865ca48 Michael Hanselmann
510 3865ca48 Michael Hanselmann
511 3865ca48 Michael Hanselmann
class TestPathJoin(unittest.TestCase):
512 3865ca48 Michael Hanselmann
  """Testing case for PathJoin"""
513 3865ca48 Michael Hanselmann
514 3865ca48 Michael Hanselmann
  def testBasicItems(self):
515 3865ca48 Michael Hanselmann
    mlist = ["/a", "b", "c"]
516 3865ca48 Michael Hanselmann
    self.failUnlessEqual(utils.PathJoin(*mlist), "/".join(mlist))
517 3865ca48 Michael Hanselmann
518 3865ca48 Michael Hanselmann
  def testNonAbsPrefix(self):
519 3865ca48 Michael Hanselmann
    self.failUnlessRaises(ValueError, utils.PathJoin, "a", "b")
520 3865ca48 Michael Hanselmann
521 3865ca48 Michael Hanselmann
  def testBackTrack(self):
522 3865ca48 Michael Hanselmann
    self.failUnlessRaises(ValueError, utils.PathJoin, "/a", "b/../c")
523 3865ca48 Michael Hanselmann
524 3865ca48 Michael Hanselmann
  def testMultiAbs(self):
525 3865ca48 Michael Hanselmann
    self.failUnlessRaises(ValueError, utils.PathJoin, "/a", "/b")
526 3865ca48 Michael Hanselmann
527 3865ca48 Michael Hanselmann
528 3865ca48 Michael Hanselmann
class TestTailFile(testutils.GanetiTestCase):
529 3865ca48 Michael Hanselmann
  """Test case for the TailFile function"""
530 3865ca48 Michael Hanselmann
531 3865ca48 Michael Hanselmann
  def testEmpty(self):
532 3865ca48 Michael Hanselmann
    fname = self._CreateTempFile()
533 3865ca48 Michael Hanselmann
    self.failUnlessEqual(utils.TailFile(fname), [])
534 3865ca48 Michael Hanselmann
    self.failUnlessEqual(utils.TailFile(fname, lines=25), [])
535 3865ca48 Michael Hanselmann
536 3865ca48 Michael Hanselmann
  def testAllLines(self):
537 3865ca48 Michael Hanselmann
    data = ["test %d" % i for i in range(30)]
538 3865ca48 Michael Hanselmann
    for i in range(30):
539 3865ca48 Michael Hanselmann
      fname = self._CreateTempFile()
540 3865ca48 Michael Hanselmann
      fd = open(fname, "w")
541 3865ca48 Michael Hanselmann
      fd.write("\n".join(data[:i]))
542 3865ca48 Michael Hanselmann
      if i > 0:
543 3865ca48 Michael Hanselmann
        fd.write("\n")
544 3865ca48 Michael Hanselmann
      fd.close()
545 3865ca48 Michael Hanselmann
      self.failUnlessEqual(utils.TailFile(fname, lines=i), data[:i])
546 3865ca48 Michael Hanselmann
547 3865ca48 Michael Hanselmann
  def testPartialLines(self):
548 3865ca48 Michael Hanselmann
    data = ["test %d" % i for i in range(30)]
549 3865ca48 Michael Hanselmann
    fname = self._CreateTempFile()
550 3865ca48 Michael Hanselmann
    fd = open(fname, "w")
551 3865ca48 Michael Hanselmann
    fd.write("\n".join(data))
552 3865ca48 Michael Hanselmann
    fd.write("\n")
553 3865ca48 Michael Hanselmann
    fd.close()
554 3865ca48 Michael Hanselmann
    for i in range(1, 30):
555 3865ca48 Michael Hanselmann
      self.failUnlessEqual(utils.TailFile(fname, lines=i), data[-i:])
556 3865ca48 Michael Hanselmann
557 3865ca48 Michael Hanselmann
  def testBigFile(self):
558 3865ca48 Michael Hanselmann
    data = ["test %d" % i for i in range(30)]
559 3865ca48 Michael Hanselmann
    fname = self._CreateTempFile()
560 3865ca48 Michael Hanselmann
    fd = open(fname, "w")
561 3865ca48 Michael Hanselmann
    fd.write("X" * 1048576)
562 3865ca48 Michael Hanselmann
    fd.write("\n")
563 3865ca48 Michael Hanselmann
    fd.write("\n".join(data))
564 3865ca48 Michael Hanselmann
    fd.write("\n")
565 3865ca48 Michael Hanselmann
    fd.close()
566 3865ca48 Michael Hanselmann
    for i in range(1, 30):
567 3865ca48 Michael Hanselmann
      self.failUnlessEqual(utils.TailFile(fname, lines=i), data[-i:])
568 3865ca48 Michael Hanselmann
569 3865ca48 Michael Hanselmann
570 3865ca48 Michael Hanselmann
class TestPidFileFunctions(unittest.TestCase):
571 79b60c1c Michael Hanselmann
  """Tests for WritePidFile and ReadPidFile"""
572 3865ca48 Michael Hanselmann
573 3865ca48 Michael Hanselmann
  def setUp(self):
574 3865ca48 Michael Hanselmann
    self.dir = tempfile.mkdtemp()
575 3865ca48 Michael Hanselmann
    self.f_dpn = lambda name: os.path.join(self.dir, "%s.pid" % name)
576 3865ca48 Michael Hanselmann
577 3865ca48 Michael Hanselmann
  def testPidFileFunctions(self):
578 3865ca48 Michael Hanselmann
    pid_file = self.f_dpn('test')
579 3865ca48 Michael Hanselmann
    fd = utils.WritePidFile(self.f_dpn('test'))
580 3865ca48 Michael Hanselmann
    self.failUnless(os.path.exists(pid_file),
581 3865ca48 Michael Hanselmann
                    "PID file should have been created")
582 3865ca48 Michael Hanselmann
    read_pid = utils.ReadPidFile(pid_file)
583 3865ca48 Michael Hanselmann
    self.failUnlessEqual(read_pid, os.getpid())
584 3865ca48 Michael Hanselmann
    self.failUnless(utils.IsProcessAlive(read_pid))
585 3865ca48 Michael Hanselmann
    self.failUnlessRaises(errors.LockError, utils.WritePidFile,
586 3865ca48 Michael Hanselmann
                          self.f_dpn('test'))
587 3865ca48 Michael Hanselmann
    os.close(fd)
588 79b60c1c Michael Hanselmann
    utils.RemoveFile(self.f_dpn("test"))
589 3865ca48 Michael Hanselmann
    self.failIf(os.path.exists(pid_file),
590 3865ca48 Michael Hanselmann
                "PID file should not exist anymore")
591 3865ca48 Michael Hanselmann
    self.failUnlessEqual(utils.ReadPidFile(pid_file), 0,
592 3865ca48 Michael Hanselmann
                         "ReadPidFile should return 0 for missing pid file")
593 3865ca48 Michael Hanselmann
    fh = open(pid_file, "w")
594 3865ca48 Michael Hanselmann
    fh.write("blah\n")
595 3865ca48 Michael Hanselmann
    fh.close()
596 3865ca48 Michael Hanselmann
    self.failUnlessEqual(utils.ReadPidFile(pid_file), 0,
597 3865ca48 Michael Hanselmann
                         "ReadPidFile should return 0 for invalid pid file")
598 3865ca48 Michael Hanselmann
    # but now, even with the file existing, we should be able to lock it
599 3865ca48 Michael Hanselmann
    fd = utils.WritePidFile(self.f_dpn('test'))
600 3865ca48 Michael Hanselmann
    os.close(fd)
601 79b60c1c Michael Hanselmann
    utils.RemoveFile(self.f_dpn("test"))
602 3865ca48 Michael Hanselmann
    self.failIf(os.path.exists(pid_file),
603 3865ca48 Michael Hanselmann
                "PID file should not exist anymore")
604 3865ca48 Michael Hanselmann
605 3865ca48 Michael Hanselmann
  def testKill(self):
606 3865ca48 Michael Hanselmann
    pid_file = self.f_dpn('child')
607 3865ca48 Michael Hanselmann
    r_fd, w_fd = os.pipe()
608 3865ca48 Michael Hanselmann
    new_pid = os.fork()
609 3865ca48 Michael Hanselmann
    if new_pid == 0: #child
610 3865ca48 Michael Hanselmann
      utils.WritePidFile(self.f_dpn('child'))
611 3865ca48 Michael Hanselmann
      os.write(w_fd, 'a')
612 3865ca48 Michael Hanselmann
      signal.pause()
613 3865ca48 Michael Hanselmann
      os._exit(0)
614 3865ca48 Michael Hanselmann
      return
615 3865ca48 Michael Hanselmann
    # else we are in the parent
616 3865ca48 Michael Hanselmann
    # wait until the child has written the pid file
617 3865ca48 Michael Hanselmann
    os.read(r_fd, 1)
618 3865ca48 Michael Hanselmann
    read_pid = utils.ReadPidFile(pid_file)
619 3865ca48 Michael Hanselmann
    self.failUnlessEqual(read_pid, new_pid)
620 3865ca48 Michael Hanselmann
    self.failUnless(utils.IsProcessAlive(new_pid))
621 3865ca48 Michael Hanselmann
    utils.KillProcess(new_pid, waitpid=True)
622 3865ca48 Michael Hanselmann
    self.failIf(utils.IsProcessAlive(new_pid))
623 79b60c1c Michael Hanselmann
    utils.RemoveFile(self.f_dpn('child'))
624 3865ca48 Michael Hanselmann
    self.failUnlessRaises(errors.ProgrammerError, utils.KillProcess, 0)
625 3865ca48 Michael Hanselmann
626 3865ca48 Michael Hanselmann
  def tearDown(self):
627 3865ca48 Michael Hanselmann
    shutil.rmtree(self.dir)
628 3865ca48 Michael Hanselmann
629 3865ca48 Michael Hanselmann
630 3865ca48 Michael Hanselmann
class TestSshKeys(testutils.GanetiTestCase):
631 3865ca48 Michael Hanselmann
  """Test case for the AddAuthorizedKey function"""
632 3865ca48 Michael Hanselmann
633 3865ca48 Michael Hanselmann
  KEY_A = 'ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a'
634 3865ca48 Michael Hanselmann
  KEY_B = ('command="/usr/bin/fooserver -t --verbose",from="198.51.100.4" '
635 3865ca48 Michael Hanselmann
           'ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b')
636 3865ca48 Michael Hanselmann
637 3865ca48 Michael Hanselmann
  def setUp(self):
638 3865ca48 Michael Hanselmann
    testutils.GanetiTestCase.setUp(self)
639 3865ca48 Michael Hanselmann
    self.tmpname = self._CreateTempFile()
640 3865ca48 Michael Hanselmann
    handle = open(self.tmpname, 'w')
641 3865ca48 Michael Hanselmann
    try:
642 3865ca48 Michael Hanselmann
      handle.write("%s\n" % TestSshKeys.KEY_A)
643 3865ca48 Michael Hanselmann
      handle.write("%s\n" % TestSshKeys.KEY_B)
644 3865ca48 Michael Hanselmann
    finally:
645 3865ca48 Michael Hanselmann
      handle.close()
646 3865ca48 Michael Hanselmann
647 3865ca48 Michael Hanselmann
  def testAddingNewKey(self):
648 3865ca48 Michael Hanselmann
    utils.AddAuthorizedKey(self.tmpname,
649 3865ca48 Michael Hanselmann
                           'ssh-dss AAAAB3NzaC1kc3MAAACB root@test')
650 3865ca48 Michael Hanselmann
651 3865ca48 Michael Hanselmann
    self.assertFileContent(self.tmpname,
652 3865ca48 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
653 3865ca48 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="198.51.100.4"'
654 3865ca48 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n"
655 3865ca48 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1kc3MAAACB root@test\n")
656 3865ca48 Michael Hanselmann
657 3865ca48 Michael Hanselmann
  def testAddingAlmostButNotCompletelyTheSameKey(self):
658 3865ca48 Michael Hanselmann
    utils.AddAuthorizedKey(self.tmpname,
659 3865ca48 Michael Hanselmann
        'ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@test')
660 3865ca48 Michael Hanselmann
661 3865ca48 Michael Hanselmann
    self.assertFileContent(self.tmpname,
662 3865ca48 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
663 3865ca48 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="198.51.100.4"'
664 3865ca48 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n"
665 3865ca48 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@test\n")
666 3865ca48 Michael Hanselmann
667 3865ca48 Michael Hanselmann
  def testAddingExistingKeyWithSomeMoreSpaces(self):
668 3865ca48 Michael Hanselmann
    utils.AddAuthorizedKey(self.tmpname,
669 3865ca48 Michael Hanselmann
        'ssh-dss  AAAAB3NzaC1w5256closdj32mZaQU   root@key-a')
670 3865ca48 Michael Hanselmann
671 3865ca48 Michael Hanselmann
    self.assertFileContent(self.tmpname,
672 3865ca48 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
673 3865ca48 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="198.51.100.4"'
674 3865ca48 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
675 3865ca48 Michael Hanselmann
676 3865ca48 Michael Hanselmann
  def testRemovingExistingKeyWithSomeMoreSpaces(self):
677 3865ca48 Michael Hanselmann
    utils.RemoveAuthorizedKey(self.tmpname,
678 3865ca48 Michael Hanselmann
        'ssh-dss  AAAAB3NzaC1w5256closdj32mZaQU   root@key-a')
679 3865ca48 Michael Hanselmann
680 3865ca48 Michael Hanselmann
    self.assertFileContent(self.tmpname,
681 3865ca48 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="198.51.100.4"'
682 3865ca48 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
683 3865ca48 Michael Hanselmann
684 3865ca48 Michael Hanselmann
  def testRemovingNonExistingKey(self):
685 3865ca48 Michael Hanselmann
    utils.RemoveAuthorizedKey(self.tmpname,
686 3865ca48 Michael Hanselmann
        'ssh-dss  AAAAB3Nsdfj230xxjxJjsjwjsjdjU   root@test')
687 3865ca48 Michael Hanselmann
688 3865ca48 Michael Hanselmann
    self.assertFileContent(self.tmpname,
689 3865ca48 Michael Hanselmann
      "ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
690 3865ca48 Michael Hanselmann
      'command="/usr/bin/fooserver -t --verbose",from="198.51.100.4"'
691 3865ca48 Michael Hanselmann
      " ssh-dss AAAAB3NzaC1w520smc01ms0jfJs22 root@key-b\n")
692 3865ca48 Michael Hanselmann
693 3865ca48 Michael Hanselmann
694 90e234a6 Michael Hanselmann
class TestNewUUID(unittest.TestCase):
695 90e234a6 Michael Hanselmann
  """Test case for NewUUID"""
696 90e234a6 Michael Hanselmann
697 90e234a6 Michael Hanselmann
  def runTest(self):
698 90e234a6 Michael Hanselmann
    self.failUnless(utils.UUID_RE.match(utils.NewUUID()))
699 90e234a6 Michael Hanselmann
700 90e234a6 Michael Hanselmann
701 3865ca48 Michael Hanselmann
if __name__ == "__main__":
702 3865ca48 Michael Hanselmann
  testutils.GanetiTestProgram()