From 589138ea7164b229c79d499b602b1f7535ce2544 Mon Sep 17 00:00:00 2001 From: Anatoly Bubenkov Date: Sat, 6 Jul 2013 21:30:24 +0200 Subject: [PATCH] re #320 fallback to test scope if the class-scoped fixture is used in non-class-based test function --HG-- branch : 320-class-scoped-fixture-caching-is-broken-if --- _pytest/python.py | 3 ++- testing/python/fixture.py | 6 +++--- testing/test_fixture_scope.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 4 deletions(-) create mode 100644 testing/test_fixture_scope.py diff --git a/_pytest/python.py b/_pytest/python.py index daaf727ef..627b9c89a 100644 --- a/_pytest/python.py +++ b/_pytest/python.py @@ -1317,7 +1317,8 @@ class FixtureRequest(FuncargnamesCompatAttr): x = self._pyfuncitem.getparent(pytest.Class) if x is not None: return x - scope = "module" + # fallback to function + return self._pyfuncitem if scope == "module": return self._pyfuncitem.getparent(pytest.Module) raise ValueError("unknown finalization scope %r" %(scope,)) diff --git a/testing/python/fixture.py b/testing/python/fixture.py index 357e08f4b..09856edce 100644 --- a/testing/python/fixture.py +++ b/testing/python/fixture.py @@ -513,12 +513,12 @@ class TestRequestCachedSetup: def test_request_cachedsetup_class(self, testdir): reprec = testdir.inline_runsource(""" - mysetup = ["hello", "hello2"].pop + mysetup = ["hello", "hello2", "hello3"].pop def pytest_funcarg__something(request): return request.cached_setup(mysetup, scope="class") def test_func1(something): - assert something == "hello2" + assert something == "hello3" def test_func2(something): assert something == "hello2" class TestClass: @@ -1090,7 +1090,7 @@ class TestAutouseManagement: def arg(): l.append(1) return 0 - @pytest.fixture(scope="class", autouse=True) + @pytest.fixture(scope="module", autouse=True) def something(arg): l.append(2) diff --git a/testing/test_fixture_scope.py b/testing/test_fixture_scope.py new file mode 100644 index 000000000..0bd8c5206 --- /dev/null +++ b/testing/test_fixture_scope.py @@ -0,0 +1,28 @@ +"""Tests for fixtures with different scoping.""" + + +def test_class_scope_with_normal_tests(testdir): + testpath = testdir.makepyfile(""" + import pytest + + class Box: + value = 0 + + @pytest.fixture(scope='class') + def a(request): + Box.value += 1 + return Box.value + + def test_a(a): + assert a == 1 + + class Test1: + def test_b(self, a): + assert a == 2 + + class Test2: + def test_c(self, a): + assert a == 3""") + reprec = testdir.inline_run(testpath) + for test in ['test_a', 'test_b', 'test_c']: + assert reprec.matchreport(test).passed