Hidung
test runner mendukung setup_package()
dan teardown_package()
metode. Berikut kutipan dari dokumen:
Dalam aplikasi saya, saya memiliki setup_package()
yang kira-kira seperti berikut ini:
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
Selain itu, semua kelas kasus uji disubklasifikasikan dari kelas dasar, yang, penting, mendefinisikan tearDown
umum 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()
Subclass sering menimpa setUp
dasar , tetapi biasanya tidak perlu mengganti tearDown
- dengan memutar kembali transaksi, ini memastikan bahwa pengujian berikutnya akan dimulai pada database yang benar-benar bersih.