[TIP] Learning fixtures in py.test

Paradox paradox at pobox.com
Thu Oct 24 14:02:41 PDT 2013


I am trying to understand fixtures and how they are used.  I am writing 
tests for my program that interacts with an Sqlite database using 
Sqlalchemy.  I am working on Python 2.7.5 in Ubuntu 13.10.

My setup_session fixture is:

=================
@pytest.fixture (autouse = True)
def setup_session():
     db_file = 'database.db'
     engine = create_engine('sqlite:///' + db_file, echo = True)
     Base = declarative_base()
     Session = sessionmaker(bind=engine)
     session = Session()
     return session
==================

Then when I try to use that fixture in a test it is something like:
==================
def test_get_id_of_row(setup_session):
     assert(get_id_of_row('cell known to be in test data')==1)
==================

I am getting an error:
==================
NameError: global name 'session' is not defined
==================

Shouldn't that be taken care of by passing the setup_session fixture to 
the test function?  There is something I don't get about fixtures and 
would appreciate any pointers on where to read to better understand, I 
have read the pytest.org site on fixtures several times and it is still 
not sinking in!

thomas



More information about the testing-in-python mailing list