blob: e26f113a424c4cfc49543dd85c67a25a789167ba [file] [log] [blame]
Kuang-che Wufb553102018-10-02 18:14:29 +08001# -*- 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"""
6from __future__ import print_function
7import multiprocessing
8import os
9import tempfile
10import time
11import unittest
12
13from bisect_kit import locking
14
15
16def 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
23class 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
52if __name__ == '__main__':
53 unittest.main()