Add fixture_property decorator

Add a new decorator that improve property decorator
by allowing to invoke getter method from fixture class.

This makes below code to work:

import tobiko

class MyFixture(tobiko.SharedFixture):

  @tobiko.fixture_property
  def my_property():
      return ...

assert tibiko.get_fixture(MyFixture).my_property == MyFixture.my_property

Change-Id: I72b6b8305823bb7be2bee6a806a6bced915229f6
This commit is contained in:
Federico Ressi 2019-05-22 08:56:32 +02:00
parent 7d0f8e92f4
commit 53b0b45a42
3 changed files with 30 additions and 0 deletions

View File

@ -28,6 +28,7 @@ TobikoException = _exception.TobikoException
is_fixture = _fixture.is_fixture
get_fixture = _fixture.get_fixture
fixture_property = _fixture.fixture_property
required_fixture = _fixture.required_fixture
required_setup_fixture = _fixture.required_setup_fixture
get_fixture_name = _fixture.get_fixture_name

View File

@ -215,6 +215,10 @@ def init_fixture(obj, name):
raise TypeError("Invalid fixture object type: {!r}".format(obj))
def fixture_property(*args, **kwargs):
return FixtureProperty(*args, **kwargs)
def required_fixture(obj):
'''Creates a property that gets fixture identified by given :param obj:
@ -371,6 +375,13 @@ class SharedFixture(fixtures.Fixture):
pass
class FixtureProperty(property):
def __get__(self, instance, owner):
instance = instance or tobiko.get_fixture(owner)
return super(FixtureProperty, self).__get__(instance, owner)
class RequiredFixtureProperty(object):
def __init__(self, fixture):

View File

@ -208,6 +208,24 @@ class CleanupFixtureTest(FixtureBaseTest):
result.cleanup_fixture.assert_called_once_with()
class MyFixtureWithProperty(MyBaseFixture):
@tobiko.fixture_property
def some_property(self):
return id(self)
class FixturePropertyTest(FixtureBaseTest):
def test_with_instance(self):
fixture = tobiko.get_fixture(MyFixtureWithProperty)
self.assertEqual(id(fixture), fixture.some_property)
def test_without_instance(self):
fixture = tobiko.get_fixture(MyFixtureWithProperty)
self.assertEqual(id(fixture), MyFixtureWithProperty.some_property)
class MyFixture2(MyBaseFixture):
pass