Fixtures meets parameters: Writing efficient, elegant and reusable tests
- Track:
- Testing, Quality Assurance, Security
- Type:
- Talk
- Level:
- intermediate
- Duration:
- 30 minutes
Abstract
We’re all familiar with pytest fixtures. They’re invaluable for setting up environments before each test run, tearing them down afterward, and providing essential data for test execution. They introduce modularity and reusability to tests, ensuring consistency across multiple runs. Similarly, pytest’s parametrize annotation allows us to run the same tests with various input permutations and combinations. Together, fixtures and parametrize form a powerful toolkit for creating clean, maintainable, and scalable test suites.
Now, let’s consider a common engineering scenario: migrating from an old API to a new one. The outputs of the two APIs remain the same, but the inputs differ. Tasks like refactoring and deprecating older APIs are part and parcel of every engineer’s job. So, how can we make this migration easier?
While core business logic often needs thoughtful redesign, our focus here is on tests, particularly unit tests. Pytest parametrize can help us run tests with different inputs, while fixtures simplify setup and teardown. But what if we could go a step further? Instead of writing entirely new tests for the new API, what if we could reuse existing tests?
In this talk, I’ll demonstrate how to enhance test reusability, simplify test management, and streamline test cleanup by passing pytest fixtures as parameters to existing tests and seamlessly upgrading existing tests to cover workflows and scenarios for both old and new APIs. Attendees will learn to write more efficient and elegant tests by leveraging the power of pytest!