4  Professional Workflows: Testing and Git

4.1 Introduction

In the previous chapter, we learned that pure functions, those with no side effects and deterministic outputs, are the building blocks of reliable code. Small, testable functions are the foundation of reproducible pipelines.

This brings us to two final, crucial questions: how do we prove that our functions actually do what we claim they do? And how do we manage the complexity of collaborating with others (and with AI) without breaking everything?

This chapter addresses both questions by introducing unit testing and advanced Git workflows. You will learn what unit tests are and why they are essential for reliable data analysis, how to write and run them in both R (with {testthat}) and Python (with pytest), and how to use LLMs to accelerate test writing while embracing your role as a code reviewer. We will also cover professional Git techniques like Trunk-Based Development and interactive staging, which are especially valuable when managing code generated by AI assistants.

4.2 Part 1: Unit Testing

The answer to “how do we prove it works?” is unit testing. A unit test is a piece of code whose sole job is to check that another piece of code, a “unit”, works correctly. In our functional world, the “unit” is almost always a single function. This is why we spent so much time on FP in the previous chapter. Small, pure functions are not just easy to reason about; they are incredibly easy to test.

Writing tests is your contract with your collaborators and your future self. It’s a formal promise that your function, calculate_mean_mpg(), given a specific input, will always produce a specific, correct output. It’s the safety net that catches bugs before they make it into your final analysis and the tool that gives you the confidence to refactor and improve your code without breaking it.

4.2.1 The Philosophy of a Good Unit Test

So, what should we test? Writing good tests is a skill, but it revolves around answering a few key questions about your function. For any function you write, you should have tests that cover:

  • The “Happy Path”: does the function return the expected, correct value for a typical, valid input?
  • Bad Inputs: does the function fail gracefully or throw an informative error when given garbage input (e.g., a string instead of a number, a data frame with the wrong columns)?
  • Edge Cases: how does the function handle tricky but valid inputs? For example, what happens if it receives an empty data frame, a vector with NA values, or a vector where all the numbers are the same?

Writing tests forces you to think through these scenarios, and in doing so, almost always leads you to write more robust and well-designed functions.

4.2.2 Unit Testing in Practice

Let’s imagine we’ve written a simple helper function to normalise a numeric vector (i.e., scale it to have a mean of 0 and a standard deviation of 1). We’ll save this in a file named utils.R or utils.py.

R version (utils.R):

normalize_vector <- function(x) {
  (x - mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE)
}

Python version (utils.py):

import numpy as np

def normalize_vector(x):
  return (x - np.nanmean(x)) / np.nanstd(x)

Now, let’s write tests for it.

4.2.2.1 Testing in R with {testthat}

In R, the standard for unit testing is the {testthat} package. The convention is to create a tests/testthat/ directory in your project, and for a script utils.R, you would create a test file named test-utils.R.

Inside test-utils.R, we use the test_that() function to group related expectations.

# In file: tests/testthat/test-utils.R

# First, we need to load the function we want to test
source("../../utils.R")

library(testthat)

test_that("Normalization works on a simple vector (the happy path)", {
  # 1. Setup: Create input and expected output
  input_vector <- c(10, 20, 30)
  expected_output <- c(-1, 0, 1)

  # 2. Action: Run the function
  actual_output <- normalize_vector(input_vector)

  # 3. Expectation: Check if the actual output matches the expected output
  expect_equal(actual_output, expected_output)
})

test_that("Normalization handles NA values correctly", {
  input_with_na <- c(10, 20, 30, NA)
  expected_output <- c(-1, 0, 1, NA)

  actual_output <- normalize_vector(input_with_na)

  # We need to use expect_equal because it knows how to compare NAs
  expect_equal(actual_output, expected_output)
})

The expect_equal() function checks for near-exact equality. {testthat} has many other expect_*() functions, like expect_error() to check that a function fails correctly, or expect_warning() to check for warnings.

4.2.2.2 Testing in Python with pytest

In Python, the de facto standard is pytest. It’s incredibly simple and powerful. The convention is to create a tests/ directory, and your test files should be named test_*.py. Inside, you just write functions whose names start with test_ and use Python’s standard assert keyword.

# In file: tests/test_utils.py

import numpy as np
from utils import normalize_vector # Import our function

def test_normalize_vector_happy_path():
    # 1. Setup
    input_vector = np.array([10, 20, 30])
    expected_output = np.array([-1.0, 0.0, 1.0])

    # 2. Action
    actual_output = normalize_vector(input_vector)

    # 3. Expectation
    # For floating point numbers, it's better to check for "close enough"
    assert np.allclose(actual_output, expected_output)

