Skip to content

Python Guide

Language Reference

Setup and use python

venv

Productive developer environment

How to structure a Python Project

Code Style

pre-commit black flake8 type hints & flake8-annotations & mypy isort flake8-docstrings

Key Librairies

Unit testing

Here is a basic example of a pytest test:

import pytest
from koala.io.config import Config
from koala.io.datawarehouse import DataWarehouse

class TestDataWarehouse:

    @pytest.fixture
    def dwh_config(self):
        return Config()


    @pytest.mark.parametrize("names", [True, False], ids=["NamesOnly", "All"])
    def test_get_all_metrics(self, dwh_config, names):
        # Given
        dwh = DataWarehouse(envir=dwh_config)

        # When
        results = dwh.get_all_metrics(name_only=names)

        # Then
        assert results is not None
        assert isinstance(results, list)

Here the test is test_get_all_metrics.

It pulls in the dwh_config fixture which I'll cover later.

It also uses pytest's parametrizing decorator to run the same test multiple times with different data configurations.

The key practice that makes testing really really easy is the Given/When/Then framework which makes the process of writing tests calmingly methodic and digestable.

Given Everything I need to setup a test. This can consist of test data but also of setting up a database connection using fixtures which I promise I'll cover later. The distinction I like is that fixtures return ERRORs where as tests throw FAILs.

When The part of the code under test. I try to make this section one line of code so it is really clear what is being tested and how a user would write the same line of code. It forces me to think about the Developer Experience (DX) of the API design.

Then This is the part where you confirm your expectations. Aim for proprty based aspects instead of fixed values. This might mean you have to sharpen your knowledge of metaprogramming methods like isinstance.

References


Last update: 2022-10-16