1
|
|
|
import os |
2
|
|
|
import time |
3
|
|
|
import tempfile |
4
|
|
|
import shutil |
5
|
|
|
|
6
|
|
|
from subprocess import Popen, PIPE |
7
|
|
|
from nose.tools import assert_equal, assert_true |
8
|
|
|
|
9
|
|
|
from smartdispatch.filelock import open_with_lock, open_with_dirlock, open_with_flock |
10
|
|
|
from smartdispatch.filelock import find_mount_point, get_fs, have_psutil |
11
|
|
|
|
12
|
|
|
|
13
|
|
|
def _test_open_with_lock(lock_func): |
14
|
|
|
temp_dir = tempfile.mkdtemp() |
15
|
|
|
filename = os.path.join(temp_dir, "testing.lck") |
16
|
|
|
|
17
|
|
|
python_script = os.path.join(temp_dir, "test_lock.py") |
18
|
|
|
|
19
|
|
|
script = ["import logging", |
20
|
|
|
"from smartdispatch.filelock import {}".format(lock_func.__name__), |
21
|
|
|
"logging.root.setLevel(logging.INFO)", |
22
|
|
|
"with {}('{}', 'r+'): pass".format(lock_func.__name__, filename)] |
23
|
|
|
|
24
|
|
|
open(os.path.join(temp_dir, "test_lock.py"), 'w').write("\n".join(script)) |
25
|
|
|
|
26
|
|
|
command = "python " + python_script |
27
|
|
|
|
28
|
|
|
# Lock the commands file before running python command |
29
|
|
|
with lock_func(filename, 'w'): |
30
|
|
|
process = Popen(command, stdout=PIPE, stderr=PIPE, shell=True) |
31
|
|
|
time.sleep(1) |
32
|
|
|
|
33
|
|
|
stdout, stderr = process.communicate() |
34
|
|
|
assert_equal(stdout, "") |
35
|
|
|
assert_true("Traceback" not in stderr, msg="Unexpected error: '{}'".format(stderr)) |
36
|
|
|
assert_true("write-lock" in stderr, msg="Forcing a race condition, try increasing sleeping time above.") |
37
|
|
|
|
38
|
|
|
shutil.rmtree(temp_dir) # Cleaning up. |
39
|
|
|
|
40
|
|
|
|
41
|
|
|
def test_open_with_default_lock(): |
42
|
|
|
_test_open_with_lock(open_with_lock) |
43
|
|
|
|
44
|
|
|
|
45
|
|
|
def test_open_with_dirlock(): |
46
|
|
|
_test_open_with_lock(open_with_dirlock) |
47
|
|
|
|
48
|
|
|
|
49
|
|
|
def test_open_with_flock(): |
50
|
|
|
_test_open_with_lock(open_with_flock) |
51
|
|
|
|
52
|
|
|
|
53
|
|
|
def test_find_mount_point(): |
54
|
|
|
assert_equal(find_mount_point('/'), '/') |
55
|
|
|
|
56
|
|
|
for d in os.listdir('/mnt'): |
57
|
|
|
path = os.path.join('/mnt', d) |
58
|
|
|
if os.path.ismount(path): |
59
|
|
|
assert_equal(find_mount_point(path), path) |
60
|
|
|
else: |
61
|
|
|
assert_equal(find_mount_point(path), '/') |
62
|
|
|
|
63
|
|
|
|
64
|
|
|
def test_get_fs(): |
65
|
|
|
if have_psutil: |
66
|
|
|
fs = get_fs('/') |
67
|
|
|
assert_true(fs is not None) |
68
|
|
|
|