Are you confused about pytest's fixtures?

Do you struggle to understand them?

#100daysOfCode #pytest #Python

🧵This one is for you👇
1️⃣ pytest's fixtures are functions decorated with "pytest.fixture" decorator

They can return value or produce side effects like creating/removing a database.

They can be located inside http://conftest.py  or inside the test file.
2️⃣ To use the value returned from the fixture function inside a test you need to add a parameter with the same name as the fixture function.
3️⃣ You can run part of the fixture before the test function (before yield) and the part after (after yield).

For example:
* create ES index before test function
* remove ES index after test function
👇
4️⃣ A fixture can accept parameters when using factories

It returns the factory method instead of value.

You can use the factory method inside a test to get a value based on provided parameters

For example, create users with different usernames👇
5️⃣ By default, fixtures run before/after each test - scope='function'.

You can change the scope of the fixture using the *scope* parameter:

* 'module' - before/after all tests in the module
* 'session' - before first and after the last test in the test suite
👇
6️⃣ You can provide multiple different fixtures to the same test by using

* fixture's params argument
* pytest's request

An example 👇
7️⃣ pytest also provides built-in fixtures like:

- tmp_path: pathlib.Path object to a temporary directory unique to each test function
- request: information on the executing test function
- caplog: Control logging and access log entries
- ...

Examples 👇
You can follow @jangiacomelli.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.