FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Five layers of tests that stop dirty client data reaching your model

Plain Python catches mixed amount formats and duplicate order IDs at the head of the pipeline, and a dedicated library takes over as the project grows.

ShareLinkedInFacebookX

In brief

  • Write many cheap unit tests for transformation functions and keep only a few expensive E2E tests, because E2E tests break easily.
  • Check data for accuracy, completeness, validity and consistency, then combine those checks into a gate for every batch.
  • Great Expectations calls each assertion about data an Expectation; a Checkpoint is how checks run in production.
Pyramid of five data-testing layers. From bottom to top: unit tests, data checks, integration tests, batch gate and E2E. The bottom layer has many tests that run fast and cheaply. The top layer has few tests that run slowly and cost more. The batch gate layer is shaded orange because that is where a dirty batch is stopped before it reaches the model.
Five testing layers arranged as a test pyramid. Unit tests sit at the base and E2E at the apex, while the batch gate is where a dirty batch is stopped before it reaches the model. Source: IBM, BrowserStack, Guru99, Microsoft Code-With Engineering Playbook.

A retail chain’s order file arrives in the first week of an engagement, exported from three different systems. In the amount column, one row reads “1.250.000”, another “1,250,000”, a third is blank, and one order ID appears twice. The revenue forecasting model will accept every one of those rows without complaint.

IBM sums up the problem with the familiar phrase “garbage in, garbage out”: poor input data produces wrong model output. IBM also defines data quality as the degree to which a dataset meets the criteria of accuracy, completeness, validity and consistency. This guide turns those four criteria into working code.

For a Forward Deployed Engineer, this work often decides whether the first demo keeps the client’s trust. When the model returns a strange number, you need to be able to point to the row that caused it and explain how that row got through.

What you will build, and what you need

You will build five layers of checks in the spirit of the test pyramid. The bottom layer holds many fast, cheap unit tests. The top holds very few end-to-end (E2E) tests, because they are slow, expensive and brittle. BrowserStack stresses that the pyramid only suggests where tests belong; it does not prescribe a fixed ratio.

All you need is Python 3 and an empty folder. The code below deliberately sticks to plain Python, using assert and the csv module, so the underlying logic stays visible. This is a simplified version: the pipeline accepts orders in VND (Vietnamese dong) only.

The first five steps map to the five layers. Step 6 adds no sixth layer. It switches tools, moving the data checks and the gate to a dedicated library once the project grows.

Step 1: unit tests for pure transformation functions

Start with the function that normalizes amounts, where errors creep in most easily. The function below is for VND only: it strips every period and comma, because the dong has no decimal subunit.

# transform.py
def normalize_amount(raw):
    """VND only. Do not use for currencies with decimal places."""
    if raw is None:
        return None
    cleaned = raw.strip().replace(".", "").replace(",", "")
    if not cleaned.isdigit():
        return None
    return float(cleaned)
# test_transform.py
from transform import normalize_amount

assert normalize_amount("1.250.000") == 1250000.0
assert normalize_amount("1,250,000") == 1250000.0
assert normalize_amount(" 500000 ") == 500000.0
assert normalize_amount("") is None
assert normalize_amount("abc") is None
print("unit OK")

Run python test_transform.py. If you see unit OK, the tests pass. Guru99 explains the value of this layer: unit tests surface errors close to where they originate, so fixes are quicker and cheaper.

The VND restriction is deliberate. Feed this function a USD order written as “99.50” and it returns 9950, wrong by a factor of 100 with no error raised. That is why, in step 2, every non-VND row is flagged and quarantined until you write a separate normalization function for each currency.

Try normalize_amount("-50000") as well. It returns None, because the minus sign makes isdigit() return false. Whether refund orders may be negative is a business decision; ask the client rather than guess.

Step 2: turn the four quality criteria into checks

Unit tests check your code. This step checks the client’s data. Each condition below corresponds to one of IBM’s criteria.

# checks.py
SUPPORTED_CURRENCY = "VND"  # simplified version: VND only

def check_batch(rows):
    failures, seen = [], set()
    for i, r in enumerate(rows):
        oid = r.get("order_id")
        if not oid:
            failures.append((i, "missing order_id"))        # completeness
        elif oid in seen:
            failures.append((i, "duplicate order_id"))      # consistency
        seen.add(oid)
        if r.get("amount") is None or r["amount"] <= 0:
            failures.append((i, "invalid amount"))          # validity
        if r.get("currency") != SUPPORTED_CURRENCY:
            failures.append((i, "unsupported currency"))    # validity
    return failures

Accuracy is the hardest criterion to express as a rule, because a number can be correctly formatted and still wrong. The practical approach is to ask the client for a reference figure, such as last month’s total revenue in the accounting system, and then add a check that compares the batch total with it.

Step 3: integration tests between stages

Functions that each work correctly will not necessarily work together. Guru99 describes integration testing as the layer that finds defects where modules interact. In a pipeline, that means the joints between the read, transform and check steps.

Create fixtures/orders_sample.csv with five rows and two planted errors:

order_id,amount,currency
A1,1.250.000,VND
A2,"1,250,000",VND
A2,300000,VND
A4,,VND
A5,99000,VND
# test_pipeline.py
import csv
from transform import normalize_amount
from checks import check_batch

def load(path):
    with open(path, newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    for r in rows:
        r["amount"] = normalize_amount(r.get("amount"))
    return rows

rows = load("fixtures/orders_sample.csv")
msgs = {m for _, m in check_batch(rows)}
assert len(rows) == 5
assert msgs == {"duplicate order_id", "invalid amount"}
print("integration OK")

This test catches a class of error that unit tests miss. In the file, the amount containing commas has to be in double quotes. If a later export drops the quotes, the csv module splits “1,250,000” across several columns, the currency column receives an unexpected value, and the test turns red at once instead of letting a wrong number travel on.

Step 4: a gate on every run

According to Guru99, a smoke test confirms that a build is stable enough for further testing. In a pipeline, apply the same idea to each batch: a clean enough batch passes, and anything else stops before it reaches the model.

# gate.py
from checks import check_batch

MAX_BAD_RATIO = 0.02  # assumed threshold, agree it with the client

def gate(rows):
    bad = {i for i, _ in check_batch(rows)}
    ratio = len(bad) / max(len(rows), 1)
    if not rows or ratio > MAX_BAD_RATIO:
        raise SystemExit(f"BATCH BLOCKED: {len(bad)}/{len(rows)} bad rows")
    clean = [r for i, r in enumerate(rows) if i not in bad]
    quarantine = [r for i, r in enumerate(rows) if i in bad]
    return clean, quarantine

Say a batch has 1,000 rows. If 15 are bad, the error rate is 1.5%: the batch proceeds with 985 clean rows, and the 15 bad ones go to quarantine for the client to review. If 37 are bad, the rate is 3.7% and the whole batch is blocked, because that many errors usually signals a change in the source system rather than a few typos.

Step 5: only a few E2E tests, run close to production

Microsoft’s Code-With Engineering Playbook describes E2E testing as checking the whole application from start to finish with every component assembled. The playbook also warns that the higher a test sits, the slower it is and the more effort it takes to write, run and maintain.

One or two scenarios are therefore enough: take a real file with sensitive data masked, run it through the entire pipeline, and check whether the model’s output is plausible.

TestGrid advises always putting the user’s perspective first. On a client site, the sensible application of that advice is to run E2E tests as close to production as possible: the same kind of connection, the same access permissions and the same file format the real system will send. A sample file you put together on your laptop cannot stand in for any of that.

Step 6: move to Great Expectations

This step adds no new layer. It replaces the tooling for the data checks (step 2) and the gate (step 4). As the number of rules grows, move the data side to Great Expectations.

GX Core is a Python library for building and running data validation workflows in code. Each condition in check_batch corresponds to an Expectation, a verifiable assertion about data.

The snippet below is an illustration of a single rule, “order_id must not be missing”, written with GX Core 1.x calls. Function names may differ between versions, so check the GX documentation for the version you install before relying on it.

# gx_demo.py  (illustration; check against the GX docs)
import great_expectations as gx
import pandas as pd

df = pd.read_csv("fixtures/orders_sample.csv", dtype=str)

context = gx.get_context()
source = context.data_sources.add_pandas("orders")
asset = source.add_dataframe_asset(name="orders_df")
batch_def = asset.add_batch_definition_whole_dataframe("whole")
batch = batch_def.get_batch(batch_parameters={"dataframe": df})

exp = gx.expectations.ExpectColumnValuesToNotBeNull(column="order_id")
print(batch.validate(exp).success)

With the fixture from step 3, the result should be True, since all five rows have an order_id. Delete the ID from one row and run it again to see the result flip to False.

The gate function, in turn, corresponds to a Checkpoint. The GX documentation calls Checkpoints the primary means of validating data when GX is deployed in production. Your next exercise: write the remaining three rules from step 2 as Expectations, then group them into a Checkpoint.

Common mistakes

The most common mistake is pouring effort into E2E tests and skipping unit tests. Every red run then costs half a day of hunting for the step that failed. Another is setting the blocking threshold without consulting the client. A 2% threshold is a business call; engineering cannot settle it alone.

The last is quietly deleting bad rows. Quarantine means keeping them, recording the reason and sending the list to the client. The client may well discover that their own system is producing the bad data.

How to put this skill on a CV

On a CV, “wrote tests” says little. Write a specific sentence instead, for example: built a validation gate for data batches that quarantines bad rows and blocks batches above an error threshold before they reach the model.

In interviews, bring the five-row fixture from step 3 and be ready to run it live on your laptop. Show the interviewer which errors you planted in the data and which layer of the pipeline catches each one.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
8 sources
Read next on the roadmap · Stage 5: DeploymentKeep the PDF out of your queueClaim checks keep messages small, idempotent filters survive duplicate delivery, and a few dozen lines of plain Python build the whole pipeline on a laptop.