Matthew Treinish | 9b4d588 | 2013-10-24 20:00:11 +0000 | [diff] [blame] | 1 | # 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 | |
| 16 | import fixtures |
| 17 | |
Sean Dague | fc691e3 | 2014-01-03 08:51:54 -0500 | [diff] [blame] | 18 | from tempest.openstack.common import lockutils |
Matthew Treinish | 9b4d588 | 2013-10-24 20:00:11 +0000 | [diff] [blame] | 19 | |
| 20 | |
| 21 | class 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 Dague | fc691e3 | 2014-01-03 08:51:54 -0500 | [diff] [blame] | 46 | self.mgr = lockutils.lock(name, lock_file_prefix, True) |
Matthew Treinish | 9b4d588 | 2013-10-24 20:00:11 +0000 | [diff] [blame] | 47 | |
| 48 | def setUp(self): |
| 49 | super(LockFixture, self).setUp() |
| 50 | self.addCleanup(self.mgr.__exit__, None, None, None) |
| 51 | self.mgr.__enter__() |