1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
|
# Copyright 2007 Google Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""Unit tests for nss_cache/lock.py."""
__author__ = "vasilios@google.com (Vasilios Hoffman)"
import builtins
import errno
import fcntl
import os
import re
import shutil
import signal
import stat
import sys
import tempfile
import unittest
from unittest import mock
from nss_cache import lock
class TestPidFile(unittest.TestCase):
"""Unit tests for PidFile class in lock.py."""
# Note that we do not test whether fcntl actually works as expected.
# That is outside the scope of unit tests and I'm not going to fork
# a child to test this, at least not now.
#
# Rest assured, it works as expected and fcntl throws an exception if
# another process has the lock.
#
# We also do not test if os.kill works as expected :)
def setUp(self):
super(TestPidFile, self).setUp()
self.workdir = tempfile.mkdtemp()
self.filename = "%s/%s" % (self.workdir, "pidfile")
def tearDown(self):
shutil.rmtree(self.workdir)
super(TestPidFile, self).tearDown()
def testInit(self):
locker = lock.PidFile()
pid = os.getpid()
filename = os.path.basename(sys.argv[0])
filename = "%s/%s" % (locker.STATE_DIR, filename)
self.assertTrue(isinstance(locker, lock.PidFile))
self.assertEqual(locker.pid, pid)
self.assertEqual(locker.filename, filename)
self.assertEqual(locker._locked, False)
self.assertEqual(locker._file, None)
# also check the case where argv[0] is empty (interactively loaded)
full_path = sys.argv[0]
sys.argv[0] = ""
self.assertRaises(TypeError, lock.PidFile)
sys.argv[0] = full_path
def testHandleArgumentsProperly(self):
filename = "TEST"
pid = 10
locker = lock.PidFile(filename=filename, pid=pid)
self.assertEqual(locker.filename, filename)
self.assertEqual(locker.pid, pid)
def testDestructorUnlocks(self):
yes = lock.PidFile()
with mock.patch.object(yes, "Locked") as locked, mock.patch.object(
yes, "Unlock"
) as unlock:
locked.return_value = True
yes.__del__()
# Destructor should unlock
unlock.assert_called_once()
no = lock.PidFile()
with mock.patch.object(no, "Locked") as locked, mock.patch.object(
yes, "Unlock"
) as unlock:
locked.return_value = False
no.__del__()
# No unlock needed if already not locked.
unlock.assert_not_called()
def testOpenCreatesAppropriateFileWithPerms(self):
locker = lock.PidFile(filename=self.filename)
locker._Open()
self.assertTrue(os.path.exists(self.filename))
file_mode = os.stat(self.filename)[stat.ST_MODE]
correct_mode = (
stat.S_IFREG | stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH
)
self.assertEqual(file_mode, correct_mode)
os.remove(self.filename)
def testLockCreatesPidfiles(self):
locker = lock.PidFile()
with mock.patch.object(locker, "_Open") as open:
open.side_effect = NotImplementedError()
self.assertRaises(NotImplementedError, locker.Lock)
# Note that testing when self._file is not None is covered below.
@mock.patch("fcntl.lockf")
def testLockLocksWithFcntl(self, lockf):
locker = lock.PidFile(pid="PID")
with mock.patch.object(locker, "_file") as f:
locker.Lock()
self.assertTrue(locker._locked)
lockf.assert_called_once_with(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
def testLockStoresPid(self):
locker = lock.PidFile(filename=self.filename, pid="PID")
locker.Lock()
pid_file = open(self.filename, "r")
self.assertEqual(pid_file.read(), "PID\n")
pid_file.close()
os.remove(self.filename)
def testLockTrapsPermissionDeniedOnly(self):
locker = lock.PidFile()
with mock.patch.object(locker, "_Open") as open:
open.side_effect = [IOError(errno.EACCES, ""), IOError(errno.EIO, "")]
self.assertEqual(False, locker.Lock())
self.assertRaises(IOError, locker.Lock)
def testForceLockTerminatesAndClearsLock(self):
locker = lock.PidFile(pid="PID")
with mock.patch.object(locker, "SendTerm"), mock.patch.object(
locker, "ClearLock"
), mock.patch.object(locker, "_file") as f:
with mock.patch("fcntl.lockf") as lockf:
# This is a little weird due to recursion.
# The first time through lockf throws an error and we retry the lock.
# The 2nd time through we should fail, because lockf will still throw
# an error, so we expect False back and the above mock objects
# invoked.
lockf.side_effect = [
IOError(errno.EAGAIN, ""),
IOError(errno.EAGAIN, ""),
]
self.assertFalse(locker.Lock(force=True))
lockf.assert_has_calls(
(
mock.call(locker._file, fcntl.LOCK_EX | fcntl.LOCK_NB),
mock.call(locker._file, fcntl.LOCK_EX | fcntl.LOCK_NB),
)
)
def testSendTermMatchesCommandAndSendsTerm(self):
locker = lock.PidFile()
# Program mocks
mock_re = mock.create_autospec(re.Pattern)
mock_re.match.return_value = True
with mock.patch("re.compile") as regexp, mock.patch(
"os.kill"
) as kill, mock.patch.object(locker, "_file") as f:
f.read.return_value = "1234"
regexp.return_value = mock_re
# Create a file we open() in SendTerm().
proc_dir = "%s/1234" % self.workdir
proc_filename = "%s/cmdline" % proc_dir
os.mkdir(proc_dir)
proc_file = open(proc_filename, "w")
proc_file.write("TEST")
proc_file.flush()
proc_file.close()
locker.PROC_DIR = self.workdir
# Actually exercise the mocks
locker.SendTerm()
# Assert the mocks
regexp.assert_called_with(r".*nsscache")
kill.assert_called_once_with(1234, signal.SIGTERM)
f.read.assert_called()
f.seek.assert_called_with(0)
os.remove(proc_filename)
os.rmdir(proc_dir)
def testSendTermNoPid(self):
locker = lock.PidFile()
with mock.patch.object(locker, "_file") as f, mock.patch("os.kill") as kill:
f.read.return_value = "\n"
locker.PROC = self.workdir
locker.SendTerm()
f.read.assert_called()
kill.assert_not_called()
def testSendTermNonePid(self):
locker = lock.PidFile()
with mock.patch.object(locker, "_file") as f, mock.patch("os.kill") as kill:
f.read.return_value = None
locker.PROC = self.workdir
locker.SendTerm()
f.read.assert_called()
kill.assert_not_called()
def testSendTermTrapsENOENT(self):
locker = lock.PidFile()
with mock.patch.object(locker, "_file") as f, mock.patch(
"os.kill"
) as kill, mock.patch("builtins.open") as mock_open:
f.read.return_value = "1234\n"
mock_open.side_effect = IOError(errno.ENOENT, "")
# self.workdir/1234/cmdline should not exist :)
self.assertFalse(os.path.exists("%s/1234/cmdline" % self.workdir))
locker.PROC = self.workdir
locker.SendTerm()
f.read.assert_called()
f.seek.assert_called_with(0)
def testClearLockRemovesPidFile(self):
# Create a pid file.
pidfile = open(self.filename, "w")
pidfile.write("foo")
pidfile.flush()
locker = lock.PidFile(filename=self.filename)
# Cheat instead of calling open.
locker._file = pidfile
locker.ClearLock()
self.assertFalse(os.path.exists(self.filename))
def testLockedPredicate(self):
locker = lock.PidFile()
locker._locked = True
self.assertTrue(locker.Locked())
locker._locked = False
self.assertFalse(locker.Locked())
def testUnlockReleasesFcntlLock(self):
locker = lock.PidFile()
locker._file = "FILE_OBJECT"
with mock.patch("fcntl.lockf") as lockf:
locker.Unlock()
self.assertFalse(locker._locked)
lockf.assert_called_once_with("FILE_OBJECT", fcntl.LOCK_UN)
if __name__ == "__main__":
unittest.main()
|