[py-svn] commit/pytest: 6 new changesets

Bitbucket commits-noreply at bitbucket.org
Fri Oct 5 14:35:27 CEST 2012


6 new commits in pytest:


https://bitbucket.org/hpk42/pytest/changeset/b5230e47ebef/
changeset:   b5230e47ebef
user:        hpk42
date:        2012-10-05 10:21:35
summary:     merge factories/funcargs and setup functions into the new "fixture" document
affected #:  5 files

diff -r 45009f2213bc36057470967ff709fd4a77b5257d -r b5230e47ebefaf111624dadc34a7852418dadf3f doc/en/conf.py
--- a/doc/en/conf.py
+++ b/doc/en/conf.py
@@ -269,7 +269,11 @@
 
 
 # Example configuration for intersphinx: refer to the Python standard library.
-intersphinx_mapping = {} # 'http://docs.python.org/': None}
+intersphinx_mapping = {'python': ('http://docs.python.org/', None),
+                       'lib': ("http://docs.python.org/library/", None),
+                    }
+
+
 def setup(app):
     #from sphinx.ext.autodoc import cut_lines
     #app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))


diff -r 45009f2213bc36057470967ff709fd4a77b5257d -r b5230e47ebefaf111624dadc34a7852418dadf3f doc/en/fixture.txt
--- /dev/null
+++ b/doc/en/fixture.txt
@@ -0,0 +1,681 @@
+.. _xunitsetup:
+.. _setup:
+.. _fixture:
+.. _`fixture functions`:
+.. _`@pytest.fixture`:
+
+pytest fixtures: modular, re-useable, flexible
+========================================================
+
+.. versionadded:: 2.0,2.3
+
+.. _`funcargs`: funcargs.html
+.. _`test parametrization`: funcargs.html#parametrizing-tests
+.. _`unittest plugin`: plugin/unittest.html
+.. _`xUnit`: http://en.wikipedia.org/wiki/XUnit
+.. _`general purpose of test fixtures`: http://en.wikipedia.org/wiki/Test_fixture#Software
+.. _`django`: https://www.djangoproject.com/
+.. _`pytest-django`: https://pypi.python.org/pytest-django
+.. _`Dependency injection`: http://en.wikipedia.org/wiki/Dependency_injection#Definition
+
+pytest allows to provide and use test fixtures in a modular and flexible
+manner, offering major improvements over the classic xUnit style of
+setup/teardown functions.  The `general purpose of test fixtures`_ is to
+provide a fixed baseline upon which tests can reliably and
+repeatedly execute.  With pytest, fixtures are implemented by 
+**fixture functions** which may return a fixture object, put extra
+attributes on test classes or perform side effects.  The name of a 
+fixture function is significant and is used for invoking or activating it.
+
+**Test functions can receive fixture objects by naming them as an input
+argument.** For each argument name, a matching fixture
+function will provide a fixture object.  This mechanism has been
+introduced with pytest-2.0 and is also called the **funcarg mechanism**.
+It allows test functions to easily receive and work against specific
+pre-initialized application objects without having to care about the
+details of setup/cleanup procedures.  This mechanism is a prime example of
+`dependency injection`_ where fixture functions take the role of the
+*injector* and test functions are the *consumers* of fixture objects.
+With pytest-2.3 this mechanism has been much improved to help with
+sharing and parametrizing fixtures across test runs.
+
+**Test classes, modules or whole projects can declare a need for
+one or more fixtures**.  All required fixture functions will execute 
+before a test from the specifying context executes.  They will
+typically not provide a fixture object but rather perform side effects 
+like reading or preparing default config settings and pre-initializing 
+an application.  For example, the Django_ project requires database 
+initialization to be able to import from and use its model objects.  
+Plugins like `pytest-django`_ provide baseline fixtures which your 
+project can then easily depend or extend on.
+
+**Fixtures can be shared throughout a test session, module or class.**.  
+By means of a "scope" declaration on a fixture function, it will
+only be invoked once per the specified scope.  Sharing expensive application
+object setups between tests typically helps to speed up test runs.
+Typical examples are the setup of test databases or establishing
+required subprocesses or network connections.
+
+**Fixture functions have controlled visilibity** which depends on where they
+are defined.  If they are defined on a test class, only its test methods 
+may use it. A fixture defined in a module can only be used
+from that test module.  A fixture defined in a conftest.py file
+can only be used by the tests below the directory of that file.
+Lastly plugins can define fixtures which are available across all
+projects.
+
+**Fixture functions can interact with the requesting testcontext**.  By
+accepting a special ``request`` object, fixture functions can introspect
+the function, class or module for which they are invoked and can
+optionally register cleanup functions which are called when the last
+test finished execution.  A good example is `pytest-timeout`_ which
+allows to limit the execution time of a test, and will read the
+according parameter from a test function or from project-wide setting.
+
+**Fixture functions can be parametrized** in which case they will be called
+multiple times, each time executing the set of dependent tests, i. e. the
+tests that depend on this fixture.  Test functions do usually not need
+to be aware of their re-running.  Fixture parametrization helps to
+write functional tests for components which themselves can be 
+configured in multiple ways.
+
+
+Basic funcarg fixture example
+-----------------------------------------------------------
+
+.. versionadded:: 2.3
+
+
+Let's look at a simple self-contained test module containing a module
+visible fixture function and a test function using the provided fixture::
+
+    # content of ./test_simplefactory.py
+    import pytest
+
+    @pytest.fixture
+    def myfuncarg():
+        return 42
+
+    def test_function(myfuncarg):
+        assert myfuncarg == 17
+
+Here, the ``test_function`` needs an object named ``myfuncarg`` and thus
+py.test will discover and call the ``@pytest.fixture`` marked ``myfuncarg`` 
+factory function.  Running the tests looks like this::
+
+    $ py.test test_simplefactory.py
+    =========================== test session starts ============================
+    platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev11
+    plugins: xdist, bugzilla, cache, oejskit, cli, timeout, pep8, cov
+    collecting ... collected 1 items
+    
+    test_simplefactory.py F
+    
+    ================================= FAILURES =================================
+    ______________________________ test_function _______________________________
+    
+    myfuncarg = 42
+    
+        def test_function(myfuncarg):
+    >       assert myfuncarg == 17
+    E       assert 42 == 17
+    
+    test_simplefactory.py:8: AssertionError
+    ========================= 1 failed in 0.01 seconds =========================
+
+This shows that the test function was called with a ``myfuncarg``
+argument value of ``42`` and the assert fails as expected.  Here is 
+how py.test comes to call the test function this way:
+
+1. py.test :ref:`finds <test discovery>` the ``test_function`` because
+   of the ``test_`` prefix.  The test function needs a function argument
+   named ``myfuncarg``.  A matching factory function is discovered by
+   looking for a fixture function named ``myfuncarg``.
+
+2. ``myfuncarg()`` is called to create a value ``42``.
+
+3. ``test_function(42)`` is now called and results in the above
+   reported exception because of the assertion mismatch.
+
+Note that if you misspell a function argument or want
+to use one that isn't available, you'll see an error
+with a list of available function arguments.
+
+.. Note::
+
+    You can always issue::
+
+        py.test --fixtures test_simplefactory.py
+
+    to see available fixtures.
+
+    In versions prior to 2.3 there was no @pytest.fixture marker
+    and you had to instead use a magic ``pytest_funcarg__NAME`` prefix
+    for the fixture factory.  This remains and will remain supported 
+    but is not advertised as the primary means of declaring fixture
+    functions.
+
+
+Creating and using a session-shared fixture
+-----------------------------------------------------------------
+
+.. regendoc:wipe
+
+Here is a simple example of a fixture function creating a shared 
+``smtplib.SMTP`` connection fixture which test functions from 
+test modules below the directory of a ``conftest.py`` file may use::
+
+    # content of conftest.py
+    import pytest
+    import smtplib
+
+    @pytest.fixture(scope="session")
+    def smtp():
+        return smtplib.SMTP("merlinux.eu")
+
+The name of the fixture is ``smtp`` and you can access its result by
+listing the name ``smtp`` as an input parameter in any test or setup
+function::
+
+    # content of test_module.py
+    def test_ehlo(smtp):
+        response = smtp.ehlo()
+        assert response[0] == 250 
+        assert "merlinux" in response[1]
+        assert 0  # for demo purposes
+
+    def test_noop(smtp):
+        response = smtp.noop()
+        assert response[0] == 250
+        assert 0  # for demo purposes
+
+We deliberately insert failing ``assert 0`` statements in order to
+inspect what is going on and can now run the tests::
+
+    $ py.test -q test_module.py
+    collecting ... collected 2 items
+    FF
+    ================================= FAILURES =================================
+    ________________________________ test_ehlo _________________________________
+    
+    smtp = <smtplib.SMTP instance at 0x31bce18>
+    
+        def test_ehlo(smtp):
+            response = smtp.ehlo()
+            assert response[0] == 250
+            assert "merlinux" in response[1]
+    >       assert 0  # for demo purposes
+    E       assert 0
+    
+    test_module.py:5: AssertionError
+    ________________________________ test_noop _________________________________
+    
+    smtp = <smtplib.SMTP instance at 0x31bce18>
+    
+        def test_noop(smtp):
+            response = smtp.noop()
+            assert response[0] == 250
+    >       assert 0  # for demo purposes
+    E       assert 0
+    
+    test_module.py:10: AssertionError
+    2 failed in 0.26 seconds
+
+you see the two ``assert 0`` failing and can also see that
+the same (session-scoped) object was passed into the two test functions
+because pytest shows the incoming arguments in the traceback.
+
+Adding a finalizer to a fixture
+--------------------------------------------------------
+
+Further extending the ``smtp`` example, we now want to properly
+close a smtp server connection after the last test using it
+has been run.  We can do this by calling the ``request.addfinalizer()``
+helper::
+
+    # content of conftest.py
+    import pytest
+    import smtplib
+
+    @pytest.fixture(scope="session")
+    def smtp(request):
+        smtp = smtplib.SMTP("merlinux.eu")
+        def fin():
+            print ("finalizing %s" % smtp)
+            smtp.close()
+        request.addfinalizer(fin)
+        return smtp
+
+The registered ``fin`` function will be called when the last test
+using it has executed::
+
+    $ py.test -s -q --tb=no
+    collecting ... collected 4 items
+    FFFF
+    4 failed in 6.40 seconds
+    finalizing <smtplib.SMTP instance at 0x125d3b0>
+
+We see that the ``smtp`` instance is finalized after all
+tests executed.  If we had specified ``scope='function'`` 
+then fixture setup and cleanup would occur around each 
+single test. 
+
+Parametrizing a session-shared funcarg resource
+-----------------------------------------------------------------
+
+Extending the previous example, we can flag the fixture to create
+two ``smtp`` fixture instances which will cause all tests using the
+fixture to run twice.  The fixture function gets
+access to each parameter through the special `request`_ object::
+
+    # content of conftest.py
+    import pytest
+    import smtplib
+
+    @pytest.fixture(scope="session", 
+                    params=["merlinux.eu", "mail.python.org"])
+    def smtp(request):
+        smtp = smtplib.SMTP(request.param)
+        def fin():
+            print ("finalizing %s" % smtp)
+            smtp.close()
+        request.addfinalizer(fin)
+        return smtp
+
+The main change is the declaration of ``params``, a list of values
+for each of which the fixture function will execute and can access
+a value via ``request.param``.  No test function code needs to change.  
+So let's just do another run::
+
+    $ py.test -q
+    collecting ... collected 4 items
+    FFFF
+    ================================= FAILURES =================================
+    __________________________ test_ehlo[merlinux.eu] __________________________
+    
+    smtp = <smtplib.SMTP instance at 0x28dc5a8>
+    
+        def test_ehlo(smtp):
+            response = smtp.ehlo()
+            assert response[0] == 250
+            assert "merlinux" in response[1]
+    >       assert 0  # for demo purposes
+    E       assert 0
+    
+    test_module.py:5: AssertionError
+    __________________________ test_noop[merlinux.eu] __________________________
+    
+    smtp = <smtplib.SMTP instance at 0x28dc5a8>
+    
+        def test_noop(smtp):
+            response = smtp.noop()
+            assert response[0] == 250
+    >       assert 0  # for demo purposes
+    E       assert 0
+    
+    test_module.py:10: AssertionError
+    ________________________ test_ehlo[mail.python.org] ________________________
+    
+    smtp = <smtplib.SMTP instance at 0x28e3e18>
+    
+        def test_ehlo(smtp):
+            response = smtp.ehlo()
+            assert response[0] == 250
+    >       assert "merlinux" in response[1]
+    E       assert 'merlinux' in 'mail.python.org\nSIZE 10240000\nETRN\nSTARTTLS\nENHANCEDSTATUSCODES\n8BITMIME\nDSN'
+    
+    test_module.py:4: AssertionError
+    ________________________ test_noop[mail.python.org] ________________________
+    
+    smtp = <smtplib.SMTP instance at 0x28e3e18>
+    
+        def test_noop(smtp):
+            response = smtp.noop()
+            assert response[0] == 250
+    >       assert 0  # for demo purposes
+    E       assert 0
+    
+    test_module.py:10: AssertionError
+    4 failed in 6.17 seconds
+
+We now get four failures because we are running the two tests twice with
+different ``smtp`` fixture instances.  Note that with the
+``mail.python.org`` connection the second test fails in ``test_ehlo``
+because it expects a specific server string.
+
+We also see that the two ``smtp`` instances are finalized appropriately.
+
+Looking at test collection without running tests
+------------------------------------------------------
+
+You can also look at the tests which pytest collects without running them::
+
+    $ py.test --collectonly
+    =========================== test session starts ============================
+    platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev11
+    plugins: xdist, bugzilla, cache, oejskit, cli, timeout, pep8, cov
+    collecting ... collected 4 items
+    <Module 'test_module.py'>
+      <Function 'test_ehlo[merlinux.eu]'>
+      <Function 'test_noop[merlinux.eu]'>
+      <Function 'test_ehlo[mail.python.org]'>
+      <Function 'test_noop[mail.python.org]'>
+    
+    =============================  in 0.01 seconds =============================
+
+Our fixture parameters show up in the test id of the test functions.
+Note that pytest orders your test run by resource usage, minimizing
+the number of active resources at any given time.
+
+
+.. _`interdependent fixtures`:
+
+Interdepdendent fixtures
+----------------------------------------------------------
+
+You can not only use fixtures in test functions but fixture functions
+can use other fixtures themselves.  This contributes to a modular design
+of your fixtures and allows re-use of framework-specific fixtures across
+many projects.  As a simple example, we can extend the previous example
+and instantiate an object ``app`` where we stick the already defined
+``smtp`` resource into it::
+
+    # content of test_appsetup.py
+   
+    import pytest
+
+    class App:
+        def __init__(self, smtp):
+            self.smtp = smtp
+
+    @pytest.fixture(scope="module")
+    def app(smtp):
+        return App(smtp)
+
+    def test_smtp_exists(app):
+        assert app.smtp
+
+Here we declare an ``app`` fixture which receives the previously defined
+``smtp`` fixture and instantiates an ``App`` object with it.  Let's run it::
+
+    $ py.test -v test_appsetup.py
+    =========================== test session starts ============================
+    platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev11 -- /home/hpk/venv/1/bin/python
+    cachedir: /home/hpk/tmp/doc-exec-423/.cache
+    plugins: xdist, bugzilla, cache, oejskit, cli, timeout, pep8, cov
+    collecting ... collected 2 items
+    
+    test_appsetup.py:12: test_exists[merlinux.eu] PASSED
+    test_appsetup.py:12: test_exists[mail.python.org] PASSED
+    
+    ========================= 2 passed in 6.82 seconds =========================
+
+Due to the parametrization of ``smtp`` the test will run twice with two
+different ``App`` instances and respective smtp servers.  There is no
+need for the ``app`` fixture to be aware of the ``smtp`` parametrization 
+as pytest will fully analyse the fixture dependency graph.  Note also,
+that the ``app`` fixture has a scope of ``module`` but uses a
+session-scoped ``smtp``: it is fine for fixtures to use "broader" scoped
+fixtures but not the other way round:  A session-scoped fixture could
+not use a module-scoped one in a meaningful way.
+
+.. _`automatic per-resource grouping`:
+
+Automatic grouping of tests by fixture instances
+----------------------------------------------------------
+
+.. regendoc: wipe
+
+pytest minimizes the number of active fixtures during test runs.
+If you have a parametrized fixture, then all the tests using it will
+first execute with one instance and then finalizers are called 
+before the next fixture instance is created.  Among other things,
+this eases testing of applications which create and use global state.
+
+The following example uses two parametrized funcargs, one of which is 
+scoped on a per-module basis, and all the functions perform ``print`` call s
+to show the flow of calls::
+
+    # content of test_module.py
+    import pytest
+
+    @pytest.fixture(scope="module", params=["mod1", "mod2"])
+    def modarg(request):
+        param = request.param
+        print "create", param
+        def fin():
+            print "fin", param
+        request.addfinalizer(fin)
+        return param
+
+    @pytest.fixture(scope="function", params=[1,2])
+    def otherarg(request):
+        return request.param
+
+    def test_0(otherarg):
+        print "  test0", otherarg
+    def test_1(modarg):
+        print "  test1", modarg
+    def test_2(otherarg, modarg):
+        print "  test2", otherarg, modarg
+
+Let's run the tests in verbose mode and with looking at the print-output::
+
+    $ py.test -v -s test_module.py
+    =========================== test session starts ============================
+    platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev11 -- /home/hpk/venv/1/bin/python
+    cachedir: /home/hpk/tmp/doc-exec-423/.cache
+    plugins: xdist, bugzilla, cache, oejskit, cli, timeout, pep8, cov
+    collecting ... collected 8 items
+    
+    test_module.py:16: test_0[1] PASSED
+    test_module.py:16: test_0[2] PASSED
+    test_module.py:18: test_1[mod1] PASSED
+    test_module.py:20: test_2[1-mod1] PASSED
+    test_module.py:20: test_2[2-mod1] PASSED
+    test_module.py:18: test_1[mod2] PASSED
+    test_module.py:20: test_2[1-mod2] PASSED
+    test_module.py:20: test_2[2-mod2] PASSED
+    
+    ========================= 8 passed in 0.02 seconds =========================
+      test0 1
+      test0 2
+    create mod1
+      test1 mod1
+      test2 1 mod1
+      test2 2 mod1
+    fin mod1
+    create mod2
+      test1 mod2
+      test2 1 mod2
+      test2 2 mod2
+    fin mod2
+
+You can see that the parametrized module-scoped ``modarg`` resource caused
+an ordering of test execution that lead to the fewest possible "active" resources. The finalizer for the ``mod1`` parametrized resource was executed 
+before the ``mod2`` resource was setup.
+
+
+Marking test classes, modules, projects with required fixtures
+----------------------------------------------------------------------
+
+.. regendoc:wipe
+
+Sometimes test functions do not directly get access to a fixture object.
+For example, each test in a test class may require to operate with an
+empty directory as the current working directory.  Here is how you can
+can use the standard :ref:`tempfile <lib:tempfile>` and pytest fixtures 
+to achieve it.  We separate the creation of the fixture into
+a conftest.py file::
+
+    # content of conftest.py
+    
+    import pytest
+    import tempfile
+    import os
+
+    @pytest.fixture()
+    def cleandir():
+        newpath = tempfile.mkdtemp()
+        os.chdir(newpath)
+
+and declare its use in a test module via a ``needs`` marker::
+
+    # content of test_setenv.py
+    import os
+    import pytest
+
+    @pytest.mark.needsfixtures("cleandir")
+    class TestDirectoryInit:
+        def test_cwd_starts_empty(self):
+            assert os.listdir(os.getcwd()) == []
+            with open("myfile", "w") as f:
+                f.write("hello")
+
+        def test_cwd_again_starts_empty(self):
+            assert os.listdir(os.getcwd()) == []
+
+Due to the ``needs`` class marker, the ``cleandir`` fixture
+will be required for the execution of each of the test methods, just as if
+you specified a "cleandir" function argument to each of them.  Let's run it
+to verify our fixture is activated::
+
+    $ py.test -q
+    collecting ... collected 2 items
+    .
+    2 passed in 0.01 seconds
+
+You may specify the need for multiple fixtures::
+
+    @pytest.mark.needsfixtures("cleandir", "anotherfixture")
+
+and you may specify fixture needs at the test module level, using 
+a generic feature of the mark mechanism::
+
+    pytestmark = pytest.mark.needsfixtures("cleandir")
+
+Lastly you can put fixtures required by all tests in your project 
+into an ini-file::
+
+    # content of pytest.ini
+
+    [pytest]
+    needsfixtures = cleandir
+
+Implicit fixtures at class/module/directory/global level
+----------------------------------------------------------------------
+
+.. regendoc:wipe
+
+Occasionally, you may want to have fixtures get invoked automatically
+without any ``needs`` reference.   Also, if you are used to the classical 
+xUnit setup/teardown functions you may have gotten used to fixture
+functions executing always.  As a practical example, 
+suppose we have a database fixture which has a begin/rollback/commit 
+architecture and we want to surround each test method by a transaction 
+and a rollback.  Here is a dummy self-contained implementation::
+
+    # content of test_db_transact.py
+    
+    import pytest
+
+    @pytest.fixture(scope="module")
+    class db:
+        def __init__(self):
+            self.intransaction = False
+        def begin(self):
+            self.intransaction = True
+        def rollback(Self):
+            self.intransaction = False
+
+    class TestClass:
+        @pytest.fixture(auto=True)
+        def transact(self, request, db):
+            db.begin()
+            request.addfinalizer(db.rollback)
+
+        def test_method1(self, db):
+            assert db.intransaction
+
+        def test_method2(self):
+            pass
+
+The class-level ``transact`` fixture is marked with *auto=true* which will
+mark all test methods in the class as needing the fixture.  
+
+Here is how this maps to module, project and cross-project scopes:
+
+- if an automatic fixture was defined in a test module, all its test 
+  functions would automatically invoke it.  
+
+- if defined in a conftest.py file then all tests in all test 
+  modules belows its directory will invoke the fixture.  
+
+- lastly, and **please use that with care**: if you define an automatic
+  fixture in a plugin, it will be invoked for all tests in all projects
+  where the plugin is installed.  This can be useful if a fixture only
+  anyway works in the presence of certain settings in the ini-file.  Such
+  a global fixture should thus quickly determine if it should do
+  any work and avoid expensive imports or computation otherwise.
+
+Note that the above ``transact`` fixture may very well be something that
+you want to make available in your project without having each test function
+in your project automatically using it.  The canonical way to do that is to put 
+the transact definition into a conftest.py file without using ``auto``::
+
+    # content of conftest.py
+    @pytest.fixture()
+    def transact(self, request, db):
+        db.begin()
+        request.addfinalizer(db.rollback)
+
+and then have a TestClass using it by declaring the need::
+
+    @pytest.mark.needsfixtures("transact")
+    class TestClass:
+        def test_method1(self):
+            ...
+
+While all test methods in this TestClass will thus use the transaction
+fixture, other test classes will not unless they state the need.
+
+.. currentmodule:: _pytest.python
+
+.. _`@pytest.fixture`:
+
+``@pytest.fixture``: marking a fixture function
+--------------------------------------------------------------
+
+The ``@pytest.fixture`` marker allows to
+
+* mark a function as a factory for fixtures, useable by test and other
+  fixture functions
+
+* declare a scope which determines the level of caching, i.e. how often
+  the factory will be called. Valid scopes are ``session``, ``module``, 
+  ``class`` and ``function``.
+
+* define a list of parameters in order to run dependent tests multiple 
+  times with different fixtures
+
+.. _`request`:
+
+``request``: interacting with test invocation context
+--------------------------------------------------------------
+
+The ``request`` object may be received by fixture functions
+and provides methods to:
+
+* to inspect attributes of the requesting test context, such as 
+  ``function``, ``cls``, ``module``, ``session`` and the pytest 
+  ``config`` object.  A request object passed to a parametrized factory
+  will also carry a ``request.param`` object (A parametrized factory and
+  all of its dependent tests will be called with each of the factory-specified
+  ``params``).
+
+* to add finalizers/teardowns to be invoked when the last
+  test of the requesting test context executes
+
+.. autoclass:: _pytest.python.FuncargRequest()
+    :members:
+


