source: mod_gnutls/test/mgstest/__init__.py @ d5c572b

asyncioproxy-ticket
Last change on this file since d5c572b was d5c572b, checked in by Fiona Klute <fiona.klute@…>, 17 months ago

Use try/finally in lockfile context even when locking is disabled

The simple "yield" caused exceptions with contextlib.ExitStack?().

  • Property mode set to 100644
File size: 1.7 KB
Line 
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
19import sys
20
21import fcntl
22from contextlib import contextmanager
23
24class 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
32def 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        try:
42            yield None
43        finally:
44            pass
45    else:
46        with open(file, 'w') as lockfile:
47            try:
48                print(f'Aquiring lock on {file}...', file=sys.stderr)
49                fcntl.flock(lockfile, fcntl.LOCK_EX)
50                print(f'Got lock on {file}.', file=sys.stderr)
51                yield lockfile
52            finally:
53                print(f'Unlocking {file}...', file=sys.stderr)
54                fcntl.flock(lockfile, fcntl.LOCK_UN)
55                print(f'Unlocked {file}.', file=sys.stderr)
Note: See TracBrowser for help on using the repository browser.