Kuang-che Wu | fb55310 | 2018-10-02 18:14:29 +0800 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | # Copyright 2018 The Chromium OS Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | """Test locking module""" |
| 6 | from __future__ import print_function |
| 7 | import multiprocessing |
| 8 | import os |
| 9 | import tempfile |
| 10 | import time |
| 11 | import unittest |
| 12 | |
| 13 | from bisect_kit import locking |
| 14 | |
| 15 | |
| 16 | def lock_test_helper(filename, queue): |
| 17 | # Use smaller polling_time for shorter test duration. |
| 18 | with locking.lock_file(filename, polling_time=0.01): |
| 19 | queue.put(time.time()) |
| 20 | time.sleep(0.5) |
| 21 | |
| 22 | |
| 23 | class TestLocking(unittest.TestCase): |
| 24 | """Test locking functions.""" |
| 25 | |
| 26 | def setUp(self): |
| 27 | self.lock_filename = tempfile.mktemp() |
| 28 | |
| 29 | def tearDown(self): |
| 30 | if os.path.exists(self.lock_filename): |
| 31 | os.unlink(self.lock_filename) |
| 32 | |
| 33 | def test_lock_file(self): |
| 34 | # Because the lock cannot reenter in the same process and cannot be shared |
| 35 | # between threads, run the test on two separated processes via |
| 36 | # multiprocessing. |
| 37 | queue = multiprocessing.Queue() |
| 38 | processes = [] |
| 39 | for _ in range(2): |
| 40 | p = multiprocessing.Process( |
| 41 | target=lock_test_helper, args=(self.lock_filename, queue)) |
| 42 | p.start() |
| 43 | processes.append(p) |
| 44 | time.sleep(0.1) |
| 45 | for p in processes: |
| 46 | p.join() |
| 47 | t1 = float(queue.get()) |
| 48 | t2 = float(queue.get()) |
| 49 | self.assertAlmostEqual(t2 - t1, 0.5, places=1) |
| 50 | |
| 51 | |
| 52 | if __name__ == '__main__': |
| 53 | unittest.main() |