PyTest: test with functions
If we don't have any of the fixture services we need to write a lot of code:
- We need to call the setup_db() in every test.
- We need to call the teardown_db() in every test - and it still does not work when the test fails.
- What if there is some work that needs to be done only once and not for every test?
examples/pytest/test_functions.py
import tempfile def test_one(): db_server = setup_db_server() db = setup_db() print(f" test_one {db}") assert True print(" test_one after") teardown_db(db) # teardown_db_server(db_server) def test_two(): db_server = setup_db_server() db = setup_db() print(f" test_two {db}") assert False print(" test_two after") teardown_db(db) # teardown_db_server(db_server) def test_three(): db_server = setup_db_server() db = setup_db() print(f" test_three {db}") assert True print(" test_three after") teardown_db(db) # teardown_db_server(db_server) def setup_db(): db = tempfile.TemporaryDirectory() ... print(f"setup_db {db}") return db def teardown_db(db): ... print(f"teardown_db {db}") def setup_db_server(): print("setup db_server") if 'db_server' not in setup_db_server.__dict__: print("new db_serverironment") setup_db_server.db_server = tempfile.TemporaryDirectory() return setup_db_server.db_server def teardown_db_server(db_server): print("teardown_db_server")
$ pytest -qqs test_functions.py setup db_server new db_serverironment setup_db <TemporaryDirectory '/tmp/tmpvct7ng6r'> test_one <TemporaryDirectory '/tmp/tmpvct7ng6r'> test_one after teardown_db <TemporaryDirectory '/tmp/tmpvct7ng6r'> setup db_server setup_db <TemporaryDirectory '/tmp/tmptmaql_a_'> test_two <TemporaryDirectory '/tmp/tmptmaql_a_'> setup db_server setup_db <TemporaryDirectory '/tmp/tmpwb18nwil'> test_three <TemporaryDirectory '/tmp/tmpwb18nwil'> test_three after teardown_db <TemporaryDirectory '/tmp/tmpwb18nwil'>