How to Build Testable Data Cleaning Pipelines in Python

For Data engineers building ingestion and cleaning pipelines · Based on ArjanCodes Functional Core Python Design

// TL;DR

Data engineers can use ArjanCodes Functional Core Python Design to untangle pipelines that fetch from APIs, clean records, score quality, and write to a database all in one function. Extract each cleaning and scoring rule into a pure function, model the flow as raw record → features → quality assessment → disposition with frozen dataclasses, and confine API fetches and DB writes to an imperative shell. The result: cleaning rules you test with plain values and no network, that stay stable as sources and sinks change. Use it when your pipeline function keeps growing and every test needs a live API or database.

Why do data pipelines become untestable?

A typical pipeline function fetches records from an API, applies several cleaning rules, scores each record for quality, flags the bad ones, and writes results to a database — all in one place. The cleaning logic is the valuable, rule-rich part, but it's trapped between network calls. Testing a single transformation rule means spinning up an API mock and a database, so most teams just don't test the rules at all.

The Functional Core, Imperative Shell pattern separates the what — your cleaning and scoring rules — from the where — the API and the database.

How do you turn cleaning rules into pure functions?

Audit the function first: tag each step as a calculation, mutation, external I/O, or decision. Your normalization, validation, and quality-scoring rules are calculations. Pull each into its own pure function that takes a value and returns a score or boolean:

```python

def is_valid_email(raw: str) -> bool: ...

def completeness_score(record: RawRecord) -> float: ...

```

Each must take only what it needs, return a value, and touch no external state. The purity test: same input, same output, no side effects. Because these functions operate on already-fetched data passed in as arguments, you test them instantly with plain dictionaries or dataclasses.

How do you structure the pipeline stages?

Name the real stages: `RawRecord → ExtractedFeatures → QualityAssessment → Disposition`. Build a frozen dataclass for each, using tuples for internal collections so no stage can mutate another's data. The number of stages equals the meaningful transformations in your domain — don't force arbitrary splits.

Write one pure transformation per stage, each taking the previous immutable output and returning the next. An orchestrator chains them with readable intermediate variables:

```python

features = extract_features(raw)

quality = assess_quality(features)

disposition = decide_disposition(quality)

```

No API calls, no DB writes, no logging inside these — they stay pure.

Where do the API and database live?

In the imperative shell. The shell fetches records from the API, hands each already-fetched record to the orchestrator, receives the immutable Disposition, and persists results to the database. It's allowed to be imperative; that's the point. The core never knows where data came from or where it's going — the separation-of-what-from-where principle in action.

This means you can swap the API source or the destination warehouse by editing only the shell, while every cleaning and scoring rule stays untouched and fully tested.

How do you avoid common pipeline pitfalls?

Don't mutate the same record object across cleaning steps — that forces you to track its whole history and leaves it in invalid intermediate states. Produce a fresh immutable snapshot per stage instead. Don't force immutability on enormous batches if copying becomes a performance problem; apply it where it clarifies flow and relax it on hot paths. And don't bury logging inside core functions — return rich results and let the shell log them.

If you ever need to mock the API or database to test a cleaning rule, a dependency has leaked into your core and must move to the shell.

Next step: Take your worst pipeline function, list every step, tag its concern, and extract your first cleaning rule into a pure function you can unit test without any network connection.

// FREQUENTLY ASKED QUESTIONS

How do I test cleaning rules without calling the real API?

Move the API fetch into the imperative shell and pass already-fetched records into your pure cleaning functions as arguments. Each rule then operates purely on in-memory values, so you test it with plain dictionaries or dataclasses — no API mock, no network. This covers edge cases like malformed or missing fields instantly and reliably.

Should each cleaning rule be its own stage in the pipeline?

No. Stages represent meaningful domain transformations like raw record → features → quality assessment → disposition, and the number of stages should match the real transformations, not the number of rules. Many individual cleaning rules can live inside a single feature-extraction or assessment stage; don't force arbitrary splits that add structure without clarity.

What if making records immutable slows my batch processing?

Immutability is a tool, not a mandate. If copying large batches just to stay pure hurts performance, that's a bad trade-off in Python. Apply frozen dataclasses where they make the flow easier to reason about — typically per-record assessments and dispositions — and relax immutability on large hot-path collections where speed matters more.