diff -r 45009f2213bc36057470967ff709fd4a77b5257d -r b5230e47ebefaf111624dadc34a7852418dadf3f doc/en/funcargs.txt
--- a/doc/en/funcargs.txt
+++ b/doc/en/funcargs.txt
@@ -159,366 +159,6 @@
 funcarg factories starts at test classes, then test modules, then
 ``conftest.py`` files and finally builtin and 3-rd party plugins.
 
-Creating and using a session-shared funcarg
------------------------------------------------------------------
-
-.. regendoc:wipe
-
-.. versionadded:: 2.3
-
-The `@pytest.factory`_ marker allows to
-
-* mark a function as a factory for resources, useable by test and setup
-  functions 
-
-* define parameters in order to run tests multiple times with
-  different resource instances
-
-* declare a scope which determines the level of caching, i.e. how often
-  the factory will be called. Valid scopes are ``session``, ``module``, 
-  ``class`` and ``function``.
-
-Here is a simple example of a factory creating a shared ``smtplib.SMTP``
-connection resource which test functions then may use across the whole
-test session::
-
-    # content of conftest.py
-    import pytest
-    import smtplib
-
-    @pytest.factory(scope="session")
-    def smtp(request):
-        return smtplib.SMTP("merlinux.eu")
-
-The name of the factory is ``smtp`` (the factory function name) 
-and you can access its result by listing the name ``smtp`` as
-an input parameter in any test or setup function::
-
-    # content of test_module.py
-    def test_ehlo(smtp):
-        response = smtp.ehlo()
-        assert response[0] == 250 
-        assert "merlinux" in response[1]
-        assert 0  # for demo purposes
-
-    def test_noop(smtp):
-        response = smtp.noop()
-        assert response[0] == 250
-        assert 0  # for demo purposes
-
-We deliberately insert failing ``assert 0`` statements in order to
-inspect what is going on and can now run the tests::
-
-    $ py.test -q test_module.py
-    collecting ... collected 2 items
-    FF
-    ================================= FAILURES =================================
-    ________________________________ test_ehlo _________________________________
-    
-    smtp = <smtplib.SMTP instance at 0x31bce18>
-    
-        def test_ehlo(smtp):
-            response = smtp.ehlo()
-            assert response[0] == 250
-            assert "merlinux" in response[1]
-    >       assert 0  # for demo purposes
-    E       assert 0
-    
-    test_module.py:5: AssertionError
-    ________________________________ test_noop _________________________________
-    
-    smtp = <smtplib.SMTP instance at 0x31bce18>
-    
-        def test_noop(smtp):
-            response = smtp.noop()
-            assert response[0] == 250
-    >       assert 0  # for demo purposes
-    E       assert 0
-    
-    test_module.py:10: AssertionError
-    2 failed in 0.26 seconds
-
-you see the two ``assert 0`` failing and can also see that
-the same (session-scoped) object was passed into the two test functions.
-
-
-Parametrizing a session-shared funcarg resource
------------------------------------------------------------------
-
-Extending the previous example, we can flag the factory to create
-two ``smtp`` values which will cause all tests using it to
-run twice with two different values.  The factory function gets
-access to each parameter through the special `request`_ object::
-
-    # content of conftest.py
-    import pytest
-    import smtplib
-
-    @pytest.factory(scope="session", 
-                    params=["merlinux.eu", "mail.python.org"])
-    def smtp(request):
-        return smtplib.SMTP(request.param)
-
-The main change is the definition of a ``params`` list in the
-``factory``-marker and the ``request.param`` access within the
-factory function.  No test function code needs to change.  
-So let's just do another run::
-
-    $ py.test -q
-    collecting ... collected 4 items
-    FFFF
-    ================================= FAILURES =================================
-    __________________________ test_ehlo[merlinux.eu] __________________________
-    
-    smtp = <smtplib.SMTP instance at 0x28dc5a8>
-    
-        def test_ehlo(smtp):
-            response = smtp.ehlo()
-            assert response[0] == 250
-            assert "merlinux" in response[1]
-    >       assert 0  # for demo purposes
-    E       assert 0
-    
-    test_module.py:5: AssertionError
-    __________________________ test_noop[merlinux.eu] __________________________
-    
-    smtp = <smtplib.SMTP instance at 0x28dc5a8>
-    
-        def test_noop(smtp):
-            response = smtp.noop()
-            assert response[0] == 250
-    >       assert 0  # for demo purposes
-    E       assert 0
-    
-    test_module.py:10: AssertionError
-    ________________________ test_ehlo[mail.python.org] ________________________
-    
-    smtp = <smtplib.SMTP instance at 0x28e3e18>
-    
-        def test_ehlo(smtp):
-            response = smtp.ehlo()
-            assert response[0] == 250
-    >       assert "merlinux" in response[1]
-    E       assert 'merlinux' in 'mail.python.org\nSIZE 10240000\nETRN\nSTARTTLS\nENHANCEDSTATUSCODES\n8BITMIME\nDSN'
-    
-    test_module.py:4: AssertionError
-    ________________________ test_noop[mail.python.org] ________________________
-    
-    smtp = <smtplib.SMTP instance at 0x28e3e18>
-    
-        def test_noop(smtp):
-            response = smtp.noop()
-            assert response[0] == 250
-    >       assert 0  # for demo purposes
-    E       assert 0
-    
-    test_module.py:10: AssertionError
-    4 failed in 6.17 seconds
-
-We get four failures because we are running the two tests twice with
-different ``smtp`` instantiations as defined on the factory.
-Note that with the ``mail.python.org`` connection the second test
-fails in ``test_ehlo`` because it expects a specific server string.
-    
-Adding a finalizer to the parametrized resource
---------------------------------------------------------
-
-Further extending the ``smtp`` example, we now want to properly
-close a smtp server connection after the last test using it
-has been run.  We can do this by calling the ``request.addfinalizer()``
-helper::
-
-    # content of conftest.py
-    import pytest
-    import smtplib
-
-    @pytest.factory(scope="session", 
-                    params=["merlinux.eu", "mail.python.org"])
-    def smtp(request):
-        smtp = smtplib.SMTP(request.param)
-        def fin():
-            print ("finalizing %s" % smtp)
-            smtp.close()
-        request.addfinalizer(fin)
-        return smtp
-
-We also add a print call and then run py.test without the default
-output capturing and disabled traceback reporting::
-
-    $ py.test -s -q --tb=no
-    collecting ... collected 4 items
-    FFFF
-    4 failed in 6.40 seconds
-    finalizing <smtplib.SMTP instance at 0x125d3b0>
-    finalizing <smtplib.SMTP instance at 0x1265b90>
-
-We see that the two ``smtp`` instances are finalized appropriately.
-
-Looking at test collection without running tests
-------------------------------------------------------
-
-You can also look at what tests pytest collects without running them::
-
-    $ py.test --collectonly
-    =========================== test session starts ============================
-    platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev11
-    plugins: xdist, bugzilla, cache, oejskit, cli, timeout, pep8, cov
-    collecting ... collected 4 items
-    <Module 'test_module.py'>
-      <Function 'test_ehlo[merlinux.eu]'>
-      <Function 'test_noop[merlinux.eu]'>
-      <Function 'test_ehlo[mail.python.org]'>
-      <Function 'test_noop[mail.python.org]'>
-    
-    =============================  in 0.01 seconds =============================
-
-Note that pytest orders your test run by resource usage, minimizing
-the number of active resources at any given time.
-
-
-.. _`interdependent resources`:
-
-Interdepdendent resources
-----------------------------------------------------------
-
-You can not only use funcargs in test functions but also in their factories
-themselves.  Extending the previous example we can instantiate another
-object ``app`` and stick the ``smtp`` resource into it like this::
-
-    # content of test_appsetup.py
-   
-    import pytest
-
-    @pytest.factory(scope="module")
-    class app:
-        def __init__(self, smtp):
-            self.smtp = smtp
-
-    def test_exists(app):
-        assert app.smtp
-
-Here we declare an ``app`` class to be a factory and have its init-method
-use the previously defined ``smtp`` resource.  Let's run it::
-
-    $ py.test -v test_appsetup.py
-    =========================== test session starts ============================
-    platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev11 -- /home/hpk/venv/1/bin/python
-    cachedir: /home/hpk/tmp/doc-exec-423/.cache
-    plugins: xdist, bugzilla, cache, oejskit, cli, timeout, pep8, cov
-    collecting ... collected 2 items
-    
-    test_appsetup.py:12: test_exists[merlinux.eu] PASSED
-    test_appsetup.py:12: test_exists[mail.python.org] PASSED
-    
-    ========================= 2 passed in 6.82 seconds =========================
-
-Due to the parametrization of ``smtp`` the test will run twice with two
-different ``App`` instances and respective smtp servers.  There is no
-need for the ``app`` factory to be aware of the parametrization.  Note
-that the ``app`` factory has a scope of ``module`` but uses the
-session-scoped ``smtp`` object: it is fine for factories to use
-"broader" scoped resources but not the other way round.  A
-session-scoped resource could not use a module-scoped resource in a
-meaningful way.
-
-.. _`automatic per-resource grouping`:
-
-Grouping tests by resource parameters
-----------------------------------------------------------
-
-.. regendoc: wipe
-
-pytest minimizes the number of active resources during test runs.
-If you have a parametrized resource, then all the tests using one
-resource instance will execute one after another.  Then any finalizers
-are called for that resource instance and then the next parametrized
-resource instance is created and its tests are run.  Among other things,
-this eases testing of applications which create and use global state.
-
-The following example uses two parametrized funcargs, one of which is 
-scoped on a per-module basis, and all the functions perform ``print`` call s
-to show the flow of calls::
-
-    # content of test_module.py
-    import pytest
-
-    @pytest.factory(scope="module", params=["mod1", "mod2"])
-    def modarg(request):
-        param = request.param
-        print "create", param
-        def fin():
-            print "fin", param
-        request.addfinalizer(fin)
-        return param
-
-    @pytest.factory(scope="function", params=[1,2])
-    def otherarg(request):
-        return request.param
-
-    def test_0(otherarg):
-        print "  test0", otherarg
-    def test_1(modarg):
-        print "  test1", modarg
-    def test_2(otherarg, modarg):
-        print "  test2", otherarg, modarg
-
-Let's run the tests in verbose mode and with looking at the print-output::
-
-    $ py.test -v -s test_module.py
-    =========================== test session starts ============================
-    platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev11 -- /home/hpk/venv/1/bin/python
-    cachedir: /home/hpk/tmp/doc-exec-423/.cache
-    plugins: xdist, bugzilla, cache, oejskit, cli, timeout, pep8, cov
-    collecting ... collected 8 items
-    
-    test_module.py:16: test_0[1] PASSED
-    test_module.py:16: test_0[2] PASSED
-    test_module.py:18: test_1[mod1] PASSED
-    test_module.py:20: test_2[1-mod1] PASSED
-    test_module.py:20: test_2[2-mod1] PASSED
-    test_module.py:18: test_1[mod2] PASSED
-    test_module.py:20: test_2[1-mod2] PASSED
-    test_module.py:20: test_2[2-mod2] PASSED
-    
-    ========================= 8 passed in 0.02 seconds =========================
-      test0 1
-      test0 2
-    create mod1
-      test1 mod1
-      test2 1 mod1
-      test2 2 mod1
-    fin mod1
-    create mod2
-      test1 mod2
-      test2 1 mod2
-      test2 2 mod2
-    fin mod2
-
-You can see that the parametrized module-scoped ``modarg`` resource caused
-an ordering of test execution that lead to the fewest possible "active" resources. The finalizer for the ``mod1`` parametrized resource was executed 
-before the ``mod2`` resource was setup.
-
-.. currentmodule:: _pytest.python
-.. _`request`:
-
-``request``: interacting with test invocation context
--------------------------------------------------------
-
-The ``request`` object may be received by `@pytest.factory`_ or
-:ref:`@pytest.setup <setup>` marked functions and provides methods
-
-* to inspect attributes of the requesting test context, such as 
-  ``function``, ``cls``, ``module``, ``session`` and the pytest 
-  ``config`` object.  A request object passed to a parametrized factory
-  will also carry a ``request.param`` object (A parametrized factory and
-  all of its dependent tests will be called with each of the factory-specified
-  ``params``).
-
-* to add finalizers/teardowns to be invoked when the last
-  test of the requesting test context executes
-
-.. autoclass:: _pytest.python.FuncargRequest()
-    :members:
 
 
 .. _`test generators`:


diff -r 45009f2213bc36057470967ff709fd4a77b5257d -r b5230e47ebefaf111624dadc34a7852418dadf3f doc/en/setup.txt
--- a/doc/en/setup.txt
+++ b/doc/en/setup.txt
@@ -1,212 +1,12 @@
-.. _xunitsetup:
-.. _setup:
-.. _`setup functions`:
-.. _`@pytest.setup`:
 
-``@setup`` functions or: xunit on steroids
+Page has moved to fixture
 ========================================================
 
-.. versionadded:: 2.3
+During development prior to the pytest-2.3 release the name
+``pytest.setup`` was used but before the release it was renamed
+to :ref:`pytest.fixture` mainly to avoid the misconception that there 
+should be a ``pytest.teardown`` as well. 
 
-.. _`funcargs`: funcargs.html
-.. _`test parametrization`: funcargs.html#parametrizing-tests
-.. _`unittest plugin`: plugin/unittest.html
-.. _`xUnit`: http://en.wikipedia.org/wiki/XUnit
+Please refer to :ref:`pytest.fixture` for information on the new
+fixture functions.
 
