[py-dev] py.test: initializing test environment

Jan Balster jan at balster.info
Fri Nov 4 11:14:11 CET 2005


Hi Ian,

I'm not sure if this code snippet is the solution you wanted but I'll provide it
anyway :-)

Jan

Ian Bicking wrote:
> I want to add an option that effects the environment before any tests
> are collected.  But I'm having a hard time doing that.

conftest.py:
------------------------------------------------------------
import py

# add a new option
Option = py.test.Config.Option
option = py.test.Config.addoptions("my new testing options",
                                   Option('', '--setuptests',
                                          action="store_true",
                                          dest="setup_tests",
                                          default=False,
                                          help="setup tests"
                                          )
                                   )

def setup_tests():
    pass

# hooking into py.test Directory collector's chain ...
class SetupDirectory(py.test.collect.Directory):

    def __init__(self, fspath, parent=None):
        super(SetupDirectory, self).__init__(fspath, parent)
        # create files and dirs
        if option.setup_tests:
            setup_tests()

Directory = SetupDirectory
----------------------------------------------------------------


If you just want to create some data files you can use setup() and teardown():

conftest.py:
-----------------------------------------------------------------

...

# hooking into py.test Directory collector's chain ...
class SetupDirectory(py.test.collect.Directory):
    mypath = py.magic.autopath().dirpath().join('my_new_file')

    #setup and teardown are probably invoked multiple times
    def setup(self):
        # filenames are already collected
        # new testfiles created here are NOT executed
        if option.setup_tests:
            #create datafiles
            self.mypath.ensure()

    def teardown(self):
        #teardown_tests()
        # remove datafiles
        if mypath.check(exists= True):
            mypath.remove()

Directory = SetupDirectory
---------------------------------------------------------------------------



simple test, fails if py.test is invoked whitout the new --setuptests option
(test_file_was_created.py):
-----------------------------------------------------------------
import py

def test_file_exists():
    # fail if 'my_new_file' does not exist
    file = py.magic.autopath().dirpath().join('my_new_file')
    assert file.check(exists=True)
------------------------------------------------------------------



More information about the Pytest-dev mailing list