


In the previous post, we created the Pytest fixture which will create/drop Postgres database before/after the test method. In this part, I want to improve the fixture to be more flexible and configurable with the help of Pytest factory fixtures.
Limits of static fixture
For example, if you have more than one database to mock in the test
def test_create_user(test_db1, test_db2): ...
you must create almost two identical fixtures:
TEST_DB_URL = "postgresql://localhost" TEST_DB1_NAME = "test_foo" TEST_DB2_NAME = "test_bar" @pytest.fixture def test_db1(): with psycopg.connect(TEST_DB_URL, autocommit=True) as conn: cur = conn.cursor() cur.execute(f'DROP DATABASE IF EXISTS "{TEST_DB1_NAME}" WITH (FORCE)') cur.execute(f'CREATE DATABASE "{TEST_DB1_NAME}"') with psycopg.connect(TEST_DB_URL, dbname=TEST_DB1_NAME) as conn: yield conn cur.execute(f'DROP DATABASE IF EXISTS "{TEST_DB1_NAME}" WITH (FORCE)') @pytest.fixture def test_db2(): with psycopg.connect(TEST_DB_URL, autocommit=True) as conn: cur = conn.cursor() cur.execute(f'DROP DATABASE IF EXISTS "{TEST_DB2_NAME}" WITH (FORCE)') cur.execute(f'CREATE DATABASE "{TEST_DB2_NAME}"') with psycopg.connect(TEST_DB_URL, dbname=TEST_DB2_NAME) as conn: yield conn cur.execute(f'DROP DATABASE IF EXISTS "{TEST_DB2_NAME}" WITH (FORCE)')
Pytest fixture factories
"Static" fixtures are a bit limiting here. When needed almost the same with just a slight difference, you need to duplicate a code. Hopefully, the Pytest has a concept of factories as fixtures.
Factory fixture is a fixture which returns another fixture. Because, like every factory, it is a function, it can accept arguments to customize returned fixtures. By convention, you can prefix them with make_*, like make_test_db.
Specialized fixtures
The only argument to our fixture factory make_test_db will be a test database name to create/drop.
So, let's create two "specialized" fixtures based on the make_test_db factory fixture.
The usage will looks like:
@pytest.fixture def test_db_foo(make_test_db): yield from make_test_db("test_foo") @pytest.fixture def test_db_bar(make_test_db): yield from make_test_db("test_bar")
Sidenote: yield from
Did you notice the yield from? There is a key difference between yield and yield from on how they handle the flow of data and control within generators.
In Python, both yield and yield from are used within generator functions to produce a sequence of values, but
- yield is used to pause a generator function's execution and return a single value to the caller.
- while yield from is used to delegate the generation of values to another generator. It essentially "flattens" the nested generator, passing its yielded values directly to the caller of the outer generator.
I.e., we don't want to "yield" from a specialized fixture but from a fixture factory. Therefore yield from is required here.
Fixture factory to create/drop database
Changes required to our original fixture creating/dropping database are actually almost none except the wrapping the code to the inner function.
@pytest.fixture def make_test_db(): def _(test_db_name: str): with psycopg.connect(TEST_DB_URL, autocommit=True) as conn: cur = conn.cursor() cur.execute(f'DROP DATABASE IF EXISTS "{test_db_name}" WITH (FORCE)') # type: ignore cur.execute(f'CREATE DATABASE "{test_db_name}"') # type: ignore with psycopg.connect(TEST_DB_URL, dbname=test_db_name) as conn: yield conn cur.execute(f'DROP DATABASE IF EXISTS "{test_db_name}" WITH (FORCE)') # type: ignore yield _
Bonus: Rewrite migrations fixture as factory fixture
In the previous part, I also had a fixture applying Yoyo migrations to just created empty database. It was also not very flexible. Let's do the same and wrap actual code to the inner function.
In this case, because the code doesn't need to do cleanup after return from test method (no yield in it), the
- factory fixture returns (not yield) inner function
- specialized fixture calls (not yield from) factory fixture
@pytest.fixture def make_yoyo(): """Applies Yoyo migrations to test DB.""" def _(test_db_name: str, migrations_dir: str): url = ( urlparse(TEST_DB_URL) . _replace(scheme="postgresql+psycopg") . _replace(path=test_db_name) .geturl() ) backend = get_backend(url) migrations = read_migrations(migrations_dir) if len(migrations) == 0: raise ValueError(f"No Yoyo migrations found in '{migrations_dir}'") with backend.lock(): backend.apply_migrations(backend.to_apply(migrations)) return _ @pytest.fixture def yoyo_foo(make_yoyo): migrations_dir = str(Path(__file__, "../../foo/migrations").resolve()) make_yoyo("test_foo", migrations_dir) @pytest.fixture def yoyo_bar(make_yoyo): migrations_dir = str(Path(__file__, "../../bar/migrations").resolve()) make_yoyo("test_bar", migrations_dir)
A test method which need two databases and apply migrations to them:
from psycopg import Connection def test_get_new_users_since_last_run( test_db_foo: Connection, test_db_bar: Connection, yoyo_foo, yoyo_bar): test_db_foo.execute("...") ...
Conclusion
Building your own fixture factory creating and dropping databases for the Pytest method is actually a good exercise to practice Python generator and yield/yield from operators.
I hope this article helped you with your own database test suite. Feel free to leave me your question in the comments and happy coding!
The above is the detailed content of Pytest and PostgreSQL: Fresh database for every test (part II). For more information, please follow other related articles on the PHP Chinese website!

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Serialization and deserialization of Python objects are key aspects of any non-trivial program. If you save something to a Python file, you do object serialization and deserialization if you read the configuration file, or if you respond to an HTTP request. In a sense, serialization and deserialization are the most boring things in the world. Who cares about all these formats and protocols? You want to persist or stream some Python objects and retrieve them in full at a later time. This is a great way to see the world on a conceptual level. However, on a practical level, the serialization scheme, format or protocol you choose may determine the speed, security, freedom of maintenance status, and other aspects of the program

Python's statistics module provides powerful data statistical analysis capabilities to help us quickly understand the overall characteristics of data, such as biostatistics and business analysis. Instead of looking at data points one by one, just look at statistics such as mean or variance to discover trends and features in the original data that may be ignored, and compare large datasets more easily and effectively. This tutorial will explain how to calculate the mean and measure the degree of dispersion of the dataset. Unless otherwise stated, all functions in this module support the calculation of the mean() function instead of simply summing the average. Floating point numbers can also be used. import random import statistics from fracti


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
