blob: 593668734c810e999581e6d44ce8f514402c959c [file] [log] [blame]
Matthew Treinish9b4d5882013-10-24 20:00:11 +00001# Copyright 2011 OpenStack Foundation.
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13# License for the specific language governing permissions and limitations
14# under the License.
15
16import fixtures
17
Sean Daguefc691e32014-01-03 08:51:54 -050018from tempest.openstack.common import lockutils
Matthew Treinish9b4d5882013-10-24 20:00:11 +000019
20
21class LockFixture(fixtures.Fixture):
22 """External locking fixture.
23
24 This fixture is basically an alternative to the synchronized decorator with
25 the external flag so that tearDowns and addCleanups will be included in
26 the lock context for locking between tests. The fixture is recommended to
27 be the first line in a test method, like so::
28
29 def test_method(self):
30 self.useFixture(LockFixture)
31 ...
32
33 or the first line in setUp if all the test methods in the class are
34 required to be serialized. Something like::
35
36 class TestCase(testtools.testcase):
37 def setUp(self):
38 self.useFixture(LockFixture)
39 super(TestCase, self).setUp()
40 ...
41
42 This is because addCleanups are put on a LIFO queue that gets run after the
43 test method exits. (either by completing or raising an exception)
44 """
45 def __init__(self, name, lock_file_prefix=None):
Sean Daguefc691e32014-01-03 08:51:54 -050046 self.mgr = lockutils.lock(name, lock_file_prefix, True)
Matthew Treinish9b4d5882013-10-24 20:00:11 +000047
48 def setUp(self):
49 super(LockFixture, self).setUp()
50 self.addCleanup(self.mgr.__exit__, None, None, None)
51 self.mgr.__enter__()