Næse
testløber understøtter setup_package()
og teardown_package()
metoder. Her er et uddrag fra dokumenterne:
I min applikation har jeg setup_package()
som ser nogenlunde ud som følgende:
def _create_database():
template_engine = sa.create_engine("postgres://[email protected]/postgres", echo=False)
conn = template_engine.connect()
conn = conn.execution_options(autocommit=False)
conn.execute("ROLLBACK")
try:
conn.execute("DROP DATABASE %s" % DB_NAME)
except sa.exc.ProgrammingError as e:
# Could not drop the database, probably does not exist
conn.execute("ROLLBACK")
except sa.exc.OperationalError as e:
# Could not drop database because it's being accessed by other users (psql prompt open?)
conn.execute("ROLLBACK")
conn.execute("CREATE DATABASE %s" % DB_NAME)
conn.close()
template_engine.dispose()
def setup_package():
_create_database()
engine = sa.create_engine("postgres://[email protected]/%s" % DB_NAME, echo=False)
session = sa.orm.scoped_session(sa.orm.sessionmaker())
session.configure(bind=engine)
Base.metadata.bind = engine
Base.metadata.create_all()
def teardown_package():
# no need to do anything as the old database is dropped at the start of every run
Derudover er alle testcaseklasser underklassificeret fra en basisklasse, som, hvad der er vigtigt, definerer en fælles tearDown
metode:
class BaseTest(unittest.TestCase):
def setUp(self):
# This makes things nicer if the previous test fails
# - without this all subsequent tests fail
self.tearDown()
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
session.expunge_all()
session.rollback()
Underklasser tilsidesætter ofte basis setUp
, men det er normalt ikke nødvendigt at tilsidesætte tearDown
- ved at rulle transaktionen tilbage sikrer det, at den næste test starter på en fuldstændig ren database.