-Python, Java and many other languages support a so called xUnit_ style 
-of resource setup.  This typically involves the call of a ``setup``
-("fixture") method before running a test function and ``teardown`` after
-it has finished.  Unlike :ref:`injected resources <resources>` setup
-functions work indirectly by causing global side effects or 
-setting test case attributes which test methods can then access.  
-
-pytest originally introduced in 2005 a scope-specific model of detecting
-setup and teardown functions on a per-module, class or function basis.
-The Python unittest package and nose have subsequently incorporated them.
-This model remains supported by pytest as :ref:`old-style xunit`.
-
-Moreover, pytest-2.3 introduces a new ``pytest.setup()`` decorator
-to mark functions as setup functions which allow to implement everything
-you can do with the old-style and much more.  Specifically setup functions:
-
-- can receive :ref:`resources through funcargs <resources>`,
-- fully interoperate with parametrized resources,
-- can be defined in a plugin or :ref:`conftest.py <conftest.py>` file and get called 
-  on a per-session, per-module, per-class or per-function basis,
-- can access the :ref:`request <request>` for which the setup is called,
-- can precisely control teardown by registering one or multiple 
-  teardown functions as soon as they have performed some actions 
-  which need undoing, eliminating the no need for a separate 
-  "teardown" decorator.
-- allow to separate different setup concerns even if they
-  happen to work in the same scope
-
-All of these features are now demonstrated by little examples.
-
-.. _`new_setup`:
-.. _`@pytest.setup`:
-
-basic per-function setup
--------------------------------
-
-.. regendoc:wipe
-
-Suppose you want to have a clean directory with a single
-file entry for each test function in a module and have
-the test execute with this directory as current working dir::
-
-    # content of test_funcdir.py
-    import pytest
-    import os
-
-    @pytest.setup()
-    def mydir(tmpdir):
-        tmpdir.join("myfile").write("example content")
-        old = tmpdir.chdir()
-
-    def test_function1():
-        assert os.path.exists("myfile")
-        f = open("anotherfile", "w")
-        f.write("")
-        f.close()
-
-    def test_function2():
-        assert os.path.exists("myfile")
-        assert not os.path.exists("anotherfile")
-
-Our ``mydir`` setup function is executed on a per-function basis,
-the default scope used by the ``pytest.setup`` decorator.
-It accesses the ``tmpdir`` resource which provides a new empty
-directory path object.  The ``test_function2`` here checks that 
-it executes with a fresh directory and that it
-does not see the previously created ``anotherfile``.  We can
-thus expect two passing tests::
-
-    $ py.test -v
-    =========================== test session starts ============================
-    platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev7 -- /home/hpk/venv/1/bin/python
-    cachedir: /home/hpk/tmp/doc-exec-410/.cache
-    plugins: xdist, bugzilla, cache, oejskit, cli, pep8, cov
-    collecting ... collected 2 items
-    
-    test_funcdir.py:9: test_function1 PASSED
-    test_funcdir.py:15: test_function2 PASSED
-    
-    ========================= 2 passed in 0.26 seconds =========================
-
-per-function setup, for every function of a project
-------------------------------------------------------------
-
-If you want to define a setup per-function but want to apply
-it to every function in your project you don't need to duplicate
-the setup-definition into each test module.  Instead you can put
-it into a ``conftest.py`` file into the root of your project::
-
-    # content of conftest.py
-    import pytest
-    import os
-
-    @pytest.setup()
-    def cleandir(tmpdir):
-        old = tmpdir.chdir()
-
-The ``cleandir`` setup function will be called for every test function
-below the directory tree where ``conftest.py`` resides.  In this
-case it just uses the builtin ``tmpdir`` resource to change to the
-empty directory ahead of running a test.
-
-test modules accessing a global resource
--------------------------------------------------------
-
-.. note::
-
-    Relying on `global state is considered bad programming practise <http://en.wikipedia.org/wiki/Global_variable>`_ but when you work with an application
-    that relies on it you often have no choice.
-
-If you want test modules to access a global resource,
-you can stick the resource to the module globals in
-a per-module setup function.  We use a :ref:`resource factory
-<@pytest.factory>` to create our global resource::
-
-    # content of conftest.py
-    import pytest
-
-    class GlobalResource:
-        def __init__(self):
-            pass
-
-    @pytest.factory(scope="session")
-    def globresource():
-        return GlobalResource()
-
-    @pytest.setup(scope="module")
-    def setresource(request, globresource):
-        request.module.globresource = globresource
-       
-Now any test module can access ``globresource`` as a module global::
-
-    # content of test_glob.py
-
-    def test_1():
-        print ("test_1 %s" % globresource)
-    def test_2():
-        print ("test_2 %s" % globresource)
-
-Let's run this module without output-capturing::
-
-    $ py.test -qs test_glob.py
-    collecting ... collected 2 items
-    ..
-    2 passed in 0.02 seconds
-    test_1 <conftest.GlobalResource instance at 0x13197e8>
-    test_2 <conftest.GlobalResource instance at 0x13197e8>
-
-The two tests see the same global ``globresource`` object.
-
-Parametrizing the global resource
-+++++++++++++++++++++++++++++++++++++++++++++++++
-
-We extend the previous example and add parametrization to the globresource 
-factory and also add a finalizer::
-
-    # content of conftest.py
-
-    import pytest
-
-    class GlobalResource:
-        def __init__(self, param):
-            self.param = param
-
-    @pytest.factory(scope="session", params=[1,2])
-    def globresource(request):
-        g = GlobalResource(request.param)
-        def fin():
-            print "finalizing", g
-        request.addfinalizer(fin)
-        return g
-
-    @pytest.setup(scope="module")
-    def setresource(request, globresource):
-        request.module.globresource = globresource
-
-And then re-run our test module::
-
-    $ py.test -qs test_glob.py
-    collecting ... collected 4 items
-    ....
-    4 passed in 0.02 seconds
-    test_1 <conftest.GlobalResource instance at 0x1922e18>
-    test_2 <conftest.GlobalResource instance at 0x1922e18>
-    finalizing <conftest.GlobalResource instance at 0x1922e18>
-    test_1 <conftest.GlobalResource instance at 0x1925518>
-    test_2 <conftest.GlobalResource instance at 0x1925518>
-    finalizing <conftest.GlobalResource instance at 0x1925518>
-
-We are now running the two tests twice with two different global resource
-instances.  Note that the tests are ordered such that only
-one instance is active at any given time: the finalizer of 
-the first globresource instance is called before the second
-instance is created and sent to the setup functions.
-
-
-


diff -r 45009f2213bc36057470967ff709fd4a77b5257d -r b5230e47ebefaf111624dadc34a7852418dadf3f doc/en/xunit_setup.txt
--- a/doc/en/xunit_setup.txt
+++ b/doc/en/xunit_setup.txt
@@ -1,16 +1,16 @@
 
-.. _`old-style xunit`:
+.. _`classic xunit`:
 
-Old-style xunit-style setup
+classic xunit-style setup
 ========================================
 
 .. note:: 
 
     This section describes the old way how you can implement setup and
     teardown on a per-module/class/function basis.  It remains fully
-    supported but it is recommended to rather use :ref:`@setup functions
-    <setup>` or :ref:`injected resources <resources>` for implementing your
-    setup needs.
+    supported but it is recommended to rather use :ref:`fixture functions
+    <fixture>` or :ref:`funcargs <resources>` for implementing your
+    needs to prepare and fix the test state for your tests.
 
 Module level setup/teardown
 --------------------------------------



https://bitbucket.org/hpk42/pytest/changeset/de544d09912b/
changeset:   de544d09912b
user:        hpk42
date:        2012-10-05 10:21:35
summary:     rename pytest.factory usages into pytest.fixture ones
affected #:  8 files

diff -r b5230e47ebefaf111624dadc34a7852418dadf3f -r de544d09912bf791c6635f023ce153348e38e961 _pytest/python.py
--- a/_pytest/python.py
+++ b/_pytest/python.py
@@ -10,12 +10,12 @@
 import _pytest
 cutdir = py.path.local(_pytest.__file__).dirpath()
 
-class FactoryMarker:
+class FixtureFunctionMarker:
     def __init__(self, scope, params):
         self.scope = scope
         self.params = params
     def __call__(self, function):
-        function._pytestfactory = self
+        function._pytestfixturefunction = self
         return function
 
 class SetupMarker:
@@ -26,18 +26,32 @@
         return function
 
 # XXX a test fails when scope="function" how it should be, investigate
-def factory(scope=None, params=None):
-    """ return a decorator to mark functions as resource factories.
+def fixture(scope=None, params=None):
+    """ return a decorator to mark a fixture factory function.
 
-    :arg scope: the scope for which this resource is shared, one of
+    The name of the fixture function can be referenced in a test context
+    to cause activation ahead of running tests.  Test modules or classes
+    can use the pytest.mark.needsfixtures(fixturename) marker to specify
+    needed fixtures.  Test functions can use fixture names as input arguments
+    in which case the object returned from the fixture function will be
+    injected.
+
+    :arg scope: the scope for which this fixture is shared, one of
                 "function", "class", "module", "session". Defaults to "function".
     :arg params: an optional list of parameters which will cause multiple
-                invocations of tests depending on the resource.
+                invocations of the fixture functions and their dependent
+                tests.
     """
-    return FactoryMarker(scope, params)
+    return FixtureFunctionMarker(scope, params)
 
 def setup(scope="function"):
-    """ return a decorator to mark functions as setup functions.
+    """ return a decorator to mark a function as providing a fixture for
+    a testcontext.  A fixture function is executed for each scope and may
+    receive funcargs which allows it to initialise and provide implicit
+    test state.  A fixture function may receive the "testcontext" object
+    and register a finalizer via "testcontext.addfinalizer(finalizer)"
+    which will be called when the last test in the testcontext has
+    executed.
 
     :arg scope: the scope for which the setup function will be active, one
                 of "function", "class", "module", "session".
@@ -112,7 +126,7 @@
 def pytest_namespace():
     raises.Exception = pytest.fail.Exception
     return {
-        'factory': factory,
+        'fixture': fixture,
         'setup': setup,
         'raises' : raises,
         'collect': {
@@ -1377,9 +1391,9 @@
                 continue
             # resource factories either have a pytest_funcarg__ prefix
             # or are "funcarg" marked
-            marker = getattr(obj, "_pytestfactory", None)
+            marker = getattr(obj, "_pytestfixturefunction", None)
             if marker is not None:
-                if not isinstance(marker, FactoryMarker):
+                if not isinstance(marker, FixtureFunctionMarker):
                     # magic globals  with __getattr__
                     # give us something thats wrong for that case
                     continue


diff -r b5230e47ebefaf111624dadc34a7852418dadf3f -r de544d09912bf791c6635f023ce153348e38e961 doc/en/example/costlysetup/conftest.py
--- a/doc/en/example/costlysetup/conftest.py
+++ b/doc/en/example/costlysetup/conftest.py
@@ -1,7 +1,7 @@
 
 import pytest
 
- at pytest.factory("session")
+ at pytest.fixture("session")
 def setup(request):
     setup = CostlySetup()
     request.addfinalizer(setup.finalize)


diff -r b5230e47ebefaf111624dadc34a7852418dadf3f -r de544d09912bf791c6635f023ce153348e38e961 doc/en/example/multipython.py
--- a/doc/en/example/multipython.py
+++ b/doc/en/example/multipython.py
@@ -5,12 +5,12 @@
 import py, pytest
 
 pythonlist = ['python2.4', 'python2.5', 'python2.6', 'python2.7', 'python2.8']
- at pytest.factory(params=pythonlist)
+ at pytest.fixture(params=pythonlist)
 def python1(request, tmpdir):
     picklefile = tmpdir.join("data.pickle")
     return Python(request.param, picklefile)
 
- at pytest.factory(params=pythonlist)
+ at pytest.fixture(params=pythonlist)
 def python2(request, python1):
     return Python(request.param, python1.picklefile)
 


diff -r b5230e47ebefaf111624dadc34a7852418dadf3f -r de544d09912bf791c6635f023ce153348e38e961 doc/en/faq.txt
--- a/doc/en/faq.txt
+++ b/doc/en/faq.txt
@@ -125,7 +125,7 @@
 
 .. note::
 
-    With pytest-2.3 you can use the :ref:`@pytest.factory` decorator
+    With pytest-2.3 you can use the :ref:`@pytest.fixture` decorator
     to mark a function as a funcarg factory.  
 
 .. _`Convention over Configuration`: http://en.wikipedia.org/wiki/Convention_over_Configuration
@@ -146,7 +146,7 @@
   policy - in real-world examples some combinations
   often should not run.
 
-However, with pytest-2.3 you can use the :ref:`@pytest.factory` decorator
+However, with pytest-2.3 you can use the :ref:`@pytest.fixture` decorator
 and specify ``params`` so that all tests depending on the factory-created
 resource will run multiple times with different parameters.
 


diff -r b5230e47ebefaf111624dadc34a7852418dadf3f -r de544d09912bf791c6635f023ce153348e38e961 doc/en/funcarg_compare.txt
--- a/doc/en/funcarg_compare.txt
+++ b/doc/en/funcarg_compare.txt
@@ -63,9 +63,9 @@
 Direct scoping of funcarg factories
 --------------------------------------------------------
 
-Instead of calling cached_setup(), you can use the :ref:`@pytest.factory <@pytest.factory>` decorator and directly state the scope::
+Instead of calling cached_setup(), you can use the :ref:`@pytest.fixture <@pytest.fixture>` decorator and directly state the scope::
 
-    @pytest.factory(scope="session")
+    @pytest.fixture(scope="session")
     def db(request):
         # factory will only be invoked once per session - 
         db = DataBase()
@@ -87,7 +87,7 @@
 parametrization, i.e. calling a test multiple times with different value
 sets.  pytest-2.3 introduces a decorator for use on the factory itself::
 
-    @pytest.factory(params=["mysql", "pg"])
+    @pytest.fixture(params=["mysql", "pg"])
     def db(request):
         ... # use request.param
 
@@ -104,7 +104,7 @@
 
 Of course it's perfectly fine to combine parametrization and scoping::
 
-    @pytest.factory(scope="session", params=["mysql", "pg"])
+    @pytest.fixture(scope="session", params=["mysql", "pg"])
     def db(request):
         if request.param == "mysql":
             db = MySQL()
@@ -125,7 +125,7 @@
 denotes the name under which the resource can be accessed as a function
 argument::
 
-    @pytest.factory()
+    @pytest.fixture()
     def db(request):
         ...
 


diff -r b5230e47ebefaf111624dadc34a7852418dadf3f -r de544d09912bf791c6635f023ce153348e38e961 doc/en/funcargs.txt
--- a/doc/en/funcargs.txt
+++ b/doc/en/funcargs.txt
@@ -51,7 +51,7 @@
 
 Concretely, there are three main means of funcarg management:
 
-* a `@pytest.factory`_ marker to define resource factories,
+* a `@pytest.fixture`_ marker to define resource factories,
   their scoping and parametrization.   Factories can themselves 
   receive resources through their function arguments, easing
   the setup of `interdependent resources`_.  Factories can use
@@ -77,9 +77,9 @@
 setup statically into the test source code, leading to duplicate and
 hard-to change fixtures.
 
-.. _`@pytest.factory`:
+.. _`@pytest.fixture`:
 
-``@pytest.factory``: Creating parametrized, scoped resources
+``@pytest.fixture``: Creating parametrized, scoped resources
 =====================================================================
 
 Basic funcarg injection example
@@ -91,7 +91,7 @@
     # content of ./test_simplefactory.py
     import pytest
 
-    @pytest.factory()
+    @pytest.fixture()
     def myfuncarg():
         return 42
 
@@ -99,7 +99,7 @@
         assert myfuncarg == 17
 
 Here, the ``test_function`` needs an object named ``myfuncarg`` and thus
-py.test will discover and call the ``@pytest.factory`` marked ``myfuncarg`` 
+py.test will discover and call the ``@pytest.fixture`` marked ``myfuncarg`` 
 factory function.  Running the tests looks like this::
 
     $ py.test test_simplefactory.py
@@ -168,7 +168,7 @@
 Parametrizing test functions
 ==========================================================================
 
-While the `@pytest.factory`_ decorator allows to define parametrization
+While the `@pytest.fixture`_ decorator allows to define parametrization
 of funcarg resources at the factory-level, there are also means to
 define parametrization at test functions directly:
 
@@ -365,18 +365,18 @@
 
 * previously funcarg factories were specified with a special 
   ``pytest_funcarg__NAME`` prefix instead of using the 
-  ``@pytest.factory`` decorator.
+  ``@pytest.fixture`` decorator.
 
 * Factories received a `request`_ object which managed caching through
   ``request.cached_setup()`` calls and allowed using other funcargs via 
   ``request.getfuncargvalue()`` calls.  These intricate APIs made it hard 
   to do proper parametrization and implement resource caching. The
-  new ``@pytest.factory`` decorator allows to simply declare the scope
+  new ``@pytest.fixture`` decorator allows to simply declare the scope
   and let pytest figure things out for you.
 
 * if you used parametrization and funcarg factories which made use of
   ``request.cached_setup()`` it is recommeneded to invest a few minutes
-  and simplify your funcarg factory code to use the `@pytest.factory`_ 
+  and simplify your funcarg factory code to use the `@pytest.fixture`_ 
   decorator instead.  This will also allow to take advantage of 
   the `automatic per-resource grouping`_ of tests.
 


diff -r b5230e47ebefaf111624dadc34a7852418dadf3f -r de544d09912bf791c6635f023ce153348e38e961 doc/en/unittest.txt
--- a/doc/en/unittest.txt
+++ b/doc/en/unittest.txt
@@ -82,7 +82,7 @@
     import pytest
     import unittest
 
-    @pytest.factory()
+    @pytest.fixture()
     def db():
         class DummyDB:
             x = 1


diff -r b5230e47ebefaf111624dadc34a7852418dadf3f -r de544d09912bf791c6635f023ce153348e38e961 testing/test_python.py
--- a/testing/test_python.py
+++ b/testing/test_python.py
@@ -744,7 +744,7 @@
     def test_accessmarker_function(self, testdir):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory()
+            @pytest.fixture()
             def markers(request):
                 return request.node.markers
             @pytest.mark.XYZ
@@ -758,7 +758,7 @@
     def test_accessmarker_dynamic(self, testdir):
         testdir.makeconftest("""
             import pytest
-            @pytest.factory()
+            @pytest.fixture()
             def markers(request):
                 return request.node.markers
 
@@ -1674,11 +1674,11 @@
     def test_receives_funcargs(self, testdir):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory()
+            @pytest.fixture()
             def arg1():
                 return 1
 
-            @pytest.factory()
+            @pytest.fixture()
             def arg2(arg1):
                 return arg1 + 1
 
@@ -1694,11 +1694,11 @@
     def test_receives_funcargs_scope_mismatch(self, testdir):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory(scope="function")
+            @pytest.fixture(scope="function")
             def arg1():
                 return 1
 
-            @pytest.factory(scope="module")
+            @pytest.fixture(scope="module")
             def arg2(arg1):
                 return arg1 + 1
 
