1 | #!/usr/bin/python3 |
---|
2 | |
---|
3 | # Copyright 2019 Fiona Klute |
---|
4 | # |
---|
5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
---|
6 | # you may not use this file except in compliance with the License. |
---|
7 | # You may obtain 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, |
---|
13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
---|
14 | # See the License for the specific language governing permissions and |
---|
15 | # limitations under the License. |
---|
16 | |
---|
17 | """Python modules for the mod_gnutls test suite.""" |
---|
18 | |
---|
19 | import sys |
---|
20 | |
---|
21 | import fcntl |
---|
22 | from contextlib import contextmanager |
---|
23 | |
---|
24 | class TestExpectationFailed(Exception): |
---|
25 | """Raise if a test failed. The constructor should be called with a |
---|
26 | string describing the problem.""" |
---|
27 | pass |
---|
28 | |
---|
29 | |
---|
30 | |
---|
31 | @contextmanager |
---|
32 | def lockfile(file, nolock=False): |
---|
33 | """Context manager for an optional file-based mutex. |
---|
34 | |
---|
35 | Unless nolock=True the process must hold a lock on the given file |
---|
36 | before entering the context. The lock is released when leaving the |
---|
37 | context. |
---|
38 | |
---|
39 | """ |
---|
40 | if nolock: |
---|
41 | yield |
---|
42 | else: |
---|
43 | with open(file, 'w') as lockfile: |
---|
44 | try: |
---|
45 | print(f'Aquiring lock on {file}...', file=sys.stderr) |
---|
46 | fcntl.flock(lockfile, fcntl.LOCK_EX) |
---|
47 | print(f'Got lock on {file}.', file=sys.stderr) |
---|
48 | yield |
---|
49 | finally: |
---|
50 | print(f'Unlocking {file}...', file=sys.stderr) |
---|
51 | fcntl.flock(lockfile, fcntl.LOCK_UN) |
---|
52 | print(f'Unlocked {file}.', file=sys.stderr) |
---|