James E. Blair | a190f3b | 2015-01-05 14:56:54 -0800 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | # Copyright 2014 Hewlett-Packard Development Company, L.P. |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 6 | # not use this file except in compliance with the License. You may obtain |
| 7 | # a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 13 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 14 | # License for the specific language governing permissions and limitations |
| 15 | # under the License. |
| 16 | |
| 17 | import daemon |
| 18 | import logging |
| 19 | import os |
| 20 | import sys |
| 21 | |
| 22 | import extras |
| 23 | import fixtures |
| 24 | import testtools |
| 25 | |
| 26 | from tests.base import iterate_timeout |
| 27 | |
| 28 | # as of python-daemon 1.6 it doesn't bundle pidlockfile anymore |
| 29 | # instead it depends on lockfile-0.9.1 which uses pidfile. |
| 30 | pid_file_module = extras.try_imports(['daemon.pidlockfile', 'daemon.pidfile']) |
| 31 | |
| 32 | |
| 33 | def daemon_test(pidfile, flagfile): |
| 34 | pid = pid_file_module.TimeoutPIDLockFile(pidfile, 10) |
| 35 | with daemon.DaemonContext(pidfile=pid): |
| 36 | for x in iterate_timeout(30, "flagfile to be removed"): |
| 37 | if not os.path.exists(flagfile): |
| 38 | break |
| 39 | sys.exit(0) |
| 40 | |
| 41 | |
| 42 | class TestDaemon(testtools.TestCase): |
| 43 | log = logging.getLogger("zuul.test.daemon") |
| 44 | |
| 45 | def setUp(self): |
| 46 | super(TestDaemon, self).setUp() |
| 47 | self.test_root = self.useFixture(fixtures.TempDir( |
| 48 | rootdir=os.environ.get("ZUUL_TEST_ROOT"))).path |
| 49 | |
| 50 | def test_daemon(self): |
| 51 | pidfile = os.path.join(self.test_root, "daemon.pid") |
| 52 | flagfile = os.path.join(self.test_root, "daemon.flag") |
| 53 | open(flagfile, 'w').close() |
| 54 | if not os.fork(): |
| 55 | self._cleanups = [] |
| 56 | daemon_test(pidfile, flagfile) |
| 57 | for x in iterate_timeout(30, "daemon to start"): |
| 58 | if os.path.exists(pidfile): |
| 59 | break |
| 60 | os.unlink(flagfile) |
| 61 | for x in iterate_timeout(30, "daemon to stop"): |
| 62 | if not os.path.exists(pidfile): |
| 63 | break |