@@ -1717,12 +1717,12 @@
         testdir.makepyfile("""
             import pytest
             l = []
-            @pytest.factory(params=[1,2])
+            @pytest.fixture(params=[1,2])
             def arg1(request):
                 l.append(1)
                 return request.param
 
-            @pytest.factory()
+            @pytest.fixture()
             def arg2(arg1):
                 return arg1 + 1
 
@@ -1739,11 +1739,11 @@
         testdir.makepyfile("""
             import pytest
 
-            @pytest.factory()
+            @pytest.fixture()
             def fail(missing):
                 return
 
-            @pytest.factory()
+            @pytest.fixture()
             def call_fail(fail):
                 return
 
@@ -1764,7 +1764,7 @@
             class arg1:
                 def __init__(self, request):
                     self.x = 1
-            arg1 = pytest.factory()(arg1)
+            arg1 = pytest.fixture()(arg1)
 
             class MySetup:
                 def __init__(self, request, arg1):
@@ -1781,7 +1781,7 @@
     def test_request_can_be_overridden(self, testdir):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory()
+            @pytest.fixture()
             def request(request):
                 request.a = 1
                 return request
@@ -1863,7 +1863,7 @@
             def perfunction(request, tmpdir):
                 pass
 
-            @pytest.factory()
+            @pytest.fixture()
             def arg1(tmpdir):
                 pass
             @pytest.setup()
@@ -1918,7 +1918,7 @@
             def enabled(parentnode, markers):
                 return "needsdb" in markers
 
-            @pytest.factory(params=[1,2])
+            @pytest.fixture(params=[1,2])
             def db(request):
                 return request.param
 
@@ -1959,7 +1959,7 @@
         testdir.makepyfile("""
             import pytest
             l = []
-            @pytest.factory(scope="module")
+            @pytest.fixture(scope="module")
             def arg():
                 l.append(1)
                 return 0
@@ -1984,7 +1984,7 @@
         testdir.makepyfile("""
             import pytest
             l = []
-            @pytest.factory(params=[1,2])
+            @pytest.fixture(params=[1,2])
             def arg(request):
                 return request.param
 
@@ -2010,7 +2010,7 @@
 
             l = []
 
-            @pytest.factory(scope="session", params=[1,2])
+            @pytest.fixture(scope="session", params=[1,2])
             def arg(request):
                return request.param
 
@@ -2036,11 +2036,11 @@
 
             l = []
 
-            @pytest.factory(scope="function", params=[1,2])
+            @pytest.fixture(scope="function", params=[1,2])
             def farg(request):
                 return request.param
 
-            @pytest.factory(scope="class", params=list("ab"))
+            @pytest.fixture(scope="class", params=list("ab"))
             def carg(request):
                 return request.param
 
@@ -2117,7 +2117,7 @@
     def test_parametrize(self, testdir):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory(params=["a", "b", "c"])
+            @pytest.fixture(params=["a", "b", "c"])
             def arg(request):
                 return request.param
             l = []
@@ -2133,7 +2133,7 @@
         testdir.makepyfile("""
             import pytest
             l = []
-            @pytest.factory(scope="module")
+            @pytest.fixture(scope="module")
             def arg():
                 l.append(1)
                 return 1
@@ -2155,7 +2155,7 @@
         testdir.makepyfile("""
             import pytest
             l = []
-            @pytest.factory(scope="module")
+            @pytest.fixture(scope="module")
             def arg():
                 l.append(1)
                 return 1
@@ -2178,7 +2178,7 @@
             import pytest
             finalized = []
             created = []
-            @pytest.factory(scope="module")
+            @pytest.fixture(scope="module")
             def arg(request):
                 created.append(1)
                 assert request.scope == "module"
@@ -2217,14 +2217,14 @@
             import pytest
             finalized = []
             created = []
-            @pytest.factory(scope="function")
+            @pytest.fixture(scope="function")
             def arg(request):
                 pass
         """)
         testdir.makepyfile(
             test_mod1="""
                 import pytest
-                @pytest.factory(scope="session")
+                @pytest.fixture(scope="session")
                 def arg(request):
                     %s
                 def test_1(arg):
@@ -2239,14 +2239,14 @@
     def test_register_only_with_mark(self, testdir):
         testdir.makeconftest("""
             import pytest
-            @pytest.factory()
+            @pytest.fixture()
             def arg():
                 return 1
         """)
         testdir.makepyfile(
             test_mod1="""
                 import pytest
-                @pytest.factory()
+                @pytest.fixture()
                 def arg(arg):
                     return arg + 1
                 def test_1(arg):
@@ -2258,7 +2258,7 @@
     def test_parametrize_and_scope(self, testdir):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory(scope="module", params=["a", "b", "c"])
+            @pytest.fixture(scope="module", params=["a", "b", "c"])
             def arg(request):
                 return request.param
             l = []
@@ -2276,13 +2276,13 @@
     def test_scope_mismatch(self, testdir):
         testdir.makeconftest("""
             import pytest
-            @pytest.factory(scope="function")
+            @pytest.fixture(scope="function")
             def arg(request):
                 pass
         """)
         testdir.makepyfile("""
             import pytest
-            @pytest.factory(scope="session")
+            @pytest.fixture(scope="session")
             def arg(arg):
                 pass
             def test_mismatch(arg):
@@ -2298,7 +2298,7 @@
         testdir.makepyfile("""
             import pytest
 
-            @pytest.factory(scope="module", params=[1, 2])
+            @pytest.fixture(scope="module", params=[1, 2])
             def arg(request):
                 return request.param
 
@@ -2317,10 +2317,10 @@
         testdir.makeconftest("""
             import pytest
 
-            @pytest.factory(scope="session", params="s1 s2".split())
+            @pytest.fixture(scope="session", params="s1 s2".split())
             def sarg():
                 pass
-            @pytest.factory(scope="module", params="m1 m2".split())
+            @pytest.fixture(scope="module", params="m1 m2".split())
             def marg():
                 pass
         """)
@@ -2365,11 +2365,11 @@
 
             l = []
 
-            @pytest.factory(scope="function", params=[1,2])
+            @pytest.fixture(scope="function", params=[1,2])
             def farg(request):
                 return request.param
 
-            @pytest.factory(scope="class", params=list("ab"))
+            @pytest.fixture(scope="class", params=list("ab"))
             def carg(request):
                 return request.param
 
@@ -2411,14 +2411,14 @@
         testdir.makepyfile("""
             import pytest
 
-            @pytest.factory(scope="function", params=[1, 2])
+            @pytest.fixture(scope="function", params=[1, 2])
             def arg(request):
                 param = request.param
                 request.addfinalizer(lambda: l.append("fin:%s" % param))
                 l.append("create:%s" % param)
                 return request.param
 
-            @pytest.factory(scope="module", params=["mod1", "mod2"])
+            @pytest.fixture(scope="module", params=["mod1", "mod2"])
             def modarg(request):
                 param = request.param
                 request.addfinalizer(lambda: l.append("fin:%s" % param))
@@ -2455,7 +2455,7 @@
         testdir.makepyfile("""
             import pytest
 
-            @pytest.factory(scope="module", params=[1, 2])
+            @pytest.fixture(scope="module", params=[1, 2])
             def arg(request):
                 request.config.l = l # to access from outer
                 x = request.param
@@ -2484,7 +2484,7 @@
         testdir.makepyfile("""
             import pytest
 
-            @pytest.factory(scope="function", params=[1, 2])
+            @pytest.fixture(scope="function", params=[1, 2])
             def arg(request):
                 x = request.param
                 request.addfinalizer(lambda: l.append("fin%s" % x))
@@ -2506,7 +2506,7 @@
         testdir.makepyfile("""
             import pytest
 
-            @pytest.factory(scope="module", params=[1, 2])
+            @pytest.fixture(scope="module", params=[1, 2])
             def arg(request):
                 return request.param
 
@@ -2562,7 +2562,7 @@
     def test_funcarg(self, testdir, scope, ok, error):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory(scope=%r)
+            @pytest.fixture(scope=%r)
             def arg(request):
                 for x in %r:
                     assert hasattr(request, x)
@@ -2582,7 +2582,7 @@
     def test_subfactory_missing_funcarg(self, testdir):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory()
+            @pytest.fixture()
             def gen(qwe123):
                 return 1
             def test_something(gen):
@@ -2618,7 +2618,7 @@
     def test_newstyle_with_request(self, testdir):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory()
+            @pytest.fixture()
             def arg(request):
                 pass
             def test_1(arg):
@@ -2630,7 +2630,7 @@
     def test_setupcontext_no_param(self, testdir):
         testdir.makepyfile("""
             import pytest
-            @pytest.factory(params=[1,2])
+            @pytest.fixture(params=[1,2])
             def arg(request):
                 return request.param
 
@@ -2683,7 +2683,7 @@
         @pytest.setup()
         def fix1():
             l.append(1)
-        @pytest.factory()
+        @pytest.fixture()
         def arg1():
             l.append(2)
         def test_hello(arg1):
@@ -2696,10 +2696,10 @@
 def test_request_funcargnames(testdir):
     testdir.makepyfile("""
         import pytest
-        @pytest.factory()
+        @pytest.fixture()
         def arg1():
             pass
-        @pytest.factory()
+        @pytest.fixture()
         def farg(arg1):
             pass
         @pytest.setup()



https://bitbucket.org/hpk42/pytest/changeset/70b4758381a0/
changeset:   70b4758381a0
user:        hpk42
date:        2012-10-05 10:21:35
summary:     internally unify setup and fixture code, making setup a shortcut to fixture(autoactive=True)
affected #:  4 files

diff -r de544d09912bf791c6635f023ce153348e38e961 -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 _pytest/nose.py
--- a/_pytest/nose.py
+++ b/_pytest/nose.py
@@ -41,7 +41,7 @@
 
 def call_optional(obj, name):
     method = getattr(obj, name, None)
-    if method is not None and not hasattr(method, "_pytestsetup"):
+    if method is not None and not hasattr(method, "_pytestfixturefunction"):
         # If there's any problems allow the exception to raise rather than
         # silently ignoring them
         method()


diff -r de544d09912bf791c6635f023ce153348e38e961 -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 _pytest/python.py
--- a/_pytest/python.py
+++ b/_pytest/python.py
@@ -11,22 +11,18 @@
 cutdir = py.path.local(_pytest.__file__).dirpath()
 
 class FixtureFunctionMarker:
-    def __init__(self, scope, params):
+    def __init__(self, scope, params, autoactive=False):
         self.scope = scope
         self.params = params
+        self.autoactive = autoactive
+
     def __call__(self, function):
         function._pytestfixturefunction = self
         return function
 
-class SetupMarker:
-    def __init__(self, scope):
-        self.scope = scope
-    def __call__(self, function):
-        function._pytestsetup = self
-        return function
 
 # XXX a test fails when scope="function" how it should be, investigate
-def fixture(scope=None, params=None):
+def fixture(scope=None, params=None, autoactive=False):
     """ return a decorator to mark a fixture factory function.
 
     The name of the fixture function can be referenced in a test context
@@ -42,8 +38,11 @@
                 invocations of the fixture functions and their dependent
                 tests.
     """
-    return FixtureFunctionMarker(scope, params)
+    return FixtureFunctionMarker(scope, params, autoactive=autoactive)
 
+defaultfuncargprefixmarker = fixture()
+
+# XXX remove in favour of fixture(autoactive=True)
 def setup(scope="function"):
     """ return a decorator to mark a function as providing a fixture for
     a testcontext.  A fixture function is executed for each scope and may
@@ -57,7 +56,7 @@
                 of "function", "class", "module", "session".
                 Defaults to "function".
     """
-    return SetupMarker(scope)
+    return FixtureFunctionMarker(scope, params=None, autoactive=True)
 
 def cached_property(f):
     """returns a cached property that is calculated by function f.
@@ -163,7 +162,10 @@
             testfunction(*pyfuncitem._args)
         else:
             funcargs = pyfuncitem.funcargs
-            testfunction(**funcargs)
+            testargs = {}
+            for arg in getfuncargnames(testfunction):
+                testargs[arg] = funcargs[arg]
+            testfunction(**testargs)
 
 def pytest_collect_file(path, parent):
     ext = path.ext
@@ -666,7 +668,6 @@
             for i, valset in enumerate(argvalues):
                 assert len(valset) == len(argnames)
                 newcallspec = callspec.copy(self)
-                #print ("setmulti %r id %r" % (argnames, ids[i]))
                 newcallspec.setmulti(valtype, argnames, valset, ids[i],
                                      scopenum)
                 newcalls.append(newcallspec)
@@ -879,14 +880,19 @@
             #req._discoverfactories()
         if callobj is not _dummy:
             self.obj = callobj
-        startindex = int(self.cls is not None)
-        self.funcargnames = getfuncargnames(self.obj, startindex=startindex)
+        self.funcargnames = self._getfixturenames()
+
         for name, val in (py.builtin._getfuncdict(self.obj) or {}).items():
             setattr(self.markers, name, val)
         if keywords:
             for name, val in keywords.items():
                 setattr(self.markers, name, val)
 
+    def _getfixturenames(self):
+        startindex = int(self.cls is not None)
+        return (self.session.funcargmanager._autofixtures +
+                getfuncargnames(self.obj, startindex=startindex))
+
     @property
     def function(self):
         "underlying python 'function' object"
@@ -913,8 +919,8 @@
 
     def setup(self):
         super(Function, self).setup()
-        if hasattr(self, "_request"):
-            self._request._callsetup()
+        #if hasattr(self, "_request"):
+        #    self._request._callsetup()
         fillfuncargs(self)
 
     def __eq__(self, other):
@@ -1054,6 +1060,7 @@
         """add finalizer/teardown function to be called after the
         last test within the requesting test context finished
         execution. """
+        # XXX usually this method is shadowed by factorydef specific ones
         self._addfinalizer(finalizer, scope=self.scope)
 
     def _addfinalizer(self, finalizer, scope):
@@ -1084,13 +1091,11 @@
     def _fillfuncargs(self):
         item = self._pyfuncitem
         funcargnames = getattr(item, "funcargnames", self.funcargnames)
+
         for argname in funcargnames:
             if argname not in item.funcargs:
                 item.funcargs[argname] = self.getfuncargvalue(argname)
 
-    def _callsetup(self):
-        self.funcargmanager.ensure_setupcalls(self)
-
     def cached_setup(self, setup, teardown=None, scope="module", extrakey=None):
         """ (deprecated) Return a testing resource managed by ``setup`` &
         ``teardown`` calls.  ``scope`` and ``extrakey`` determine when the
@@ -1154,20 +1159,19 @@
         factorydef = factorydeflist.pop()
         self._factorystack.append(factorydef)
         try:
-            return self._getfuncargvalue(factorydef)
+            result = self._getfuncargvalue(factorydef)
+            self._funcargs[argname] = result
+            return result
         finally:
             self._factorystack.pop()
 
     def _getfuncargvalue(self, factorydef):
-        # collect funcargs from the factory
-        newnames = factorydef.funcargnames
+        if factorydef.active:
+            return factorydef.cached_result
+
+        # prepare request scope and param attributes before
+        # calling into factory
         argname = factorydef.argname
-        factory_kwargs = {}
-        def fillfactoryargs():
-            for newname in newnames:
-                val = self.getfuncargvalue(newname)
-                factory_kwargs[newname] = val
-
         node = self._pyfuncitem
         mp = monkeypatch()
         mp.setattr(self, '_currentarg', argname)
@@ -1177,9 +1181,7 @@
             pass
         else:
             mp.setattr(self, 'param', param, raising=False)
-
         scope = factorydef.scope
-        funcargfactory = factorydef.func
         if scope is not None:
             __tracebackhide__ = True
             if scopemismatch(self.scope, scope):
@@ -1191,17 +1193,16 @@
                     (scope, argname, self.scope, "\n".join(lines))))
             __tracebackhide__ = False
             mp.setattr(self, "scope", scope)
-            kwargs = {}
-            if hasattr(self, "param"):
-                kwargs["extrakey"] = param
-            fillfactoryargs()
-            val = self.cached_setup(lambda: funcargfactory(**factory_kwargs),
-                                    scope=scope, **kwargs)
-        else:
-            fillfactoryargs()
-            val = funcargfactory(**factory_kwargs)
+
+        # prepare finalization according to scope
+        self.session._setupstate.addfinalizer(factorydef.finish, self.node)
+        self.funcargmanager.addargfinalizer(factorydef.finish, argname)
+        for subargname in factorydef.funcargnames: # XXX all deps?
+            self.funcargmanager.addargfinalizer(factorydef.finish, subargname)
+        mp.setattr(self, "addfinalizer", factorydef.addfinalizer)
+        # finally perform the factory call
+        val = factorydef.execute(request=self)
         mp.undo()
-        self._funcargs[argname] = val
         return val
 
     def _factorytraceback(self):
@@ -1291,8 +1292,8 @@
         self.arg2facspec = {}
         self._seenplugins = set()
         self._holderobjseen = set()
-        self.setuplist = []
         self._arg2finish = {}
+        self._autofixtures = []
         session.config.pluginmanager.register(self, "funcmanage")
 
     ### XXX this hook should be called for historic events like pytest_configure
@@ -1325,13 +1326,11 @@
         # so that the caller can reuse it and does not have to re-discover
         # factories again for each funcargname
         parentid = parentnode.nodeid
-        funcargnames = list(funcargnames)
-        _, setupargs = self.getsetuplist(parentnode)
+        funcargnames = self._autofixtures + list(funcargnames)
         def merge(otherlist):
             for arg in otherlist:
                 if arg not in funcargnames:
                     funcargnames.append(arg)
-        merge(setupargs)
         arg2facdeflist = {}
         lastlen = -1
         while lastlen != len(funcargnames):
@@ -1365,6 +1364,9 @@
             cs1 = item.callspec
         except AttributeError:
             return
+
+        # determine which fixtures are not needed anymore for the next test
+        keylist = []
         for name in cs1.params:
             try:
                 if name in nextitem.callspec.params and \
@@ -1372,8 +1374,13 @@
                     continue
             except AttributeError:
                 pass
-            key = (name, cs1.params[name])
-            item.session._setupstate._callfinalizers(key)
+            key = (-cs1._arg2scopenum[name], name, cs1.params[name])
+            keylist.append(key)
+
+        # sort by scope (function scope first, then higher ones)
+        keylist.sort()
+        for (scopenum, name, param) in keylist:
+            item.session._setupstate._callfinalizers((name, param))
             l = self._arg2finish.get(name)
             if l is not None:
                 for fin in l:
@@ -1382,55 +1389,36 @@
     def _parsefactories(self, holderobj, nodeid, unittest=False):
         if holderobj in self._holderobjseen:
             return
-        #print "parsefactories", holderobj
         self._holderobjseen.add(holderobj)
         for name in dir(holderobj):
-            #print "check", holderobj, name
             obj = getattr(holderobj, name)
             if not callable(obj):
                 continue
-            # resource factories either have a pytest_funcarg__ prefix
-            # or are "funcarg" marked
+            # fixture functions have a pytest_funcarg__ prefix
+            # or are "@pytest.fixture" marked
             marker = getattr(obj, "_pytestfixturefunction", None)
-            if marker is not None:
-                if not isinstance(marker, FixtureFunctionMarker):
-                    # magic globals  with __getattr__
-                    # give us something thats wrong for that case
+            if marker is None:
+                if not name.startswith(self._argprefix):
                     continue
+                marker = defaultfuncargprefixmarker
+                name = name[len(self._argprefix):]
+            elif not isinstance(marker, FixtureFunctionMarker):
+                # magic globals  with __getattr__ might have got us a wrong
+                # fixture attribute
+                continue
+            else:
                 assert not name.startswith(self._argprefix)
-                argname = name
-                scope = marker.scope
-                params = marker.params
-            elif name.startswith(self._argprefix):
-                argname = name[len(self._argprefix):]
-                scope = None
-                params = None
-            else:
-                # no funcargs. check if we have a setup function.
-                setup = getattr(obj, "_pytestsetup", None)
-                if setup is not None:
-                    scope = setup.scope
-                    sf = SetupCall(self, nodeid, obj, scope, unittest)
-                    self.setuplist.append(sf)
-                continue
-            faclist = self.arg2facspec.setdefault(argname, [])
-            factorydef = FactoryDef(self, nodeid, argname, obj, scope, params)
+            factorydef = FactoryDef(self, nodeid, name, obj,
+                                    marker.scope, marker.params,
+                                    unittest=unittest)
+            faclist = self.arg2facspec.setdefault(name, [])
             faclist.append(factorydef)
-            ### check scope/params mismatch?
-
-    def getsetuplist(self, node):
-        nodeid = node.nodeid
-        l = []
-        allargnames = []
-        for setupcall in self.setuplist:
-            if nodeid.startswith(setupcall.baseid):
-                l.append(setupcall)
-                for arg in setupcall.funcargnames:
-                    if arg not in allargnames:
-                        allargnames.append(arg)
-        l.sort(key=lambda x: x.scopenum)
-        return l, allargnames
-
+            if marker.autoactive:
+                # make sure the self._autofixtures list is always sorted
+                # by scope, scopenum 0 is session
+                self._autofixtures.append(name)
+                self._autofixtures.sort(
+                    key=lambda x: self.arg2facspec[x][-1].scopenum)
 
     def getfactorylist(self, argname, nodeid):
         try:
@@ -1438,20 +1426,17 @@
         except KeyError:
             return None
         else:
-            return self._matchfactories(factorydeflist, nodeid)
+            return list(self._matchfactories(factorydeflist, nodeid))
 
     def _matchfactories(self, factorydeflist, nodeid):
-        l = []
         for factorydef in factorydeflist:
-            #print "check", basepath, nodeid
             if nodeid.startswith(factorydef.baseid):
-                l.append(factorydef)
-        return l
+                yield factorydef
 
     def _raiselookupfailed(self, argname, function, nodeid, getfactb=None):
         available = []
         for name, facdef in self.arg2facspec.items():
-            faclist = self._matchfactories(facdef, nodeid)
+            faclist = list(self._matchfactories(facdef, nodeid))
             if faclist:
                 available.append(name)
         msg = "LookupError: no factory found for argument %r" % (argname,)
@@ -1460,36 +1445,6 @@
         lines = getfactb and getfactb() or []
         raise FuncargLookupError(function, msg, lines)
 
-    def ensure_setupcalls(self, request):
-        setuplist, allnames = self.getsetuplist(request._pyfuncitem)
-        for setupcall in setuplist:
-            if setupcall.active:
-                continue
-            request._factorystack.append(setupcall)
-            mp = monkeypatch()
-            try:
-                mp.setattr(request, "scope", setupcall.scope)
-                kwargs = {}
-                for name in setupcall.funcargnames:
-                    kwargs[name] = request.getfuncargvalue(name)
-                scope = setupcall.scope or "function"
-                scol = setupcall.scopeitem = request._getscopeitem(scope)
-                self.session._setupstate.addfinalizer(setupcall.finish, scol)
-                for argname in setupcall.funcargnames: # XXX all deps?
-                    self.addargfinalizer(setupcall.finish, argname)
-                req = kwargs.get("request", None)
-                if req is not None:
-                    mp.setattr(req, "addfinalizer", setupcall.addfinalizer)
-                # for unittest-setup methods we need to provide
-                # the correct instance
-                posargs = ()
-                if setupcall.unittest:
-                    posargs = (request.instance,)
-                setupcall.execute(posargs, kwargs)
-            finally:
-                mp.undo()
-                request._factorystack.remove(setupcall)
-
     def addargfinalizer(self, finalizer, argname):
         l = self._arg2finish.setdefault(argname, [])
         l.append(finalizer)
@@ -1501,28 +1456,24 @@
             except ValueError:
                 pass
 
-
-class SetupCall:
-    """ a container/helper for managing calls to setup functions. """
-    def __init__(self, funcargmanager, baseid, func, scope, unittest):
+class FactoryDef:
+    """ A container for a factory definition. """
+    def __init__(self, funcargmanager, baseid, argname, func, scope, params,
+        unittest=False):
         self.funcargmanager = funcargmanager
         self.baseid = baseid
         self.func = func
+        self.argname = argname
+        self.scope = scope
+        self.scopenum = scopes.index(scope or "function")
+        self.params = params
         startindex = unittest and 1 or None
         self.funcargnames = getfuncargnames(func, startindex=startindex)
-        self.scope = scope
-        self.scopenum = scopes.index(scope)
+        self.unittest = unittest
         self.active = False
-        self.unittest= unittest
         self._finalizer = []
 
-    def execute(self, posargs, kwargs):
-        assert not self.active
-        self.active = True
-        self.func(*posargs, **kwargs)
-
     def addfinalizer(self, finalizer):
-        assert self.active
         self._finalizer.append(finalizer)
 
     def finish(self):
@@ -1532,17 +1483,23 @@
         # check neccesity of next commented call
         self.funcargmanager.removefinalizer(self.finish)
         self.active = False
+        #print "finished", self
+        #del self.cached_result
 
-class FactoryDef:
-    """ A container for a factory definition. """
-    def __init__(self, funcargmanager, baseid, argname, func, scope, params):
-        self.funcargmanager = funcargmanager
-        self.baseid = baseid
-        self.func = func
-        self.argname = argname
-        self.scope = scope
-        self.params = params
-        self.funcargnames = getfuncargnames(func)
+    def execute(self, request):
+        kwargs = {}
+        for newname in self.funcargnames:
+            kwargs[newname] = request.getfuncargvalue(newname)
+        if self.unittest:
+            result = self.func(request.instance, **kwargs)
+        else:
+            result = self.func(**kwargs)
+        self.active = True
+        self.cached_result = result
+        return result
+
+    def __repr__(self):
+        return "<FactoryDef name=%r scope=%r>" % (self.argname, self.scope)
 
 def getfuncargnames(function, startindex=None):
     # XXX merge with main.py's varnames
@@ -1634,5 +1591,5 @@
 def xunitsetup(obj, name):
     meth = getattr(obj, name, None)
     if meth is not None:
-        if not hasattr(meth, "_pytestsetup"):
+        if not hasattr(meth, "_pytestfixturefunction"):
             return meth


diff -r de544d09912bf791c6635f023ce153348e38e961 -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 _pytest/unittest.py
--- a/_pytest/unittest.py
+++ b/_pytest/unittest.py
@@ -52,6 +52,9 @@
 class TestCaseFunction(pytest.Function):
     _excinfo = None
 
+    def _getfixturenames(self):
+        return list(self.session.funcargmanager._autofixtures)
+
     def setup(self):
         self._testcase = self.parent.obj(self.name)
         self._obj = getattr(self._testcase, self.name)
@@ -62,7 +65,7 @@
         if hasattr(self._testcase, 'setup_method'):
             self._testcase.setup_method(self._obj)
         if hasattr(self, "_request"):
-            self._request._callsetup()
+            self._request._fillfuncargs()
 
     def teardown(self):
         if hasattr(self._testcase, 'teardown_method'):


diff -r de544d09912bf791c6635f023ce153348e38e961 -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 testing/test_python.py
--- a/testing/test_python.py
+++ b/testing/test_python.py
@@ -276,8 +276,10 @@
         assert hasattr(modcol.obj, 'test_func')
 
     def test_function_equality(self, testdir, tmpdir):
+        from _pytest.python import FuncargManager
         config = testdir.parseconfigure()
         session = testdir.Session(config)
+        session.funcargmanager = FuncargManager(session)
         def func1():
             pass
         def func2():
@@ -576,21 +578,18 @@
         assert item.funcargs['other'] == 42
 
     def test_funcarg_lookup_modulelevel(self, testdir):
-        modcol = testdir.getmodulecol("""
+        testdir.makepyfile("""
             def pytest_funcarg__something(request):
                 return request.function.__name__
 
             class TestClass:
                 def test_method(self, something):
-                    pass
+                    assert something == "test_method"
             def test_func(something):
-                pass
+                assert something == "test_func"
         """)
-        item1, item2 = testdir.genitems([modcol])
-        funcargs.fillfuncargs(item1)
-        assert item1.funcargs['something'] ==  "test_method"
-        funcargs.fillfuncargs(item2)
-        assert item2.funcargs['something'] ==  "test_func"
+        reprec = testdir.inline_run()
+        reprec.assertoutcome(passed=2)
 
     def test_funcarg_lookup_classlevel(self, testdir):
         p = testdir.makepyfile("""
@@ -1881,16 +1880,9 @@
     def test_parsefactories_conftest(self, testdir):
         testdir.makepyfile("""
             def test_check_setup(item, fm):
-                setupcalls, allnames = fm.getsetuplist(item)
-                assert len(setupcalls) == 2
-                assert setupcalls[0].func.__name__ == "perfunction"
-                assert "request" in setupcalls[0].funcargnames
-                assert "tmpdir" in setupcalls[0].funcargnames
-                assert setupcalls[1].func.__name__ == "perfunction2"
-                assert "request" not in setupcalls[1].funcargnames
-                assert "arg1" in setupcalls[1].funcargnames
-                assert "tmpdir" not in setupcalls[1].funcargnames
-                #assert "tmpdir" in setupcalls[1].depfuncargs
+                assert len(fm._autofixtures) == 2
+                assert "perfunction2" in fm._autofixtures
+                assert "perfunction" in fm._autofixtures
         """)
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=1)
@@ -2098,8 +2090,8 @@
             class TestClass:
                 @pytest.setup(scope="class")
                 def addteardown(self, item, request):
+                    l.append("setup-%d" % item)
                     request.addfinalizer(lambda: l.append("teardown-%d" % item))
-                    l.append("setup-%d" % item)
                 def test_step1(self, item):
                     l.append("step1-%d" % item)
                 def test_step2(self, item):
@@ -2436,17 +2428,18 @@
                 l.append("test4")
             def test_5():
                 assert len(l) == 12 * 3
-                import pprint
-                pprint.pprint(l)
-                assert l == [
+                expected = [
                     'create:1', 'test1', 'fin:1', 'create:2', 'test1',
                     'fin:2', 'create:mod1', 'test2', 'create:1', 'test3',
                     'fin:1', 'create:2', 'test3', 'fin:2', 'create:1',
-                    'test4', 'fin:1', 'create:2', 'test4', 'fin:mod1',
-                    'fin:2', 'create:mod2', 'test2', 'create:1', 'test3',
+                    'test4', 'fin:1', 'create:2', 'test4', 'fin:2',
+                    'fin:mod1', 'create:mod2', 'test2', 'create:1', 'test3',
                     'fin:1', 'create:2', 'test3', 'fin:2', 'create:1',
-                    'test4', 'fin:1', 'create:2', 'test4', 'fin:mod2',
-                'fin:2']
+                    'test4', 'fin:1', 'create:2', 'test4', 'fin:2',
+                'fin:mod2']
+                import pprint
+                pprint.pprint(list(zip(l, expected)))
+                assert l == expected
         """)
         reprec = testdir.inline_run("-v")
         reprec.assertoutcome(passed=12+1)
@@ -2707,7 +2700,7 @@
             pass
         def test_function(request, farg):
             assert set(request.funcargnames) == \
-                   set(["tmpdir", "arg1", "request", "farg"])
+                   set(["tmpdir", "sarg", "arg1", "request", "farg"])
     """)
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)



https://bitbucket.org/hpk42/pytest/changeset/8d87ff808393/
changeset:   8d87ff808393
user:        hpk42
date:        2012-10-05 14:24:44
summary:     rename a number of internal and externally visible variables to use the fixture name
rather than funcargs.  Introduce .funcargnames compatibility attribute for backward compat.
affected #:  33 files

diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e ISSUES.txt
--- a/ISSUES.txt
+++ b/ISSUES.txt
@@ -71,7 +71,7 @@
 and the documentation needs to change along to mention this new way of
 doing things. 
 
-impl note: probably Request._fillfuncargs would be called from the
+impl note: probably Request._fillfixtures would be called from the
 python plugins own pytest_runtest_setup(item) and would call
 item.getresource(X) for all X in the funcargs of a function.
 


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e _pytest/capture.py
--- a/_pytest/capture.py
+++ b/_pytest/capture.py
@@ -189,7 +189,7 @@
     """
     if "capfd" in request._funcargs:
         raise request.raiseerror(error_capsysfderror)
-    return CaptureFuncarg(py.io.StdCapture)
+    return CaptureFixture(py.io.StdCapture)
 
 def pytest_funcarg__capfd(request):
     """enables capturing of writes to file descriptors 1 and 2 and makes
@@ -200,9 +200,9 @@
         request.raiseerror(error_capsysfderror)
     if not hasattr(os, 'dup'):
         pytest.skip("capfd funcarg needs os.dup")
-    return CaptureFuncarg(py.io.StdCaptureFD)
+    return CaptureFixture(py.io.StdCaptureFD)
 
-class CaptureFuncarg:
+class CaptureFixture:
     def __init__(self, captureclass):
         self.capture = captureclass(now=False)
 


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e _pytest/helpconfig.py
--- a/_pytest/helpconfig.py
+++ b/_pytest/helpconfig.py
@@ -80,7 +80,7 @@
     tw.line() ; tw.line()
     #tw.sep("=")
     tw.line("to see available markers type: py.test --markers")
-    tw.line("to see available funcargs type: py.test --funcargs")
+    tw.line("to see available fixtures type: py.test --fixtures")
     return
 
     tw.line("conftest.py options:")


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e _pytest/main.py
--- a/_pytest/main.py
+++ b/_pytest/main.py
@@ -308,8 +308,8 @@
         pass
 
     def _repr_failure_py(self, excinfo, style=None):
-        fm = self.session.funcargmanager
-        if excinfo.errisinstance(fm.FuncargLookupError):
+        fm = self.session._fixturemanager
+        if excinfo.errisinstance(fm.FixtureLookupError):
             function = excinfo.value.function
             factblines = excinfo.value.factblines
             if function is not None:
@@ -317,7 +317,7 @@
                 lines, _ = inspect.getsourcelines(function)
                 for i, line in enumerate(lines):
                     if line.strip().startswith('def'):
-                        return fm.FuncargLookupErrorRepr(fspath,
+                        return fm.FixtureLookupErrorRepr(fspath,
                                     lineno, lines[:i+1],
                                     str(excinfo.value.msg), factblines)
         if self.config.option.fulltrace:


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e _pytest/python.py
--- a/_pytest/python.py
+++ b/_pytest/python.py
@@ -44,18 +44,7 @@
 
 # XXX remove in favour of fixture(autoactive=True)
 def setup(scope="function"):
-    """ return a decorator to mark a function as providing a fixture for
-    a testcontext.  A fixture function is executed for each scope and may
-    receive funcargs which allows it to initialise and provide implicit
-    test state.  A fixture function may receive the "testcontext" object
-    and register a finalizer via "testcontext.addfinalizer(finalizer)"
-    which will be called when the last test in the testcontext has
-    executed.
-
-    :arg scope: the scope for which the setup function will be active, one
-                of "function", "class", "module", "session".
-                Defaults to "function".
-    """
+    """ alias for fixture(scope, autoactive=True) """
     return FixtureFunctionMarker(scope, params=None, autoactive=True)
 
 def cached_property(f):
@@ -85,9 +74,9 @@
 
 def pytest_addoption(parser):
     group = parser.getgroup("general")
-    group.addoption('--funcargs',
-               action="store_true", dest="showfuncargs", default=False,
-               help="show available function arguments, sorted by plugin")
+    group.addoption('--fixtures', '--fixtures',
+               action="store_true", dest="showfixtures", default=False,
+               help="show available fixtures, sorted by plugin appearance")
     parser.addini("python_files", type="args",
         default=('test_*.py', '*_test.py'),
         help="glob-style file patterns for Python test module discovery")
@@ -97,8 +86,8 @@
         help="prefixes for Python test function and method discovery")
 
 def pytest_cmdline_main(config):
-    if config.option.showfuncargs:
-        showfuncargs(config)
+    if config.option.showfixtures:
+        showfixtures(config)
         return 0
 
 
@@ -119,7 +108,7 @@
     )
 
 def pytest_sessionstart(session):
-    session.funcargmanager = FuncargManager(session)
+    session._fixturemanager = FixtureManager(session)
 
 @pytest.mark.trylast
 def pytest_namespace():
@@ -131,10 +120,11 @@
         'collect': {
         'Module': Module, 'Class': Class, 'Instance': Instance,
         'Function': Function, 'Generator': Generator,
-        '_fillfuncargs': fillfuncargs}
+        '_fillfuncargs': fillfixtures}
     }
 
-def pytest_funcarg__pytestconfig(request):
+ at fixture()
+def pytestconfig(request):
     """ the pytest config object with access to command line opts."""
     return request.config
 
@@ -146,12 +136,12 @@
             testfunction(*pyfuncitem._args)
         else:
             try:
-                funcargnames = pyfuncitem.funcargnames
+                fixturenames = pyfuncitem.fixturenames
             except AttributeError:
                 funcargs = pyfuncitem.funcargs
             else:
                 funcargs = {}
-                for name in funcargnames:
+                for name in fixturenames:
                     funcargs[name] = pyfuncitem.funcargs[name]
             testfunction(**funcargs)
 
@@ -352,7 +342,7 @@
         return self._memoizedcall('_obj', self._importtestmodule)
 
     def collect(self):
-        self.session.funcargmanager._parsefactories(self.obj, self.nodeid)
+        self.session._fixturemanager._parsefactories(self.obj, self.nodeid)
         return super(Module, self).collect()
 
     def _importtestmodule(self):
@@ -425,7 +415,7 @@
         return obj
 
     def collect(self):
-        self.session.funcargmanager._parsefactories(self.obj, self.nodeid)
+        self.session._fixturemanager._parsefactories(self.obj, self.nodeid)
         return super(Instance, self).collect()
 
     def newinstance(self):
@@ -534,14 +524,14 @@
 
 
 
-def fillfuncargs(function):
+def fillfixtures(function):
     """ fill missing funcargs for a test function. """
     if getattr(function, "_args", None) is None:  # not a yielded function
         try:
             request = function._request
         except AttributeError:
-            request = function._request = FuncargRequest(function)
-        request._fillfuncargs()
+            request = function._request = FixtureRequest(function)
+        request._fillfixtures()
 
 _notexists = object()
 
@@ -605,21 +595,30 @@
             self._globalparam = param
 
 
-class Metafunc:
+class FuncargnamesCompatAttr:
+    """ helper class so that Metafunc, Function and FixtureRequest
+    don't need to each define the "funcargnames" compatibility attribute.
+    """
+    @property
+    def funcargnames(self):
+        """ alias attribute for ``fixturenames`` for pre-2.3 compatibility"""
+        return self.fixturenames
+
+class Metafunc(FuncargnamesCompatAttr):
     def __init__(self, function, config=None, cls=None, module=None,
                  parentnode=None):
         self.config = config
         self.module = module
         self.function = function
         self.parentnode = parentnode
-        self.parentid = getattr(parentnode, "nodeid", "")
+        self._parentid = getattr(parentnode, "nodeid", "")
         argnames = getfuncargnames(function, startindex=int(cls is not None))
         if parentnode is not None:
-            fm = parentnode.session.funcargmanager
-            self.funcargnames, self._arg2facdeflist = fm.getallfuncargnames(
+            fm = parentnode.session._fixturemanager
+            self.fixturenames, self._arg2fixturedeflist = fm.getfixtureclosure(
                 argnames, parentnode)
         else:
-            self.funcargnames = argnames
+            self.fixturenames = argnames
         self.cls = cls
         self.module = module
         self._calls = []
@@ -631,7 +630,7 @@
         """ Add new invocations to the underlying test function using the list
         of argvalues for the given argnames.  Parametrization is performed
         during the collection phase.  If you need to setup expensive resources
-        you may pass indirect=True and implement a funcarg factory which can
+        you may pass indirect=True and implement a fixture function which can
         perform the expensive setup just before a test is actually run.
 
         :arg argnames: an argument name or a list of argument names
@@ -640,7 +639,7 @@
             values for the list of argument names.
 
         :arg indirect: if True each argvalue corresponding to an argument will
-            be passed as request.param to its respective funcarg factory so
+            be passed as request.param to its respective fixture function so
             that it can perform more expensive setups during the setup phase of
             a test rather than at collection time.
 
@@ -657,7 +656,7 @@
         if not indirect:
             #XXX should we also check for the opposite case?
             for arg in argnames:
-                if arg not in self.funcargnames:
+                if arg not in self.fixturenames:
                     raise ValueError("%r has no argument %r" %(self.function, arg))
         valtype = indirect and "params" or "funcargs"
         if not ids:
@@ -686,13 +685,13 @@
         :arg id: used for reporting and identification purposes.  If you
             don't supply an `id` an automatic unique id will be generated.
 
-        :arg param: a parameter which will be exposed to a later funcarg factory
+        :arg param: a parameter which will be exposed to a later fixture function
             invocation through the ``request.param`` attribute.
         """
         assert funcargs is None or isinstance(funcargs, dict)
         if funcargs is not None:
             for name in funcargs:
-                if name not in self.funcargnames:
+                if name not in self.fixturenames:
                     pytest.fail("funcarg %r not used in this function." % name)
         else:
             funcargs = {}
@@ -722,11 +721,11 @@
         return "-".join(l)
 
 
-def showfuncargs(config):
+def showfixtures(config):
     from _pytest.main import wrap_session
-    return wrap_session(config, _showfuncargs_main)
+    return wrap_session(config, _showfixtures_main)
 
-def _showfuncargs_main(config, session):
+def _showfixtures_main(config, session):
     session.perform_collect()
     if session.items:
         plugins = session.items[0].getplugins()
@@ -735,7 +734,7 @@
     curdir = py.path.local()
     tw = py.io.TerminalWriter()
     verbose = config.getvalue("verbose")
-    argprefix = session.funcargmanager._argprefix
+    argprefix = session._fixturemanager._argprefix
     for plugin in plugins:
         available = []
         for name, factory in vars(plugin).items():
@@ -854,7 +853,7 @@
 #  the basic py.test Function item
 #
 _dummy = object()
-class Function(FunctionMixin, pytest.Item):
+class Function(FunctionMixin, pytest.Item, FuncargnamesCompatAttr):
     """ a Function Item is responsible for setting up and executing a
     Python test function.
     """
@@ -876,11 +875,11 @@
                     self.param = callspec.param
             else:
                 self.funcargs = {}
-            self._request = req = FuncargRequest(self)
+            self._request = req = FixtureRequest(self)
             #req._discoverfactories()
         if callobj is not _dummy:
             self.obj = callobj
-        self.funcargnames = self._getfixturenames()
+        self.fixturenames = self._getfuncargnames()
 
         for name, val in (py.builtin._getfuncdict(self.obj) or {}).items():
             setattr(self.markers, name, val)
@@ -888,9 +887,10 @@
             for name, val in keywords.items():
                 setattr(self.markers, name, val)
 
-    def _getfixturenames(self):
+
+    def _getfuncargnames(self):
         startindex = int(self.cls is not None)
-        return (self.session.funcargmanager._autofixtures +
+        return (self.session._fixturemanager._autofixtures +
                 getfuncargnames(self.obj, startindex=startindex))
 
     @property
@@ -921,7 +921,7 @@
         super(Function, self).setup()
         #if hasattr(self, "_request"):
         #    self._request._callsetup()
-        fillfuncargs(self)
+        fillfixtures(self)
 
     def __eq__(self, other):
         try:
@@ -960,8 +960,8 @@
     return decoratescope
 
 
-class FuncargRequest:
-    """ A request for function arguments from a test or setup function.
+class FixtureRequest(FuncargnamesCompatAttr):
+    """ A request for fixtures from a test or setup function.
 
     A request object gives access to attributes of the requesting
     test context.  It has an optional ``param`` attribute in case
@@ -976,38 +976,38 @@
         self.scope = "function"
         self.getparent = pyfuncitem.getparent
         self._funcargs  = self._pyfuncitem.funcargs.copy()
-        self._name2factory = {}
-        self.funcargmanager = pyfuncitem.session.funcargmanager
+        self._arg2fixturedeflist = {}
+        self._fixturemanager = pyfuncitem.session._fixturemanager
         self._currentarg = None
-        self.parentid = pyfuncitem.parent.nodeid
-        self.funcargnames, self._arg2facdeflist_ = \
-            self.funcargmanager.getallfuncargnames(
+        self._parentid = pyfuncitem.parent.nodeid
+        self.fixturenames, self._arg2fixturedeflist_ = \
+            self._fixturemanager.getfixtureclosure(
                 getfuncargnames(self.function), # XXX _pyfuncitem...
                 pyfuncitem.parent)
-        self._factorystack = []
+        self._fixturestack = []
 
     @property
     def node(self):
         """ underlying collection node (depends on request scope)"""
         return self._getscopeitem(self.scope)
 
-    def _getfaclist(self, argname):
-        facdeflist = self._name2factory.get(argname, None)
-        getfactb = None
+    def _getfixturedeflist(self, argname):
+        fixturedeflist = self._arg2fixturedeflist.get(argname, None)
+        getfixturetb = None
         function = None
-        if facdeflist is None:
-            if self._factorystack:
-                function = self._factorystack[-1].func
-                getfactb = lambda: self._factorystack[:-1]
+        if fixturedeflist is None:
+            if self._fixturestack:
+                function = self._fixturestack[-1].func
+                getfixturetb = lambda: self._fixturestack[:-1]
             else:
                 function = self.function
-            facdeflist = self.funcargmanager.getfactorylist(
-                            argname, self.parentid)
-            self._name2factory[argname] = facdeflist
-        if not facdeflist:
-            self.funcargmanager._raiselookupfailed(argname, function,
-                                                   self.parentid, getfactb)
-        return facdeflist
+            fixturedeflist = self._fixturemanager.getfixturedeflist(
+                            argname, self._parentid)
+            self._arg2fixturedeflist[argname] = fixturedeflist
+        if not fixturedeflist:
+            self._fixturemanager._raiselookupfailed(argname, function,
+                                                   self._parentid, getfixturetb)
+        return fixturedeflist
 
     @property
     def config(self):
@@ -1060,7 +1060,7 @@
         """add finalizer/teardown function to be called after the
         last test within the requesting test context finished
         execution. """
-        # XXX usually this method is shadowed by factorydef specific ones
+        # XXX usually this method is shadowed by fixturedef specific ones
         self._addfinalizer(finalizer, scope=self.scope)
 
     def _addfinalizer(self, finalizer, scope):
@@ -1084,15 +1084,15 @@
         self.node.applymarker(marker)
 
     def raiseerror(self, msg):
-        """ raise a FuncargLookupError with the given message. """
-        raise self.funcargmanager.FuncargLookupError(self.function, msg)
+        """ raise a FixtureLookupError with the given message. """
+        raise self._fixturemanager.FixtureLookupError(self.function, msg)
 
 
-    def _fillfuncargs(self):
+    def _fillfixtures(self):
         item = self._pyfuncitem
-        funcargnames = getattr(item, "funcargnames", self.funcargnames)
+        fixturenames = getattr(item, "fixturenames", self.fixturenames)
 
-        for argname in funcargnames:
+        for argname in fixturenames:
             if argname not in item.funcargs:
                 item.funcargs[argname] = self.getfuncargvalue(argname)
 
@@ -1100,9 +1100,9 @@
         """ (deprecated) Return a testing resource managed by ``setup`` &
         ``teardown`` calls.  ``scope`` and ``extrakey`` determine when the
         ``teardown`` function will be called so that subsequent calls to
-        ``setup`` would recreate the resource.  With pytest-2.3 you
+        ``setup`` would recreate the resource.  With pytest-2.3 you often
         do not need ``cached_setup()`` as you can directly declare a scope
-        on a funcarg factory and register a finalizer through
+        on a fixture function and register a finalizer through
         ``request.addfinalizer()``.
 
         :arg teardown: function receiving a previously setup resource.
@@ -1151,27 +1151,27 @@
         except KeyError:
             pass
         try:
-            factorydeflist = self._getfaclist(argname)
-        except FuncargLookupError:
+            fixturedeflist = self._getfixturedeflist(argname)
+        except FixtureLookupError:
             if argname == "request":
                 return self
             raise
-        factorydef = factorydeflist.pop()
-        self._factorystack.append(factorydef)
+        fixturedef = fixturedeflist.pop()
+        self._fixturestack.append(fixturedef)
         try:
-            result = self._getfuncargvalue(factorydef)
+            result = self._getfuncargvalue(fixturedef)
             self._funcargs[argname] = result
             return result
         finally:
-            self._factorystack.pop()
+            self._fixturestack.pop()
 
-    def _getfuncargvalue(self, factorydef):
-        if factorydef.active:
-            return factorydef.cached_result
+    def _getfuncargvalue(self, fixturedef):
+        if fixturedef.active:
+            return fixturedef.cached_result
 
         # prepare request scope and param attributes before
         # calling into factory
-        argname = factorydef.argname
+        argname = fixturedef.argname
         node = self._pyfuncitem
         mp = monkeypatch()
         mp.setattr(self, '_currentarg', argname)
@@ -1181,7 +1181,7 @@
             pass
         else:
             mp.setattr(self, 'param', param, raising=False)
-        scope = factorydef.scope
+        scope = fixturedef.scope
         if scope is not None:
             __tracebackhide__ = True
             if scopemismatch(self.scope, scope):
@@ -1195,20 +1195,20 @@
             mp.setattr(self, "scope", scope)
 
         # prepare finalization according to scope
-        self.session._setupstate.addfinalizer(factorydef.finish, self.node)
-        self.funcargmanager.addargfinalizer(factorydef.finish, argname)
-        for subargname in factorydef.funcargnames: # XXX all deps?
-            self.funcargmanager.addargfinalizer(factorydef.finish, subargname)
-        mp.setattr(self, "addfinalizer", factorydef.addfinalizer)
+        self.session._setupstate.addfinalizer(fixturedef.finish, self.node)
+        self._fixturemanager.addargfinalizer(fixturedef.finish, argname)
+        for subargname in fixturedef.fixturenames: # XXX all deps?
+            self._fixturemanager.addargfinalizer(fixturedef.finish, subargname)
+        mp.setattr(self, "addfinalizer", fixturedef.addfinalizer)
         # finally perform the factory call
-        val = factorydef.execute(request=self)
+        val = fixturedef.execute(request=self)
         mp.undo()
         return val
 
     def _factorytraceback(self):
         lines = []
-        for factorydef in self._factorystack:
-            factory = factorydef.func
+        for fixturedef in self._fixturestack:
+            factory = fixturedef.func
             fs, lineno = getfslineno(factory)
             p = self._pyfuncitem.session.fspath.bestrelpath(fs)
             args = inspect.formatargspec(*inspect.getargspec(factory))
@@ -1232,10 +1232,10 @@
         raise ValueError("unknown finalization scope %r" %(scope,))
 
     def __repr__(self):
-        return "<FuncargRequest for %r>" %(self._pyfuncitem)
+        return "<FixtureRequest for %r>" %(self._pyfuncitem)
 
 class ScopeMismatchError(Exception):
-    """ A funcarg factory tries to access a funcargvalue/factory
+    """ A fixture function tries to use a different fixture function which
     which has a lower scope (e.g. a Session one calls a function one)
     """
 
@@ -1249,14 +1249,14 @@
         new_kwargs[name] = kwargs[name]
     return new_kwargs
 
-class FuncargLookupError(LookupError):
+class FixtureLookupError(LookupError):
     """ could not find a factory. """
     def __init__(self, function, msg, factblines=None):
         self.function = function
         self.msg = msg
         self.factblines = factblines
 
-class FuncargLookupErrorRepr(TerminalRepr):
+class FixtureLookupErrorRepr(TerminalRepr):
     def __init__(self, filename, firstlineno, deflines, errorstring, factblines):
         self.deflines = deflines
         self.errorstring = errorstring
@@ -1268,10 +1268,10 @@
         tw.line()
         if self.factblines:
             tw.line('    dependency of:')
-            for factorydef in self.factblines:
+            for fixturedef in self.factblines:
                 tw.line('        %s in %s' % (
-                    factorydef.argname,
-                    factorydef.baseid,
+                    fixturedef.argname,
+                    fixturedef.baseid,
                 ))
             tw.line()
         for line in self.deflines:
@@ -1281,15 +1281,15 @@
         tw.line()
         tw.line("%s:%d" % (self.filename, self.firstlineno+1))
 
-class FuncargManager:
+class FixtureManager:
     _argprefix = "pytest_funcarg__"
-    FuncargLookupError = FuncargLookupError
-    FuncargLookupErrorRepr = FuncargLookupErrorRepr
+    FixtureLookupError = FixtureLookupError
+    FixtureLookupErrorRepr = FixtureLookupErrorRepr
 
     def __init__(self, session):
         self.session = session
         self.config = session.config
-        self.arg2facspec = {}
+        self.arg2fixturedeflist = {}
         self._seenplugins = set()
         self._holderobjseen = set()
         self._arg2finish = {}
@@ -1319,41 +1319,44 @@
         for plugin in plugins:
             self.pytest_plugin_registered(plugin)
 
-    def getallfuncargnames(self, funcargnames, parentnode):
-        # collect the closure of all funcargs, starting with
-        # funcargnames as the initial set
-        # we populate and return a arg2facdeflist mapping
-        # so that the caller can reuse it and does not have to re-discover
-        # factories again for each funcargname
+    def getfixtureclosure(self, fixturenames, parentnode):
+        # collect the closure of all funcargs, starting with the given
+        # fixturenames as the initial set.  As we have to visit all
+        # factory definitions anyway, we also return a arg2fixturedeflist
+        # mapping so that the caller can reuse it and does not have
+        # to re-discover fixturedefs again for each fixturename
+        # (discovering matching fixtures for a given name/node is expensive)
+
         parentid = parentnode.nodeid
-        funcargnames = self._autofixtures + list(funcargnames)
+        fixturenames_closure = list(self._autofixtures)
         def merge(otherlist):
             for arg in otherlist:
-                if arg not in funcargnames:
-                    funcargnames.append(arg)
-        arg2facdeflist = {}
+                if arg not in fixturenames_closure:
+                    fixturenames_closure.append(arg)
+        merge(fixturenames)
+        arg2fixturedeflist = {}
         lastlen = -1
-        while lastlen != len(funcargnames):
-            lastlen = len(funcargnames)
-            for argname in list(funcargnames):
-                if argname in arg2facdeflist:
+        while lastlen != len(fixturenames_closure):
+            lastlen = len(fixturenames_closure)
+            for argname in fixturenames_closure:
+                if argname in arg2fixturedeflist:
                     continue
-                facdeflist = self.getfactorylist(argname, parentid)
-                arg2facdeflist[argname] = facdeflist
-                if facdeflist is not None:
-                    for facdef in facdeflist:
-                        merge(facdef.funcargnames)
-        return funcargnames, arg2facdeflist
+                fixturedeflist = self.getfixturedeflist(argname, parentid)
+                arg2fixturedeflist[argname] = fixturedeflist
+                if fixturedeflist is not None:
+                    for fixturedef in fixturedeflist:
+                        merge(fixturedef.fixturenames)
+        return fixturenames_closure, arg2fixturedeflist
 
     def pytest_generate_tests(self, metafunc):
-        for argname in metafunc.funcargnames:
-            faclist = metafunc._arg2facdeflist[argname]
+        for argname in metafunc.fixturenames:
+            faclist = metafunc._arg2fixturedeflist[argname]
             if faclist is None:
-                continue # will raise FuncargLookupError at setup time
-            for facdef in faclist:
-                if facdef.params is not None:
-                    metafunc.parametrize(argname, facdef.params, indirect=True,
-                                         scope=facdef.scope)
+                continue # will raise FixtureLookupError at setup time
+            for fixturedef in faclist:
+                if fixturedef.params is not None:
+                    metafunc.parametrize(argname, fixturedef.params, indirect=True,
+                                         scope=fixturedef.scope)
 
     def pytest_collection_modifyitems(self, items):
         # separate parametrized setups
@@ -1394,7 +1397,7 @@
             obj = getattr(holderobj, name)
             if not callable(obj):
                 continue
-            # fixture functions have a pytest_funcarg__ prefix
+            # fixture functions have a pytest_funcarg__ prefix (pre-2.3 style)
             # or are "@pytest.fixture" marked
             marker = getattr(obj, "_pytestfixturefunction", None)
             if marker is None:
@@ -1408,42 +1411,42 @@
                 continue
             else:
                 assert not name.startswith(self._argprefix)
-            factorydef = FactoryDef(self, nodeid, name, obj,
+            fixturedef = FixtureDef(self, nodeid, name, obj,
                                     marker.scope, marker.params,
                                     unittest=unittest)
-            faclist = self.arg2facspec.setdefault(name, [])
-            faclist.append(factorydef)
+            faclist = self.arg2fixturedeflist.setdefault(name, [])
+            faclist.append(fixturedef)
             if marker.autoactive:
                 # make sure the self._autofixtures list is always sorted
                 # by scope, scopenum 0 is session
                 self._autofixtures.append(name)
                 self._autofixtures.sort(
-                    key=lambda x: self.arg2facspec[x][-1].scopenum)
+                    key=lambda x: self.arg2fixturedeflist[x][-1].scopenum)
 
-    def getfactorylist(self, argname, nodeid):
+    def getfixturedeflist(self, argname, nodeid):
         try:
-            factorydeflist = self.arg2facspec[argname]
+            fixturedeflist = self.arg2fixturedeflist[argname]
         except KeyError:
             return None
         else:
-            return list(self._matchfactories(factorydeflist, nodeid))
+            return list(self._matchfactories(fixturedeflist, nodeid))
 
-    def _matchfactories(self, factorydeflist, nodeid):
-        for factorydef in factorydeflist:
-            if nodeid.startswith(factorydef.baseid):
-                yield factorydef
+    def _matchfactories(self, fixturedeflist, nodeid):
+        for fixturedef in fixturedeflist:
+            if nodeid.startswith(fixturedef.baseid):
+                yield fixturedef
 
-    def _raiselookupfailed(self, argname, function, nodeid, getfactb=None):
+    def _raiselookupfailed(self, argname, function, nodeid, getfixturetb=None):
         available = []
-        for name, facdef in self.arg2facspec.items():
-            faclist = list(self._matchfactories(facdef, nodeid))
+        for name, fixturedef in self.arg2fixturedeflist.items():
+            faclist = list(self._matchfactories(fixturedef, nodeid))
             if faclist:
                 available.append(name)
         msg = "LookupError: no factory found for argument %r" % (argname,)
         msg += "\n available funcargs: %s" %(", ".join(available),)
-        msg += "\n use 'py.test --funcargs [testpath]' for help on them."
-        lines = getfactb and getfactb() or []
-        raise FuncargLookupError(function, msg, lines)
+        msg += "\n use 'py.test --fixtures [testpath]' for help on them."
+        lines = getfixturetb and getfixturetb() or []
+        raise FixtureLookupError(function, msg, lines)
 
     def addargfinalizer(self, finalizer, argname):
         l = self._arg2finish.setdefault(argname, [])
@@ -1456,11 +1459,11 @@
             except ValueError:
                 pass
 
-class FactoryDef:
+class FixtureDef:
     """ A container for a factory definition. """
-    def __init__(self, funcargmanager, baseid, argname, func, scope, params,
+    def __init__(self, fixturenanager, baseid, argname, func, scope, params,
         unittest=False):
-        self.funcargmanager = funcargmanager
+        self._fixturemanager = fixturenanager
         self.baseid = baseid
         self.func = func
         self.argname = argname
@@ -1468,7 +1471,7 @@
         self.scopenum = scopes.index(scope or "function")
         self.params = params
         startindex = unittest and 1 or None
-        self.funcargnames = getfuncargnames(func, startindex=startindex)
+        self.fixturenames = getfuncargnames(func, startindex=startindex)
         self.unittest = unittest
         self.active = False
         self._finalizer = []
@@ -1481,14 +1484,14 @@
             func = self._finalizer.pop()
             func()
         # check neccesity of next commented call
-        self.funcargmanager.removefinalizer(self.finish)
+        self._fixturemanager.removefinalizer(self.finish)
         self.active = False
         #print "finished", self
         #del self.cached_result
 
     def execute(self, request):
         kwargs = {}
-        for newname in self.funcargnames:
+        for newname in self.fixturenames:
             kwargs[newname] = request.getfuncargvalue(newname)
         if self.unittest:
             result = self.func(request.instance, **kwargs)
@@ -1499,7 +1502,7 @@
         return result
 
     def __repr__(self):
-        return "<FactoryDef name=%r scope=%r>" % (self.argname, self.scope)
+        return "<FixtureDef name=%r scope=%r>" % (self.argname, self.scope)
 
 def getfuncargnames(function, startindex=None):
     # XXX merge with main.py's varnames


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e _pytest/unittest.py
--- a/_pytest/unittest.py
+++ b/_pytest/unittest.py
@@ -21,7 +21,7 @@
 
 class UnitTestCase(pytest.Class):
     def collect(self):
-        self.session.funcargmanager._parsefactories(self.obj, self.nodeid,
+        self.session._fixturemanager._parsefactories(self.obj, self.nodeid,
                 unittest=True)
         loader = py.std.unittest.TestLoader()
         module = self.getparent(pytest.Module).obj
@@ -52,8 +52,8 @@
 class TestCaseFunction(pytest.Function):
     _excinfo = None
 
-    def _getfixturenames(self):
-        return list(self.session.funcargmanager._autofixtures)
+    def _getfuncargnames(self):
+        return list(self.session._fixturemanager._autofixtures)
 
     def setup(self):
         self._testcase = self.parent.obj(self.name)
@@ -65,7 +65,7 @@
         if hasattr(self._testcase, 'setup_method'):
             self._testcase.setup_method(self._obj)
         if hasattr(self, "_request"):
-            self._request._fillfuncargs()
+            self._request._fillfixtures()
 
     def teardown(self):
         if hasattr(self._testcase, 'teardown_method'):


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/builtin.txt
--- a/doc/en/builtin.txt
+++ b/doc/en/builtin.txt
@@ -25,7 +25,7 @@
 You can ask for available builtin or project-custom
 :ref:`function arguments <funcargs>` by typing::
 
-    $ py.test --funcargs
+    $ py.test --fixtures
     =========================== test session starts ============================
     platform linux2 -- Python 2.7.3 -- pytest-2.3.0.dev2
     plugins: xdist, bugzilla, cache, oejskit, pep8, cov


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/example/assertion/failure_demo.py
--- a/doc/en/example/assertion/failure_demo.py
+++ b/doc/en/example/assertion/failure_demo.py
@@ -15,7 +15,7 @@
     assert param1 * 2 < param2
 
 def pytest_generate_tests(metafunc):
-    if 'param1' in metafunc.funcargnames:
+    if 'param1' in metafunc.fixturenames:
         metafunc.addcall(funcargs=dict(param1=3, param2=6))
 
 class TestFailing(object):


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/example/attic.txt
--- a/doc/en/example/attic.txt
+++ b/doc/en/example/attic.txt
@@ -13,9 +13,9 @@
             help="run (slow) acceptance tests")
 
     def pytest_funcarg__accept(request):
-        return AcceptFuncarg(request)
+        return AcceptFixture(request)
 
-    class AcceptFuncarg:
+    class AcceptFixture:
         def __init__(self, request):
             if not request.config.option.acceptance:
                 pytest.skip("specify -A to run acceptance tests")
@@ -39,7 +39,7 @@
 If you run this test without specifying a command line option
 the test will get skipped with an appropriate message. Otherwise
 you can start to add convenience and test support methods
-to your AcceptFuncarg and drive running of tools or
+to your AcceptFixture and drive running of tools or
 applications and provide ways to do assertions about
 the output.
 


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/example/parametrize.txt
--- a/doc/en/example/parametrize.txt
+++ b/doc/en/example/parametrize.txt
@@ -84,7 +84,7 @@
             help="run all combinations")
 
     def pytest_generate_tests(metafunc):
-        if 'param1' in metafunc.funcargnames:
+        if 'param1' in metafunc.fixturenames:
             if metafunc.config.option.all:
                 end = 5
             else:
@@ -213,7 +213,7 @@
     # content of conftest.py
 
     def pytest_generate_tests(metafunc):
-        if 'db' in metafunc.funcargnames:
+        if 'db' in metafunc.fixturenames:
             metafunc.parametrize("db", ['d1', 'd2'], indirect=True)
 
     class DB1:


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/faq.txt
--- a/doc/en/faq.txt
+++ b/doc/en/faq.txt
@@ -126,11 +126,11 @@
 .. note::
 
     With pytest-2.3 you can use the :ref:`@pytest.fixture` decorator
-    to mark a function as a funcarg factory.  
+    to mark a function as a fixture function.  
 
 .. _`Convention over Configuration`: http://en.wikipedia.org/wiki/Convention_over_Configuration
 
-Can I yield multiple values from a funcarg factory function?
+Can I yield multiple values from a fixture function function?
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 There are two conceptual reasons why yielding from a factory function


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/fixture.txt
--- a/doc/en/fixture.txt
+++ b/doc/en/fixture.txt
@@ -676,6 +676,6 @@
 * to add finalizers/teardowns to be invoked when the last
   test of the requesting test context executes
 
-.. autoclass:: _pytest.python.FuncargRequest()
+.. autoclass:: _pytest.python.FixtureRequest()
     :members:
 


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/funcarg_compare.txt
--- a/doc/en/funcarg_compare.txt
+++ b/doc/en/funcarg_compare.txt
@@ -54,7 +54,7 @@
 4. there is no way how you can make use of funcarg factories
    in xUnit setup methods.
 
-5. A non-parametrized funcarg factory cannot use a parametrized 
+5. A non-parametrized fixture function cannot use a parametrized 
    funcarg resource if it isn't stated in the test function signature.
 
 All of these limitations are addressed with pytest-2.3 and its


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/funcargs.txt
--- a/doc/en/funcargs.txt
+++ b/doc/en/funcargs.txt
@@ -29,7 +29,7 @@
 The basic mechanism for injecting objects is called the *funcarg
 mechanism* because objects are injected when a test or setup
 **function** states it as an **argument**. The injected argument 
-is created by a call to a registered **funcarg factory** for each argument
+is created by a call to a registered **fixture function** for each argument
 name.  This mechanism is an example of `Dependency Injection`_ 
 and helps to de-couple test code from the setup of required
 objects: at test writing time you do not need to care for the details of
@@ -38,7 +38,7 @@
 is invoked multiple times with differently configured resource
 instances.
 
-Funcarg dependency injection allows to organise test resources 
+Fixture dependency injection allows to organise test resources 
 in a modular explicit way so that test functions state their needs
 in their signature.  pytest additionally offers powerful xunit-style 
 :ref:`setup functions <setup functions>` for the cases where you need 
@@ -144,7 +144,7 @@
 
     You can always issue::
 
-        py.test --funcargs test_simplefactory.py
+        py.test --fixtures test_simplefactory.py
 
     to see available function arguments.
 
@@ -289,7 +289,7 @@
             help="run all combinations")
 
     def pytest_generate_tests(metafunc):
-        if 'param1' in metafunc.funcargnames:
+        if 'param1' in metafunc.fixturenames:
             if metafunc.config.option.all:
                 end = 5
             else:
@@ -336,7 +336,7 @@
 according to test configuration or values specified
 in the class or module where a test function is defined:
 
-``metafunc.funcargnames``: set of required function arguments for given function
+``metafunc.fixturenames``: set of required function arguments for given function
 
 ``metafunc.function``: underlying python test function
 
@@ -346,6 +346,8 @@
 
 ``metafunc.config``: access to command line opts and general config
 
+``metafunc.funcargnames``: alias for ``fixturenames``, for pre-2.3 compatibility
+
 .. automethod:: Metafunc.parametrize
 .. automethod:: Metafunc.addcall(funcargs=None,id=_notexists,param=_notexists)
 
@@ -360,7 +362,7 @@
 Compatibility notes
 ============================================================
 
-**Funcargs** were originally introduced to pytest-2.0.  In pytest-2.3 
+**Fixtures** were originally introduced to pytest-2.0.  In pytest-2.3 
 the mechanism was extended and refined:
 
 * previously funcarg factories were specified with a special 
@@ -376,14 +378,14 @@
 
 * if you used parametrization and funcarg factories which made use of
   ``request.cached_setup()`` it is recommeneded to invest a few minutes
-  and simplify your funcarg factory code to use the `@pytest.fixture`_ 
+  and simplify your fixture function code to use the `@pytest.fixture`_ 
   decorator instead.  This will also allow to take advantage of 
   the `automatic per-resource grouping`_ of tests.
 
 .. note::
 
     Throughout the pytest documents the ``pytest_funcarg__NAME`` way of
-    defining a funcarg factory is often termed "old-style".  Their
+    defining a fixture function is often termed "old-style".  Their
     use remains fully supported and existing code using it should run
     unmodified.
 


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/getting-started.txt
--- a/doc/en/getting-started.txt
+++ b/doc/en/getting-started.txt
@@ -186,7 +186,7 @@
 
 You can find out what kind of builtin :ref:`funcargs` exist by typing::
 
-    py.test --funcargs   # shows builtin and custom function arguments
+    py.test --fixtures   # shows builtin and custom function arguments
 
 Where to go next
 -------------------------------------


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/test/plugin/terminal.txt
--- a/doc/en/test/plugin/terminal.txt
+++ b/doc/en/test/plugin/terminal.txt
@@ -24,7 +24,7 @@
     traceback print mode (long/short/line/no).
 ``--fulltrace``
     don't cut any tracebacks (default is to cut).
-``--funcargs``
+``--fixtures``
     show available function arguments, sorted by plugin
 
 Start improving this plugin in 30 seconds


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/en/usage.txt
--- a/doc/en/usage.txt
+++ b/doc/en/usage.txt
@@ -26,7 +26,7 @@
 ::
 
     py.test --version   # shows where pytest was imported from
-    py.test --funcargs  # show available builtin function arguments
+    py.test --fixtures  # show available builtin function arguments
     py.test -h | --help # show help on command line and config file options
 
 


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/builtin.txt
--- a/doc/ja/builtin.txt
+++ b/doc/ja/builtin.txt
@@ -47,7 +47,7 @@
 
 次のように入力して、利用できる組み込みまたはプロジェクトカスタムの :ref:`関数の引数 <funcargs>` を確認できます。
 
-    | $ py.test --funcargs
+    | $ py.test --fixtures
     | ====================== test session starts =======================
     | platform linux2 -- Python 2.7.1 -- pytest-2.2.4
     | collected 0 items
@@ -98,7 +98,7 @@
     | ========================  in 0.00 seconds ========================
 
 ..
-        $ py.test --funcargs
+        $ py.test --fixtures
         =========================== test session starts ============================
         platform linux2 -- Python 2.7.1 -- pytest-2.2.4
         collected 0 items


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/example/assertion/failure_demo.py
--- a/doc/ja/example/assertion/failure_demo.py
+++ b/doc/ja/example/assertion/failure_demo.py
@@ -15,7 +15,7 @@
     assert param1 * 2 < param2
 
 def pytest_generate_tests(metafunc):
-    if 'param1' in metafunc.funcargnames:
+    if 'param1' in metafunc.fixturenames:
         metafunc.addcall(funcargs=dict(param1=3, param2=6))
 
 class TestFailing(object):


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/example/attic.txt
--- a/doc/ja/example/attic.txt
+++ b/doc/ja/example/attic.txt
@@ -13,9 +13,9 @@
             help="run (slow) acceptance tests")
 
     def pytest_funcarg__accept(request):
-        return AcceptFuncarg(request)
+        return AcceptFixture(request)
 
-    class AcceptFuncarg:
+    class AcceptFixture:
         def __init__(self, request):
             if not request.config.option.acceptance:
                 pytest.skip("specify -A to run acceptance tests")
@@ -39,7 +39,7 @@
 If you run this test without specifying a command line option
 the test will get skipped with an appropriate message. Otherwise
 you can start to add convenience and test support methods
-to your AcceptFuncarg and drive running of tools or
+to your AcceptFixture and drive running of tools or
 applications and provide ways to do assertions about
 the output.
 


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/example/multipython.py
--- a/doc/ja/example/multipython.py
+++ b/doc/ja/example/multipython.py
@@ -11,7 +11,7 @@
     # over the python interpreters of our list above - the actual
     # setup and lookup of interpreters in the python1/python2 factories
     # respectively.
-    for arg in metafunc.funcargnames:
+    for arg in metafunc.fixturenames:
         if arg in ("python1", "python2"):
             metafunc.parametrize(arg, pythonlist, indirect=True)
 


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/example/parametrize.txt
--- a/doc/ja/example/parametrize.txt
+++ b/doc/ja/example/parametrize.txt
@@ -117,7 +117,7 @@
             help="run all combinations")
 
     def pytest_generate_tests(metafunc):
-        if 'param1' in metafunc.funcargnames:
+        if 'param1' in metafunc.fixturenames:
             if metafunc.config.option.all:
                 end = 5
             else:
@@ -266,7 +266,7 @@
     # conftest.py の内容
 
     def pytest_generate_tests(metafunc):
-        if 'db' in metafunc.funcargnames:
+        if 'db' in metafunc.fixturenames:
             metafunc.parametrize("db", ['d1', 'd2'], indirect=True)
 
     class DB1:


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/faq.txt
--- a/doc/ja/faq.txt
+++ b/doc/ja/faq.txt
@@ -153,7 +153,7 @@
 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 ..
-    Can I yield multiple values from a funcarg factory function?
+    Can I yield multiple values from a fixture function function?
     ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
 ..


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/funcargs.txt
--- a/doc/ja/funcargs.txt
+++ b/doc/ja/funcargs.txt
@@ -157,7 +157,7 @@
 
 いつでも次のようにして::
 
-    py.test --funcargs test_simplefactory.py
+    py.test --fixtures test_simplefactory.py
 
 ..
     to see available function arguments (which you can also
@@ -171,7 +171,7 @@
 .. _`xUnit style`: xunit_setup.html
 
 
-.. _`funcarg factory`:
+.. _`fixture function`:
 .. _factory:
 
 funcarg **request** オブジェクト
@@ -182,24 +182,24 @@
     =============================================
 
 ..
-    Each funcarg factory receives a **request** object tied to a specific test
-    function call.  A request object is passed to a funcarg factory and provides
+    Each fixture function receives a **request** object tied to a specific test
+    function call.  A request object is passed to a fixture function and provides
     access to test configuration and context:
 
 funcarg ファクトリー関数は、特別なテスト関数呼び出しに関連付けられた **request** オブジェクトを受け取ります。request オブジェクトは funcarg ファクトリーへ渡されて、テスト設定とコンテキストへのアクセスを提供します:
 
-.. autoclass:: _pytest.python.FuncargRequest()
+.. autoclass:: _pytest.python.FixtureRequest()
     :members: function,cls,module,keywords,config
 
 .. _`useful caching and finalization helpers`:
 
-.. automethod:: FuncargRequest.addfinalizer
+.. automethod:: FixtureRequest.addfinalizer
 
-.. automethod:: FuncargRequest.cached_setup
+.. automethod:: FixtureRequest.cached_setup
 
-.. automethod:: FuncargRequest.applymarker
+.. automethod:: FixtureRequest.applymarker
 
-.. automethod:: FuncargRequest.getfuncargvalue
+.. automethod:: FixtureRequest.getfuncargvalue
 
 
 .. _`test generators`:
@@ -236,7 +236,7 @@
 
     # test_example.py の内容
     def pytest_generate_tests(metafunc):
-        if "numiter" in metafunc.funcargnames:
+        if "numiter" in metafunc.fixturenames:
             metafunc.parametrize("numiter", range(10))
 
     def test_func(numiter):
@@ -329,9 +329,9 @@
 metafunc オブジェクトは ``pytest_generate_tests`` フックへ渡されます。これはテスト関数を検査したり、テスト設定またはテスト関数が定義されているクラスやモジュールで指定された値を取るテストを生成するのに役立ちます:
 
 ..
-    ``metafunc.funcargnames``: set of required function arguments for given function
+    ``metafunc.fixturenames``: set of required function arguments for given function
 
-``metafunc.funcargnames``: テスト関数へ渡される引数セット
+``metafunc.fixturenames``: テスト関数へ渡される引数セット
 
 ..
     ``metafunc.function``: underlying python test function


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/getting-started.txt
--- a/doc/ja/getting-started.txt
+++ b/doc/ja/getting-started.txt
@@ -265,7 +265,7 @@
 
 組み込みの :ref:`funcargs` を把握するには、次のコマンドを実行します::
 
-    py.test --funcargs   # 組み込み/カスタムの関数の引数を表示する
+    py.test --fixtures   # 組み込み/カスタムの関数の引数を表示する
 
 ..
     Where to go next


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/test/plugin/terminal.txt
--- a/doc/ja/test/plugin/terminal.txt
+++ b/doc/ja/test/plugin/terminal.txt
@@ -24,7 +24,7 @@
     traceback print mode (long/short/line/no).
 ``--fulltrace``
     don't cut any tracebacks (default is to cut).
-``--funcargs``
+``--fixtures``
     show available function arguments, sorted by plugin
 
 Start improving this plugin in 30 seconds


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e doc/ja/usage.txt
--- a/doc/ja/usage.txt
+++ b/doc/ja/usage.txt
@@ -43,7 +43,7 @@
 ::
 
     py.test --version   # pytest がインポートされた場所を表示
-    py.test --funcargs  # 利用できる組み込みの関数引数を表示
+    py.test --fixtures  # 利用できる組み込みの関数引数を表示
     py.test -h | --help # コマンドラインと設定ファイルオプションのヘルプを表示
 
 ..


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e testing/conftest.py
--- a/testing/conftest.py
+++ b/testing/conftest.py
@@ -64,7 +64,7 @@
         for name, l in multi.kwargs.items():
             for val in l:
                 metafunc.addcall(funcargs={name: val})
-    elif 'anypython' in metafunc.funcargnames:
+    elif 'anypython' in metafunc.fixturenames:
         for name in ('python2.4', 'python2.5', 'python2.6',
                      'python2.7', 'python3.1', 'pypy', 'jython'):
             metafunc.addcall(id=name, param=name)


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e testing/test_capture.py
--- a/testing/test_capture.py
+++ b/testing/test_capture.py
@@ -363,7 +363,7 @@
         assert 'operation on closed file' not in result.stderr.str()
 
 
-class TestCaptureFuncarg:
+class TestCaptureFixture:
     def test_std_functional(self, testdir):
         reprec = testdir.inline_runsource("""
             def test_hello(capsys):


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e testing/test_conftest.py
--- a/testing/test_conftest.py
+++ b/testing/test_conftest.py
@@ -2,7 +2,7 @@
 from _pytest.config import Conftest
 
 def pytest_generate_tests(metafunc):
-    if "basedir" in metafunc.funcargnames:
+    if "basedir" in metafunc.fixturenames:
         metafunc.addcall(param="global")
         metafunc.addcall(param="inpackage")
 


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e testing/test_helpconfig.py
--- a/testing/test_helpconfig.py
+++ b/testing/test_helpconfig.py
@@ -22,7 +22,7 @@
         *setup.cfg*
         *minversion*
         *to see*markers*py.test --markers*
-        *to see*funcargs*py.test --funcargs*
+        *to see*fixtures*py.test --fixtures*
     """)
 
 def test_collectattr():


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e testing/test_python.py
--- a/testing/test_python.py
+++ b/testing/test_python.py
@@ -1,6 +1,6 @@
 import pytest, py, sys
 from _pytest import python as funcargs
-from _pytest.python import FuncargLookupError
+from _pytest.python import FixtureLookupError
 
 class TestModule:
     def test_failing_import(self, testdir):
@@ -276,10 +276,10 @@
         assert hasattr(modcol.obj, 'test_func')
 
     def test_function_equality(self, testdir, tmpdir):
-        from _pytest.python import FuncargManager
+        from _pytest.python import FixtureManager
         config = testdir.parseconfigure()
         session = testdir.Session(config)
-        session.funcargmanager = FuncargManager(session)
+        session._fixturemanager = FixtureManager(session)
         def func1():
             pass
         def func2():
@@ -542,10 +542,10 @@
             pass
     assert funcargs.getfuncargnames(A) == ["x"]
 
-class TestFillFuncArgs:
+class TestFillFixtures:
     def test_fillfuncargs_exposed(self):
-        # used by oejskit
-        assert pytest._fillfuncargs == funcargs.fillfuncargs
+        # used by oejskit, kept for compatibility
+        assert pytest._fillfuncargs == funcargs.fillfixtures
 
     def test_funcarg_lookupfails(self, testdir):
         testdir.makepyfile("""
@@ -572,7 +572,7 @@
             def test_func(some, other):
                 pass
         """)
-        funcargs.fillfuncargs(item)
+        funcargs.fillfixtures(item)
         assert len(item.funcargs) == 2
         assert item.funcargs['some'] == "test_func"
         assert item.funcargs['other'] == 42
@@ -611,7 +611,7 @@
             def pytest_funcarg__something(request): pass
             def test_func(something): pass
         """)
-        req = funcargs.FuncargRequest(item)
+        req = funcargs.FixtureRequest(item)
         assert req.function == item.obj
         assert req.keywords == item.keywords
         assert hasattr(req.module, 'test_func')
@@ -632,7 +632,7 @@
         assert req.cls.__name__ == "TestB"
         assert req.instance.__class__ == req.cls
 
-    def XXXtest_request_contains_funcarg_name2factory(self, testdir):
+    def XXXtest_request_contains_funcarg_arg2fixturedeflist(self, testdir):
         modcol = testdir.getmodulecol("""
             def pytest_funcarg__something(request):
                 pass
@@ -642,9 +642,9 @@
         """)
         item1, = testdir.genitems([modcol])
         assert item1.name == "test_method"
-        name2factory = funcargs.FuncargRequest(item1)._name2factory
-        assert len(name2factory) == 1
-        assert name2factory[0].__name__ == "pytest_funcarg__something"
+        arg2fixturedeflist = funcargs.FixtureRequest(item1)._arg2fixturedeflist
+        assert len(arg2fixturedeflist) == 1
+        assert arg2fixturedeflist[0].__name__ == "pytest_funcarg__something"
 
     def test_getfuncargvalue_recursive(self, testdir):
         testdir.makeconftest("""
@@ -669,7 +669,7 @@
             def test_func(something): pass
         """)
         req = item._request
-        pytest.raises(FuncargLookupError, req.getfuncargvalue, "notexists")
+        pytest.raises(FixtureLookupError, req.getfuncargvalue, "notexists")
         val = req.getfuncargvalue("something")
         assert val == 1
         val = req.getfuncargvalue("something")
@@ -717,7 +717,7 @@
     def test_request_getmodulepath(self, testdir):
         modcol = testdir.getmodulecol("def test_somefunc(): pass")
         item, = testdir.genitems([modcol])
-        req = funcargs.FuncargRequest(item)
+        req = funcargs.FixtureRequest(item)
         assert req.fspath == modcol.fspath
 
 class TestMarking:
@@ -731,7 +731,7 @@
                 def test_func2(self, something):
                     pass
         """)
-        req1 = funcargs.FuncargRequest(item1)
+        req1 = funcargs.FixtureRequest(item1)
         assert 'xfail' not in item1.keywords
         req1.applymarker(pytest.mark.xfail)
         assert 'xfail' in item1.keywords
@@ -814,7 +814,7 @@
 
     def test_request_cachedsetup_extrakey(self, testdir):
         item1 = testdir.getitem("def test_func(): pass")
-        req1 = funcargs.FuncargRequest(item1)
+        req1 = funcargs.FixtureRequest(item1)
         l = ["hello", "world"]
         def setup():
             return l.pop()
@@ -829,7 +829,7 @@
 
     def test_request_cachedsetup_cache_deletion(self, testdir):
         item1 = testdir.getitem("def test_func(): pass")
-        req1 = funcargs.FuncargRequest(item1)
+        req1 = funcargs.FixtureRequest(item1)
         l = []
         def setup():
             l.append("setup")
@@ -906,14 +906,14 @@
     def test_no_funcargs(self, testdir):
         def function(): pass
         metafunc = funcargs.Metafunc(function)
-        assert not metafunc.funcargnames
+        assert not metafunc.fixturenames
         repr(metafunc._calls)
 
     def test_function_basic(self):
         def func(arg1, arg2="qwe"): pass
         metafunc = funcargs.Metafunc(func)
-        assert len(metafunc.funcargnames) == 1
-        assert 'arg1' in metafunc.funcargnames
+        assert len(metafunc.fixturenames) == 1
+        assert 'arg1' in metafunc.fixturenames
         assert metafunc.function is func
         assert metafunc.cls is None
 
@@ -1032,7 +1032,7 @@
     def test_parametrize_functional(self, testdir):
         testdir.makepyfile("""
             def pytest_generate_tests(metafunc):
-                assert "test_parametrize_functional" in metafunc.parentid
+                assert "test_parametrize_functional" in metafunc._parentid
                 metafunc.parametrize('x', [1,2], indirect=True)
                 metafunc.parametrize('y', [2])
             def pytest_funcarg__x(request):
@@ -1170,7 +1170,7 @@
     def test_addcall_with_two_funcargs_generators(self, testdir):
         testdir.makeconftest("""
             def pytest_generate_tests(metafunc):
-                assert "arg1" in metafunc.funcargnames
+                assert "arg1" in metafunc.fixturenames
                 metafunc.addcall(funcargs=dict(arg1=1, arg2=2))
         """)
         p = testdir.makepyfile("""
@@ -1213,7 +1213,7 @@
     def test_noself_in_method(self, testdir):
         p = testdir.makepyfile("""
             def pytest_generate_tests(metafunc):
-                assert 'xyz' not in metafunc.funcargnames
+                assert 'xyz' not in metafunc.fixturenames
 
             class TestHello:
                 def test_hello(xyz):
@@ -1228,7 +1228,7 @@
     def test_generate_plugin_and_module(self, testdir):
         testdir.makeconftest("""
             def pytest_generate_tests(metafunc):
-                assert "arg1" in metafunc.funcargnames
+                assert "arg1" in metafunc.fixturenames
                 metafunc.addcall(id="world", param=(2,100))
         """)
         p = testdir.makepyfile("""
@@ -1342,7 +1342,7 @@
     def test_parametrize_on_setup_arg(self, testdir):
         p = testdir.makepyfile("""
             def pytest_generate_tests(metafunc):
-                assert "arg1" in metafunc.funcargnames
+                assert "arg1" in metafunc.fixturenames
                 metafunc.parametrize("arg1", [1], indirect=True)
 
             def pytest_funcarg__arg1(request):
@@ -1403,7 +1403,7 @@
     clscol = rep.result[0]
     clscol.obj = lambda arg1: None
     clscol.funcargs = {}
-    funcargs.fillfuncargs(clscol)
+    funcargs.fillfixtures(clscol)
     assert clscol.funcargs['arg1'] == 42
 
 
@@ -1488,7 +1488,7 @@
        """
 
 def test_show_funcarg(testdir):
-    result = testdir.runpytest("--funcargs")
+    result = testdir.runpytest("--fixtures")
     result.stdout.fnmatch_lines([
             "*tmpdir*",
             "*temporary directory*",
@@ -1669,7 +1669,7 @@
     ])
 
 
-class TestFuncargFactory:
+class TestFixtureFactory:
     def test_receives_funcargs(self, testdir):
         testdir.makepyfile("""
             import pytest
@@ -1809,7 +1809,7 @@
             "*test_function*advanced*FAILED",
         ])
 
-class TestFuncargManager:
+class TestFixtureManager:
     def pytest_funcarg__testdir(self, request):
         testdir = request.getfuncargvalue("testdir")
         testdir.makeconftest("""
@@ -1817,7 +1817,7 @@
                 return "conftest"
 
             def pytest_funcarg__fm(request):
-                return request.funcargmanager
+                return request._fixturemanager
 
             def pytest_funcarg__item(request):
                 return request._pyfuncitem
@@ -1828,7 +1828,7 @@
         testdir.makepyfile("""
             def test_hello(item, fm):
                 for name in ("fm", "hello", "item"):
-                    faclist = fm.getfactorylist(name, item.nodeid)
+                    faclist = fm.getfixturedeflist(name, item.nodeid)
                     assert len(faclist) == 1
                     fac = faclist[0]
                     assert fac.func.__name__ == "pytest_funcarg__" + name
@@ -1844,7 +1844,7 @@
                 def pytest_funcarg__hello(self, request):
                     return "class"
                 def test_hello(self, item, fm):
-                    faclist = fm.getfactorylist("hello", item.nodeid)
+                    faclist = fm.getfixturedeflist("hello", item.nodeid)
                     print (faclist)
                     assert len(faclist) == 3
                     assert faclist[0].func(item._request) == "conftest"
@@ -1870,7 +1870,7 @@
                 pass
 
             def pytest_funcarg__fm(request):
-                return request.funcargmanager
+                return request._fixturemanager
 
             def pytest_funcarg__item(request):
                 return request._pyfuncitem
@@ -1919,11 +1919,11 @@
                 pass
 
             def test_func1(request):
-                assert "db" not in request.funcargnames
+                assert "db" not in request.fixturenames
 
             @pytest.mark.needsdb
             def test_func2(request):
-                assert "db" in request.funcargnames
+                assert "db" in request.fixturenames
         """)
         reprec = testdir.inline_run("-s")
         reprec.assertoutcome(passed=2)
@@ -2105,7 +2105,7 @@
         reprec.assertoutcome(passed=5)
 
 
-class TestFuncargMarker:
+class TestFixtureMarker:
     def test_parametrize(self, testdir):
         testdir.makepyfile("""
             import pytest
@@ -2686,7 +2686,7 @@
     reprec.assertoutcome(passed=1)
 
 
-def test_request_funcargnames(testdir):
+def test_request_fixturenames(testdir):
     testdir.makepyfile("""
         import pytest
         @pytest.fixture()
@@ -2699,8 +2699,23 @@
         def sarg(tmpdir):
             pass
         def test_function(request, farg):
-            assert set(request.funcargnames) == \
+            assert set(request.fixturenames) == \
                    set(["tmpdir", "sarg", "arg1", "request", "farg"])
     """)
     reprec = testdir.inline_run()
     reprec.assertoutcome(passed=1)
+
+def test_funcargnames_compatattr(testdir):
+    testdir.makepyfile("""
+        def pytest_generate_tests(metafunc):
+            assert metafunc.funcargnames == metafunc.fixturenames
+        def pytest_funcarg__fn(request):
+            assert request._pyfuncitem.funcargnames == \
+                   request._pyfuncitem.fixturenames
+            return request.funcargnames, request.fixturenames
+
+        def test_hello(fn):
+            assert fn[0] == fn[1]
+    """)
+    reprec = testdir.inline_run()
+    reprec.assertoutcome(passed=1)


diff -r 70b4758381a0f1f453bb450ae349eedb3b0f1000 -r 8d87ff80839344ad785f4d07c081ccab5603325e testing/test_terminal.py
--- a/testing/test_terminal.py
+++ b/testing/test_terminal.py
@@ -26,7 +26,7 @@
         return l
 
 def pytest_generate_tests(metafunc):
-    if "option" in metafunc.funcargnames:
+    if "option" in metafunc.fixturenames:
         metafunc.addcall(id="default",
                          funcargs={'option': Option(verbose=False)})
         metafunc.addcall(id="verbose",



https://bitbucket.org/hpk42/pytest/changeset/0d8d41c1f4c9/
changeset:   0d8d41c1f4c9
user:        hpk42
date:        2012-10-05 14:24:45
summary:     make the default non-error pass simpler and faster, refine error reporting by presenting "fixture" tracebacks
affected #:  3 files

diff -r 8d87ff80839344ad785f4d07c081ccab5603325e -r 0d8d41c1f4c9f0bfc11523b446cb3176cb31db70 _pytest/main.py
--- a/_pytest/main.py
+++ b/_pytest/main.py
@@ -310,16 +310,7 @@
     def _repr_failure_py(self, excinfo, style=None):
         fm = self.session._fixturemanager
         if excinfo.errisinstance(fm.FixtureLookupError):
-            function = excinfo.value.function
-            factblines = excinfo.value.factblines
-            if function is not None:
-                fspath, lineno = getfslineno(function)
-                lines, _ = inspect.getsourcelines(function)
-                for i, line in enumerate(lines):
-                    if line.strip().startswith('def'):
-                        return fm.FixtureLookupErrorRepr(fspath,
-                                    lineno, lines[:i+1],
-                                    str(excinfo.value.msg), factblines)
+            return excinfo.value.formatrepr()
         if self.config.option.fulltrace:
             style="long"
         else:


diff -r 8d87ff80839344ad785f4d07c081ccab5603325e -r 0d8d41c1f4c9f0bfc11523b446cb3176cb31db70 _pytest/python.py
--- a/_pytest/python.py
+++ b/_pytest/python.py
@@ -993,20 +993,12 @@
 
     def _getfixturedeflist(self, argname):
         fixturedeflist = self._arg2fixturedeflist.get(argname, None)
-        getfixturetb = None
-        function = None
         if fixturedeflist is None:
-            if self._fixturestack:
-                function = self._fixturestack[-1].func
-                getfixturetb = lambda: self._fixturestack[:-1]
-            else:
-                function = self.function
             fixturedeflist = self._fixturemanager.getfixturedeflist(
                             argname, self._parentid)
             self._arg2fixturedeflist[argname] = fixturedeflist
         if not fixturedeflist:
-            self._fixturemanager._raiselookupfailed(argname, function,
-                                                   self._parentid, getfixturetb)
+            raise FixtureLookupError(argname, self)
         return fixturedeflist
 
     @property
@@ -1085,8 +1077,7 @@
 
     def raiseerror(self, msg):
         """ raise a FixtureLookupError with the given message. """
-        raise self._fixturemanager.FixtureLookupError(self.function, msg)
-
+        raise self._fixturemanager.FixtureLookupError(None, self, msg)
 
     def _fillfixtures(self):
         item = self._pyfuncitem
@@ -1250,32 +1241,58 @@
     return new_kwargs
 
 class FixtureLookupError(LookupError):
-    """ could not find a factory. """
-    def __init__(self, function, msg, factblines=None):
-        self.function = function
+    """ could not return a requested Fixture (missing or invalid). """
+    def __init__(self, argname, request, msg=None):
+        self.argname = argname
+        self.request = request
+        self.fixturestack = list(request._fixturestack)
         self.msg = msg
-        self.factblines = factblines
+
+    def formatrepr(self):
+        tblines = []
+        addline = tblines.append
+        stack = [self.request._pyfuncitem.obj]
+        stack.extend(map(lambda x: x.func, self.fixturestack))
+        msg = self.msg
+        if msg is not None:
+            stack = stack[:-1] # the last fixture raise an error, let's present
+                               # it at the requesting side
+        for function in stack:
+            fspath, lineno = getfslineno(function)
+            lines, _ = inspect.getsourcelines(function)
+            addline("file %s, line %s" % (fspath, lineno+1))
+            for i, line in enumerate(lines):
+                line = line.rstrip()
+                addline("  " + line)
+                if line.lstrip().startswith('def'):
+                    break
+
+        if msg is None:
+            fm = self.request._fixturemanager
+            nodeid = self.request._parentid
+            available = []
+            for name, fixturedef in fm.arg2fixturedeflist.items():
+                faclist = list(fm._matchfactories(fixturedef, self.request._parentid))
+                if faclist:
+                    available.append(name)
+            msg = "fixture %r not found" % (self.argname,)
+            msg += "\n available fixtures: %s" %(", ".join(available),)
+            msg += "\n use 'py.test --fixtures [testpath]' for help on them."
+
+        return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)
 
 class FixtureLookupErrorRepr(TerminalRepr):
-    def __init__(self, filename, firstlineno, deflines, errorstring, factblines):
-        self.deflines = deflines
+    def __init__(self, filename, firstlineno, tblines, errorstring, argname):
+        self.tblines = tblines
         self.errorstring = errorstring
         self.filename = filename
         self.firstlineno = firstlineno
-        self.factblines = factblines
+        self.argname = argname
 
     def toterminal(self, tw):
-        tw.line()
-        if self.factblines:
-            tw.line('    dependency of:')
-            for fixturedef in self.factblines:
-                tw.line('        %s in %s' % (
-                    fixturedef.argname,
-                    fixturedef.baseid,
-                ))
-            tw.line()
-        for line in self.deflines:
-            tw.line("    " + line.strip())
+        #tw.line("FixtureLookupError: %s" %(self.argname), red=True)
+        for tbline in self.tblines:
+            tw.line(tbline.rstrip())
         for line in self.errorstring.split("\n"):
             tw.line("        " + line.strip(), red=True)
         tw.line()
@@ -1436,18 +1453,6 @@
             if nodeid.startswith(fixturedef.baseid):
                 yield fixturedef
 
-    def _raiselookupfailed(self, argname, function, nodeid, getfixturetb=None):
-        available = []
-        for name, fixturedef in self.arg2fixturedeflist.items():
-            faclist = list(self._matchfactories(fixturedef, nodeid))
-            if faclist:
-                available.append(name)
-        msg = "LookupError: no factory found for argument %r" % (argname,)
-        msg += "\n available funcargs: %s" %(", ".join(available),)
-        msg += "\n use 'py.test --fixtures [testpath]' for help on them."
-        lines = getfixturetb and getfixturetb() or []
-        raise FixtureLookupError(function, msg, lines)
-
     def addargfinalizer(self, finalizer, argname):
         l = self._arg2finish.setdefault(argname, [])
         l.append(finalizer)


diff -r 8d87ff80839344ad785f4d07c081ccab5603325e -r 0d8d41c1f4c9f0bfc11523b446cb3176cb31db70 testing/test_python.py
--- a/testing/test_python.py
+++ b/testing/test_python.py
@@ -559,7 +559,7 @@
         assert result.ret != 0
         result.stdout.fnmatch_lines([
             "*def test_func(some)*",
-            "*LookupError*",
+            "*fixture*some*not found*",
             "*xyzsomething*",
         ])
 
@@ -1416,8 +1416,8 @@
     result.stdout.fnmatch_lines([
         "*ERROR*test_lookup_error*",
         "*def test_lookup_error(unknown):*",
-        "*LookupError: no factory found*unknown*",
-        "*available funcargs*",
+        "*fixture*unknown*not found*",
+        "*available fixtures*",
         "*1 error*",
     ])
     assert "INTERNAL" not in result.stdout.str()
@@ -1750,12 +1750,13 @@
                 pass
             """)
         result = testdir.runpytest()
-        result.stdout.fnmatch_lines([
-            "*dependency of:*",
-            "*call_fail*",
-            "*def fail(*",
-            "*LookupError: no factory found for argument 'missing'",
-        ])
+        result.stdout.fnmatch_lines("""
+            *pytest.fixture()*
+            *def call_fail(fail)*
+            *pytest.fixture()*
+            *def fail*
+            *fixture*'missing'*not found*
+        """)
 
     def test_factory_setup_as_classes(self, testdir):
         testdir.makepyfile("""
@@ -2585,7 +2586,7 @@
         assert result.ret != 0
         result.stdout.fnmatch_lines([
             "*def gen(qwe123):*",
-            "*no factory*qwe123*",
+            "*fixture*qwe123*not found*",
             "*1 error*",
         ])
 
@@ -2602,7 +2603,7 @@
         assert result.ret != 0
         result.stdout.fnmatch_lines([
             "*def gen(qwe123):*",
-            "*no factory*qwe123*",
+            "*fixture*qwe123*not found*",
             "*1 error*",
         ])
 



https://bitbucket.org/hpk42/pytest/changeset/05bd8a8df91e/
changeset:   05bd8a8df91e
user:        hpk42
date:        2012-10-05 14:35:16
summary:     bump version
affected #:  2 files

diff -r 0d8d41c1f4c9f0bfc11523b446cb3176cb31db70 -r 05bd8a8df91ee15eaf1ab7e9aa21e3265fe62151 _pytest/__init__.py
--- a/_pytest/__init__.py
+++ b/_pytest/__init__.py
@@ -1,2 +1,2 @@
 #
-__version__ = '2.3.0.dev17'
+__version__ = '2.3.0.dev18'


diff -r 0d8d41c1f4c9f0bfc11523b446cb3176cb31db70 -r 05bd8a8df91ee15eaf1ab7e9aa21e3265fe62151 setup.py
--- a/setup.py
+++ b/setup.py
@@ -24,7 +24,7 @@
         name='pytest',
         description='py.test: simple powerful testing with Python',
         long_description = long_description,
-        version='2.3.0.dev17',
+        version='2.3.0.dev18',
         url='http://pytest.org',
         license='MIT license',
         platforms=['unix', 'linux', 'osx', 'cygwin', 'win32'],

Repository URL: https://bitbucket.org/hpk42/pytest/

--

This is a commit notification from bitbucket.org. You are receiving
this because you have the service enabled, addressing the recipient of
this email.



More information about the pytest-commit mailing list