def test_normalize_vector_with_nas():
    input_with_na = np.array([10, 20, 30, np.nan])
    expected_output = np.array([-1.0, 0.0, 1.0, np.nan])

    actual_output = normalize_vector(input_with_na)

    # `np.allclose` doesn't handle NaNs, but `np.testing.assert_allclose` does!
    np.testing.assert_allclose(actual_output, expected_output)

Because this isn’t a package though (yet), but a simple project with scripts, you also need to create another file called pytest.ini, which will tell pytest where to find the tests:

[pytest]
# Discover tests in the tests/ directory
testpaths = tests/

# Include default patterns and your hyphenated pattern
python_files = test_*.py *_test.py test-*.py

# Adds the root directory to the pythonpath, without this
# it'll be impossible to import normalize_vector() from
# utils.py
pythonpath = .

To run your tests, you simply navigate to your project’s root directory in the terminal and run the command pytest. It will automatically discover and run all your tests for you. That being said, you will get an error:

>       assert np.allclose(actual_output, expected_output)
E       assert False
E        +  where False = <function allclose at 0x7f0e81c959f0>(array([-1.22474487,  0.        ,  1.22474487]), array([-1.,  0.,  1.])    def test_normalize_vector_with_nas():
        input_with_na = np.array([10, 20, 30, np.nan])
        expected_output = np.array([-1.0, 0.0, 1.0, np.nan])

        actual_output = normalize_vector(input_with_na)

        # `np.allclose` doesn't handle NaNs, but `np.testing.assert_allclose` does!
>       np.testing.assert_allclose(actual_output, expected_output)
E       AssertionError:
E       Not equal to tolerance rtol=1e-07, atol=0
E
E       Mismatched elements: 2 / 4 (50%)
E       Max absolute difference among violations: 0.22474487
E       Max relative difference among violations: 0.22474487
E        ACTUAL: array([-1.224745,  0.      ,  1.224745,       nan])
E        DESIRED: array([-1.,  0.,  1., nan])

tests/test_utils.py:25: AssertionError
====================================================== short test summary info =======================================================
FAILED tests/test_utils.py::test_normalize_vector_happy_path - assert False
FAILED tests/test_utils.py::test_normalize_vector_with_nas - AssertionError:
========================================================= 2 failed in 0.15s ==========================================================

You don’t encounter this issue in R and understanding why reveals how valuable unit tests can be. (Hint: how does the implementation of the sd function, which computes the standard deviation, differ between R and NumPy?)

4.2.3 Testing as a Design Tool

Testing can also help you with programming, by thinking about edge cases. For example, what happens if we try to normalise a vector where all the elements are the same?

Let’s write a test for this edge case first.

pytest version:

# tests/test_utils.py
def test_normalize_vector_with_zero_std():
    input_vector = np.array([5, 5, 5, 5])
    actual_output = normalize_vector(input_vector)
    # The current function will return `[nan, nan, nan, nan]`
    # Let's assert that we expect a vector of zeros instead.
    assert np.allclose(actual_output, np.array([0, 0, 0, 0]))

If we run pytest now, this test will fail. Our test has just revealed a flaw in our function’s design. This process is a core part of Test-Driven Development (TDD): write a failing, but correct, test, then write the code to make it pass.

Let’s improve our function:


import numpy as np

def normalize_vector(x):
  std_dev = np.nanstd(x)
  if std_dev == 0:
    # If std is 0, all elements are the mean. Return a vector of zeros.
    return np.zeros_like(x, dtype=float)
  return (x - np.nanmean(x)) / std_dev

Now, if we run pytest again, our new test will pass. We used testing not just to verify our code, but to actively make it more robust and thoughtful.

4.2.4 The Modern Data Scientist’s Role: Reviewer and AI Collaborator

In the past, writing tests was often seen as a chore. Today, LLMs make this process very easy.

4.2.4.1 Using LLMs to Write Tests

LLMs are fantastic at writing unit tests. They are good at handling boilerplate code and thinking of edge cases. You can provide your function to an LLM and give it a prompt like this:

“Here is my Python function normalize_vector. Please write three pytest unit tests for it. Include a test for the happy path with a simple array, a test for an array containing np.nan, and a test for the edge case where all elements in the array are identical.”

The LLM will likely generate high-quality test code that is very similar to what we wrote above.

TipAll you need is context

When using an LLM to generate tests, context is everything. If you are writing tests for functions that heavily use specific packages (like {dplyr} or pandas), providing the LLM with that package’s API reference ensures it writes idiomatic and correct tests.

For example, when testing T pipeline code, point the LLM at the project’s AGENTS.md and T-LANGUAGE-REFERENCE.md so it knows the exact syntax and runtime behaviour of the nodes it is testing. This is particularly useful for packages that are not very well-known (or internal packages to your company that aren’t even public) or packages that have been updated very recently, as the LLM’s training data cutoff might not include the latest versions of the package.

This is a massive productivity boost. However, this introduces a new, critical role for the data scientist: you are the reviewer.

An LLM does not write your tests; it generates a draft. It is your professional responsibility to:

  1. Read and understand every line of the test code.
  2. Verify that the expected_output is actually correct.
  3. Confirm that the tests cover the cases you care about.
  4. Commit that code under your name, taking full ownership of it.

“A COMPUTER CAN NEVER BE HELD ACCOUNTABLE, THEREFORE A COMPUTER MUST NEVER MAKE A MANAGEMENT DECISION” - IBM Training Manual, 1979.

This principle is, in my opinion, even more important for tests than for production code. Even before LLMs, we relied on code we didn’t write ourselves. At my first job, my boss insisted that I avoid external packages entirely and rewrite everything from scratch. I ignored her and continued using the packages I trusted. At some point, you have to trust strangers. That was true then, and it is true now, except that “strangers” now includes LLMs and developers who themselves rely heavily on LLMs.

But here is the key difference: tests are small. Unlike a sprawling codebase, a unit test is short enough to read and understand completely. When you review an LLM-generated test, you can verify that the expected output is correct and that the test covers the right cases. This makes tests uniquely suited to the “trust but verify” workflow that AI-assisted development demands.

4.2.4.2 The Test Oracle Problem: Establishing Ground Truth for AI

When you prompt an AI assistant to write both your analytical code and its corresponding unit tests, you run headfirst into a subtle and dangerous trap: the test oracle problem.

In software engineering, a test oracle is the mechanism that determines whether a program’s output is correct. If you ask an LLM to implement a complex statistical calculation (such as computing weighted quantiles or calculating a Gini coefficient) and then ask the same LLM to write the unit test, the model will happily write an assertion that verifies its own implementation—even if its underlying math is subtly wrong, biased, or missing an edge case. The test passes, giving you a false sense of security.

For AI-assisted data science to be safe and efficient, the human must provide or verify the oracle. You do not need to write every line of code, but you must prepare the ground truth before trusting the model’s implementation.

In practice, there are three powerful types of oracles you should prepare:

  1. Golden Datasets (Snapshot Testing): A golden dataset is a small, hand-crafted, or authoritatively verified table of inputs and expected outputs. You can compute the expected values by hand for a three-row table, extract them from a trusted textbook, or export them from an established legacy system. When the LLM generates a vectorized pipeline node in Python or R, your test asserts that it produces bit-for-bit or numerically identical results to the golden snapshot.

  2. Reference Implementations (Dual-Running): Suppose you want an LLM to write a high-performance, parallelized data cleaning routine, or port an algorithm across languages (for example, from R to Python or Julia). Rather than verifying the new implementation by eye, you use the existing, trusted code as the oracle. You run both implementations on the same sample inputs and assert that their outputs match:

    def test_optimized_against_reference():
        sample_input = generate_sample_data()
        # Reference oracle: trusted, simple, but perhaps slow
        expected = reference_cleaner(sample_input)
        # AI-generated candidate: fast, complex, or cross-language
        actual = fast_ai_cleaner(sample_input)
        pd.testing.assert_frame_equal(actual, expected)
  3. Property-Based Oracles and Invariants: Sometimes you cannot predict the exact output for every arbitrary input, but you know the mathematical laws that must hold true. In property-based testing, you assert these invariants:

    • Conservation laws: Total revenue across subgroups must equal total unfiltered revenue.
    • Bounded ranges: Probabilities must always fall in \([0, 1]\); normalized Z-scores must have a sample mean of 0 and standard deviation of 1.
    • Idempotence: Running the cleaner twice on the same data must produce the exact same output as running it once (clean(clean(x)) == clean(x)).
    • Set preservation: Sorting or deriving fields must never silently drop unique row IDs or invent new records.

By preparing oracles upfront, you create an objective verification harness. The LLM can draft, refactor, and optimize code freely, and you have an automated, mathematically grounded referee to verify that the results are genuinely correct.

4.3 Part 2: Advanced Version Control

I assume you already know the basics of Git: clone, add, commit, and push. If you don’t, there are countless tutorials available, and I highly recommend you check one out and then come back to this.

In this section, we will focus on the techniques that separate the “I submit code via Dropbox” novice from the professional data scientist: Trunk-Based Development and managing AI-generated code.

4.3.1 A Better Way to Collaborate: Trunk-Based Development

A common mistake for new teams is to use branches to add new features, and then let these feature branches live for a very long time. A data scientist might create a branch called feature-big-analysis, work on it for three weeks, and then try to merge it back into main. The result is often what’s called “merge hell”: main has changed so much in three weeks that merging the branch back in creates dozens of conflicts and is a painful, stressful process.

To avoid this, many professional teams use a workflow called Trunk-Based Development (TBD). The philosophy is simple but powerful:

All developers integrate their work back into the main branch (the “trunk”) as frequently as possible, at least once a day.

This means that feature branches are incredibly short-lived. Instead of a single, massive feature branch that takes weeks, you create many tiny branches that each take a few hours or a day at most.

4.3.1.1 How to Work with Short-Lived Branches

But how can you merge something back into main if the feature isn’t finished? The main branch must always be stable and runnable. You can’t merge broken code.

The first way to solve this issue is to use feature flags.

A feature flag is just a simple variable (like a TRUE/FALSE switch) that lets you turn a new, unfinished part of the code on or off. This allows you to merge the code into main while keeping it “off” until it’s ready.

Imagine you are adding a new, complex plot to analysis.R, but it will take a few days to get right.

# At the top of your analysis.R script
# --- Configuration ---
use_new_scatterplot <- FALSE # Set to FALSE while in development

# ... lots of existing, working code ...

# --- New Feature Code ---
if (use_new_scatterplot) {
  # All your new, unfinished, possibly-buggy plotting code goes here.
  # It won't run as long as the flag is FALSE.
  library(scatterplot3d)
  scatterplot3d(mtcars$mpg, mtcars$hp, mtcars$wt)
}

With this if block, you can safely merge your changes into main. The new code is there, but it won’t execute and won’t break the existing analysis. Other developers can pull your changes and won’t even notice. Once you’ve finished the feature in subsequent small commits, the final change is just to flip the switch: use_new_scatterplot <- TRUE.

4.3.2 Collaborative Hygiene: Rebase vs. Merge

When you and a colleague both work on main, your histories can diverge. When you git pull, Git behaves in two ways:

  1. Merge (Default): creates a “merge commit” that ties the histories together. This results in a messy, non-linear history graph if done frequently.
  2. Rebase (Recommended): temporarily lifts your commits, pulls your colleague’s changes, and then replays your commits on top.

In data science projects, where identifying when a plot or number changed is critical, a linear history is valuable. I strongly recommend configuring Git to use rebase by default:

git config --global pull.rebase true

Now, when you git pull, your local changes will stay at the “tip” of the history, keeping the log clean.

4.3.3 Working with LLMs and Git: Managing AI-Generated Changes

When working with LLMs like GitHub Copilot, it’s crucial to review changes carefully before committing them. Git provides a powerful tool for this: interactive staging.

4.3.3.1 Interactive Staging: Accepting changes chunk by chunk

Git’s interactive staging feature (git add -p) is perfect for reviewing LLM changes. Instead of blindly adding all changes with git add ., git add -p lets you review each “hunk” (chunk of changes) individually.

Suppose an LLM refactored your Python script. You run:

git add -p analysis.py

Git will show you a chunk of changes and prompt you:

@@ -1,2 +1,4 @@
 # Load required libraries
 import pandas as pd
+import matplotlib.pyplot as plt
+import seaborn as sns
Stage this hunk [y,n,q,a,d,s,e,?]?

You can reply:

  • y: Yes, stage this (I approve).
  • n: No, do not stage this (I reject or want to edit later).
  • s: Split this hunk into smaller pieces (if the LLM did two unrelated things in one block).
  • e: Edit the hunk manually before staging.

This forces you to be the reviewer. It prevents “accidental” AI hallucinations (like deleting a critical import) from slipping into your repository.

4.3.3.2 Example LLM Workflow

  1. Save state: git commit -m "Working state before LLM"
  2. Prompt LLM: “Please refactor this function to be more efficient.”
  3. Review: Run git diff to see what it did.
  4. Select: Run git add -p and say y only to the parts that look correct.
  5. Clean: Run git checkout . to discard the parts you rejected.
  6. Verify: Run your unit tests!

This workflow ensures you maintain full control over your codebase while benefiting from LLM assistance.

4.4 Part 3: Testing T Pipelines with Testcraft

The R and Python testing we have just covered handles the code inside your nodes. But what about the pipeline itself? Does it have the right structure? Do nodes depend on each other in the right order? Does the data flowing between nodes have the right shape after a build?

T has a built-in testing system for this: the testcraft package and the t test CLI command.

4.4.1 The t test Command

When you initialise a T project with t init, the project gets a tests/ directory alongside src/. Any .t file in tests/ whose name starts with test- is automatically discovered and run by:

t test

This is the T equivalent of pytest or testthat::test_dir(). Each test file is a T script that builds a pipeline (or reads from an already-built one), makes assertions using expect_* functions, and fails loudly if any assertion does not hold.

4.4.2 Agent- and CI-friendly output

The t test command can emit machine-readable results, which is exactly what an AI agent or a CI script needs to decide what to do next without parsing human-friendly text. Pass --json for a structured summary of the whole run:

t test --json tests/
{
  "schema_version": "1",
  "status": "passed",
  "total": 15,
  "passed": 14,
  "failed": 1,
  "duration_ms": 2340,
  "results": [
    { "file": "tests/test_arithmetic.t", "status": "passed", "duration_ms": 120, "error": null },
    { "file": "tests/test_strings.t", "status": "failed", "duration_ms": 85, "error": "Assertion failed at line 42: expected \"hello\" but got \"world\"" }
  ]
}

The agent loop is then straightforward: run t test --json, read the top-level status, and only if it is "failed", read the error field of each failing result to decide the fix.

Notice why the oracles we discussed in Part 1 are indispensable here. An autonomous agent cannot navigate by vibes; it needs unambiguous, objective exit criteria. If the tests in your tests/ directory are vague or self-referential, an agent might “fix” a broken test simply by modifying the assertion to match its own buggy output, or by writing a trivial stub that returns a hardcoded value. When your test suite is anchored by strict oracles—golden datasets, invariant checks, and reference implementations—the agent has an uncompromising benchmark. It can propose an edit, execute t test --json, inspect the precise structural or numerical discrepancy, and iterate autonomously until the oracle is satisfied.

For CI, --format junit emits JUnit XML that runners and dashboards understand:

t test --format junit tests/

You can also filter what runs:

t test --only "stats"     # run only tests matching "stats"
t test --not "slow"       # skip tests matching "slow"
t test --failfast         # stop on the first failure
t test --list             # list tests without running them
t test --timeout 30       # mark tests slower than 30s as failed

To exclude whole files or directories automatically, add a tests/.tignore:

# tests/.tignore
slow_integration.t
*_benchmark.t
legacy/
Tip

In the REPL. t_test() returns a DataFrame with the same results, so you can inspect failures interactively:

results = t_test()
failed = results |> filter($status == "failed")
nrow(failed)   -- 0 if everything passed

4.4.3 The expect_* Primitives

Testcraft’s expect_* functions return a typed Expect value, Expect_pass, Expect_stop, or Expect_hold, rather than a bare boolean. This matters because when you wrap one in assert(), a failure gives you a rich diagnostic message instead of a generic AssertionError: false:

-- Bare assert: not very helpful on failure
assert(nrow(df) == 4)          -- AssertionError: expression evaluated to false

-- expect_*: tells you exactly what went wrong
assert(expect_nrow(df, 4))     -- AssertionError: expected 4 rows, got 7
assert(expect_colnames(df, ["id", "val"]))
  -- AssertionError: column mismatch: got ["id", "score"], expected ["id", "val"]

The core expectations you will use most often:

Function What it checks
expect_equal(actual, expected) Deep equality with tolerance for floats
expect_nrow(df, n) DataFrame has exactly n rows
expect_ncol(df, n) DataFrame has exactly n columns
expect_colnames(df, names) Column names match exactly (order-sensitive)
expect_has_colnames(df, names) DataFrame contains at least these columns
expect_no_na(df, col) No NA values in col
expect_type(x, "Int") Value has the expected type
expect_error(expr) Expression produces an Error value
expect_gt/gte/lt/lte(a, b) Numeric comparisons
expect_between(x, lo, hi) Value falls within bounds
expect_unique(x) All elements are distinct
expect_match(str, pattern) String matches a regex

4.4.4 Testing Node Outputs

The typical pattern is: build the pipeline, read each node with read_node(), then assert on the result. Here is a complete test file for the GLM pipeline from the previous chapter:

-- tests/test-glm-pipeline.t
import stats
import dataframe

p = pipeline {
  data_node = node(
    command = <{
      data.frame(
        x = c(1.0, 2.0, 3.0, 4.0, 5.0),
        y = c(0L, 0L, 1L, 1L, 1L)
      )
    }>,
    runtime = R,
    serializer = ^ipc
  )
  model_node = node(
    command = <{
      data_node$y <- as.factor(data_node$y)
      glm(y ~ x, data = data_node, family = binomial(link = "logit"))
    }>,
    runtime = R,
    serializer = ^pmml,
    deserializer = ^ipc
  )
}

build_pipeline(p)

-- Test node outputs
data = read_node(p.data_node)
assert(expect_nrow(data, 5))
assert(expect_colnames(data, ["x", "y"]))
assert(expect_no_na(data, "x"))

model = read_node(p.model_node)
assert(expect_type(model, "Model"))

print("✓ glm pipeline: all assertions passed")

4.4.5 Testing the Pipeline Structure

Testcraft also provides expectations that operate directly on the pipeline DAG, before or after building. These are unique to T and have no equivalent in testthat or pytest: they test the structure of the computation, not just the outputs.

-- Check that p is a valid Pipeline value
assert(expect_pipeline(p))

-- Check that the pipeline contains exactly these nodes
assert(expect_nodes(p, ["data_node", "model_node"]))

-- Check that model_node depends on data_node
assert(expect_dependency(p, "data_node", "model_node"))

-- Check runtimes and serializers are correctly set
assert(expect_runtime(p, "model_node", "R"))
assert(expect_serializer(p, "model_node", ^pmml))
assert(expect_deserializer(p, "model_node", ^ipc))

-- Check that model_node was actually built successfully
assert(expect_computed(p.model_node))

These structural tests are most valuable as a guard against refactoring accidents. If you reorganise the pipeline and accidentally break a dependency, expect_dependency will catch it immediately, before any downstream output has a chance to silently produce wrong results.

4.4.6 The Fixture-Chain Pattern

For more complex test suites, T supports composing pipelines with chain() and parallel(). The pattern is to separate data-producing nodes from assertion nodes, and compose them into a combined pipeline:

-- A fixture pipeline produces the base data
fixture = pipeline {
  data = node(
    command = read_csv("tests/data/sample.csv"),
    serializer = ^csv
  )
}

-- A test pipeline consumes and transforms it, then checks the result
test_filter = pipeline {
  filtered = node(
    command = data |> filter($score >= 88),
    serializer = ^csv,
    deserializer = ^csv
  )
  -- A dedicated "check" node whose output is a Dict of assertion results
  check_filter = node(
    command = [
      nrow_check:    assert(expect_nrow(filtered, 2)),
      colnames_check: assert(expect_colnames(filtered, ["name", "score", "grade"]))
    ],
    serializer = ^json,
    deserializer = ^csv
  )
}

-- chain() wires fixture.data into test_filter;
-- parallel() allows multiple independent test pipelines to run from the same fixture
combined = chain(fixture, parallel(test_filter))
build_pipeline(combined)

The check_filter node serializes its result as JSON: a named Dict where each key is the name of an assertion and each value is true on success or an Error on failure. This makes test results inspectable and diffable, not just pass/fail.

4.4.7 Summary of Testing Levels

In a well-tested T project, you will have tests at three levels:

Level Where Tool What it catches
Function tests/testthat/ or tests/test_*.py {testthat}, pytest Bugs in the R/Python helper functions used inside nodes
Node output tests/test-*.t t test + expect_* Wrong data shapes, unexpected NAs, bad column names after a build
Pipeline structure tests/test-*.t t test + expect_pipeline/nodes/dependency Broken DAG structure, wrong runtimes, serializer mismatches

These three layers complement each other. Function tests are fast and cheap to write. Node output tests catch integration bugs that only appear when R and Python code runs inside a Nix sandbox. Pipeline structure tests catch architectural regressions when the pipeline definition is refactored.

4.5 Hands-On Exercises

In these exercises, you will work in pairs or groups of three starting from a T pipeline project to practice collaborative Git workflows, unit testing (pytest or {testthat}), T pipeline testing (t test), Pull Requests (PRs), and AI-assisted code review.

4.5.1 Exercise 1: Pair/Trio Pipeline, Function & Test Workflow via Pull Requests

Goal: Start from a shared T project and split responsibilities across team members—one person sets up the repository and pipeline skeleton, another implements and pushes the decoupled pure function, and another independently builds a test oracle, writes unit and pipeline tests with LLM assistance, and opens a Pull Request.

4.5.1.1 Team Roles

  • Trios (3 people):
    • Developer A (Repo & Pipeline Setup): Scaffolds the T project, creates the dataset, pushes the GitHub repository with an initial src/pipeline.t skeleton, and coordinates reviews.
    • Developer B (Function Author): Implements the pure Python or R helper function (src/cleaning.py or src/cleaning.R) and wires it into src/pipeline.t, commits, and pushes (without writing tests).
    • Developer C (Tester & PR Reviewer): Independently builds a golden test oracle, writes unit tests (pytest / {testthat}) and T pipeline tests (tests/test-pipeline.t) on a branch, and opens a PR.
  • Pairs (2 people):
    • Developer A (Setup & Author): Performs both the repo/pipeline setup and the pure function implementation, then commits and pushes to main.
    • Developer B (Tester & Reviewer): Takes the Developer C role—pulls main, builds the oracle, writes the unit and pipeline tests on a branch, and opens a PR.

4.5.1.2 Step 1: Repository & T Pipeline Setup (Developer A)

  1. Choose one node language for your helper logic: Python (pandas, numpy, pytest) or R ({dplyr}, {testthat}).

  2. Scaffold the T project:

    nix shell --accept-flake-config github:b-rodrigues/tlang -c t init --project collab_pipeline
    cd collab_pipeline

    Declare the required packages in tproject.toml (for Python: pandas, pyarrow, numpy, pytest; for R: arrow, dplyr, testthat), run t update inside nix develop if needed, and verify you never invoke pip install or install.packages().

  3. Create the toy dataset and pipeline skeleton:

    • Create data/survey.csv with columns respondent_id, group, and score (include at least one missing respondent_id, inconsistent whitespace/casing in group such as " Alpha ", and a sentinel negative score like -999).
    • Create src/pipeline.t with an ingestion node raw_survey = node(command = read_csv("data/survey.csv"), serializer = ^ipc) and a placeholder comment or downstream node slot for the cleaning step.
    • If using Python, add pytest.ini (testpaths = tests and pythonpath = .) so pytest can import from src/.
  4. Initialize Git, push to GitHub, and invite teammates:

    • Initialize the repo, commit the scaffold (tproject.toml, flake.nix, data/survey.csv, src/pipeline.t, README.md, .gitignore), and push to a new GitHub repository.

    • Add your teammate(s) as collaborators on GitHub.

    • Everyone clones the repo, enters nix develop, and configures linear pulls:

      git config pull.rebase true

4.5.1.3 Step 2: Implement the Pure Function & Wire the Pipeline (Developer B, or A in Pairs)

Pull the latest main (git pull). Using your AI coding assistant, implement only the decoupled cleaning function and wire it into src/pipeline.t (do not write any tests yet!).

Specification for clean_survey_scores(df):

  • Saved in src/cleaning.py (Python) or src/cleaning.R (R) so it can be both imported by unit tests and loaded by T via functions = [...].
  • Takes a DataFrame (pandas.DataFrame in Python or data.frame in R) with columns respondent_id, group, and score.
  • Must be a pure function: it must never mutate the caller’s df in place or rely on global variables.
  • Drops rows where respondent_id is missing (NA / NaN / None).
  • Normalizes group by stripping leading/trailing whitespace and converting to lowercase (e.g., " Alpha " becomes "alpha").
  • Treats sentinel negative values (score < 0, such as -999) as missing (NA / np.nan).
  • Adds a score_z column containing the Z-score of the valid score values: \((x - \bar{x}) / s\), where \(\bar{x}\) and \(s\) are the sample mean and sample standard deviation (\(n - 1\) denominator, i.e., ddof=1 in NumPy/pandas or sd() in R) computed over non-missing scores. If all valid scores are identical (\(s = 0\)), set score_z to 0.0 for non-missing scores; if fewer than two valid scores exist and \(s\) is undefined, handle missing values consistently and document the behavior.
  • Fails loudly with an informative error if required columns are missing.

Your workflow:

  1. Prompt your LLM assistant to draft clean_survey_scores in src/cleaning.py (or src/cleaning.R) and connect a cleaned_survey node in src/pipeline.t using pyn() or rn() with functions = ["src/cleaning.py"] (or ["src/cleaning.R"]), deserializer = ^ipc, and serializer = ^ipc.

  2. Review the generated code line by line: verify it avoids in-place mutation (inplace=True), silent except Exception: blocks, ambiguous DataFrame truthiness checks (if df:), and population-vs-sample standard deviation mismatches.

  3. Run t run src/pipeline.t inside nix develop to verify the pipeline builds, then stage, commit, and push to main (or via a short-lived PR reviewed by Developer A):

    git add -p src/
    git commit -m "feat: add clean_survey_scores helper and pipeline node"
    git push origin main

4.5.1.4 Step 3: Build an Independent Oracle & Open a Test PR (Developer C, or B in Pairs)

Now the Tester pulls main and creates a short-lived branch—without asking the LLM to invent expected outputs by reading clean_survey_scores (avoid the test oracle problem!).

  1. Sync with main and create a test branch:

    git pull
    git checkout -b test/survey-tests
  2. Compute a golden dataset by hand (before prompting the LLM): On paper or in a scratch note, construct a 4-row input table (for instance, scores [10, 20, 30, -999], messy group names like " Alpha ", and one row with a missing respondent_id) and calculate the exact expected cleaned table and score_z values yourself.

  3. Prompt your LLM to draft two layers of tests: Give the LLM your hand-computed golden dataset and the project structure, and ask it to draft:

    • Function unit tests in tests/test_cleaning.py (pytest) or tests/testthat/test-cleaning.R ({testthat}) covering:
      • Happy path: Verified against your hand-computed golden dataset using tolerance-based float comparisons (np.testing.assert_allclose / pytest.approx in Python, or expect_equal() in R)—never raw == on floats.
      • Bad inputs: Missing required columns or wrong input types raise an error (pytest.raises / expect_error()).
      • Edge cases: All valid scores identical (\(s = 0\)), all scores missing or sentinel negative, an empty DataFrame (0 rows), and verifying the original input DataFrame is not mutated in place.
      • Invariants: Output row count is always \(\le\) input row count, and when at least two distinct valid scores exist, non-missing score_z values have sample mean \(\approx 0\) and sample standard deviation \(\approx 1\).
    • Pipeline tests in tests/test-pipeline.t using Testcraft:
      • Structural expectations (expect_pipeline, expect_nodes, expect_dependency(p, "raw_survey", "cleaned_survey"), expect_serializer).
      • Node output expectations (expect_no_na on respondent_id, expected row count after filtering missing IDs).
  4. Review with git add -p, run both test layers, push, and open a PR:

    • Inspect the LLM-generated tests with git diff and stage only verified hunks:

      git add -p tests/
    • Run both the function tests (pytest or Rscript -e "testthat::test_dir('tests/testthat')") and the T pipeline tests (t test --json).

    • If your tests uncover a bug or unhandled edge case in the implementation, keep the accurate failing test—never weaken the oracle to make a test pass!

    • Commit, push your branch, and open a Pull Request on GitHub targeting main:

      git commit -m "test: add golden unit tests and pipeline structure tests"
      git push -u origin test/survey-tests

4.5.1.5 Step 4: Code Review, Bug Fixes, and Merging

  1. Review the PR on GitHub: Developer A and Developer B review the PR, checking every expected_output against the golden oracle and verifying meaningful assertions.
  2. Fix any discovered bugs: If the PR uncovered a real bug (e.g., crashing on an empty DataFrame or using ddof=0 instead of ddof=1), the Function Author fixes it on a small fix branch (fix/survey-edge-cases), merges it to main, and the Tester rebases test/survey-tests onto main so all tests turn green.
  3. Merge and sync: Once approved and passing, merge the PR into main (using Squash and merge or Rebase and merge), then everyone runs git checkout main && git pull and verifies both pytest/{testthat} and t test --json pass locally.

4.5.2 Exercise 2: Rotating Roles — Interactive Staging and Rebase Hygiene

Goal: Rotate roles on the same T project so every team member practices setup/authoring, testing, and reviewing—while using git add -p to tame noisy AI refactors and git rebase to integrate concurrent changes cleanly.

  1. Rotate roles: The previous Tester becomes the Feature Author; the previous Author becomes the Tester/Reviewer (in trios, rotate all three roles).
  2. Author a new feature alongside a noisy LLM refactor:
    • Create a short-lived branch (git checkout -b feat/outlier-flag).
    • Prompt your LLM assistant to add a new pure function flag_outliers(df, z_col = "score_z", threshold = 2.5) in src/cleaning.py (or src/cleaning.R) returning a new DataFrame with a boolean is_outlier column (failing loudly if z_col is missing), wire a downstream flagged_survey node in src/pipeline.t, and ask the LLM to “clean up and modernize” clean_survey_scores.
    • LLMs often bundle unrequested changes alongside requested features (renaming columns, breaking pipeline node names, or adding unused imports). Run git diff, then use interactive staging (git add -p) to:
      • Accept (y) or split (s) only the verified flag_outliers and flagged_survey hunks.
      • Reject (n) unrequested refactors that alter existing behavior.
      • Discard the rejected working-tree edits with git checkout -- . and re-run pytest (or {testthat}) and t test --json to confirm existing tests still pass.
    • Commit, push your branch, and open a PR on GitHub.
  3. Simulate concurrent Trunk-Based Development:
    • While the feat/outlier-flag PR is open, another teammate merges a small improvement to main (e.g., documenting the pipeline in README.md and adding an extra edge-case test in tests/).

    • The Feature Author brings feat/outlier-flag up to date by rebasing onto main rather than creating a merge commit:

      git fetch origin
      git rebase origin/main
    • If a conflict occurs, resolve it carefully, stage with git add, continue with git rebase --continue, re-run all tests (pytest / {testthat} and t test --json), and push safely with --force-with-lease:

      git push --force-with-lease
  4. Test the new node/function and merge:
    • The Tester checks out the PR branch (or opens a companion test PR), writes LLM-assisted unit tests for flag_outliers (values beyond \(\pm 2.5\), boundary values at 2.5, missing score_z values, missing z_col, and input immutability) and updates tests/test-pipeline.t to assert the new flagged_survey dependency, verifies all tests pass, and pushes.
    • The team reviews the final diff, merges the PR into main, and runs git pull + both test suites one last time on main.

4.6 Summary

In this chapter, we covered the safety protocols of professional data science with T:

  1. Unit tests (R’s {testthat}, Python’s pytest) prove that the helper functions living inside your nodes work correctly in isolation.
  2. Git workflows (Trunk-Based Development, rebasing, interactive staging) keep collaboration clean and protect you from AI-generated regressions.
  3. Testcraft (t test, expect_*) tests T pipelines at two levels: node outputs (does the data look right after a build?) and pipeline structure (does the DAG have the right shape, runtimes, and serializers?).

With these testing layers, Git hygiene, and test oracles in place, we now have the foundation to build an AI Harness. In the next chapter, we will see how to combine these verification tools with AGENTS.md and code-inspection literacy to safely delegate coding tasks to autonomous AI agents.