

Starting a new bioinformatics project usually means deciding again where scripts live, how tests are written, and how continuous integration is configured. Each project tends to answer those questions differently, which makes onboarding and maintenance harder.
This post describes a Python-based workflow template we use as a starting point (bioinfor-wf-template). It provides a consistent structure for apps and workflows, a single testing approach (pytest), and a CI workflow that runs tests only for the files that changed. It is intended for proof-of-concept projects; the same principles can be applied to Snakemake or Nextflow projects using their native testing mechanisms, and support for those frameworks is a possible extension.
Several difficulties recur across bioinformatics projects:
No standard structure
Testing is uneven
CI/CD is inconsistent
Onboarding takes time
The template provides:
actbioinfor-wf-template/├── apps/ # Individual bioinformatics tools│ ├── fastqc/ # Quality control│ │ ├── main.py # Implementation│ │ ├── tests/ # Unit + E2E tests│ │ │ ├── test_fastq_in_pairs.py # Unit tests│ │ │ └── test_e2e.py # Integration tests│ │ └── Makefile # Local testing commands│ ├── multiqc/ # Aggregation│ │ ├── main.py│ │ ├── tests/│ │ └── Makefile│ └── [your-tool]/ # Add more tools│├── workflows/ # Composed pipelines│ ├── qc/ # Quality control workflow│ │ ├── main.py # Orchestrates apps│ │ ├── tests/│ │ └── Makefile│ └── [your-pipeline]/ # Add more workflows│├── .github/│ └── workflows/│ └── tests.yaml # GitHub Actions CI/CD│├── conftest.py # Shared pytest configuration├── pytest.ini # Pytest settings├── requirements.txt # Dependencies├── pixi.toml # (Optional) Reproducible environment└── README.mdThe main idea is that apps are reusable building blocks, and workflows compose them into pipelines.
apps/fastqc/main.py
def validate_fastq_files(fastq1: str, fastq2: str): """Validate paired FASTQ files match naming convention.""" base1 = os.path.basename(fastq1) base2 = os.path.basename(fastq2) expected_base2 = base1.replace("_R1_", "_R2_") if base2 != expected_base2: raise ValueError(f"Expected '{expected_base2}', got '{base2}'")
def run_fastqc(fastq1: str, fastq2: str, output_dir: str): """Run FastQC on paired FASTQ files using Docker.""" validate_fastq_files(fastq1, fastq2) cmd = [ "docker", "run", "--rm", "-v", f"{cwd}:{cwd}", "biocontainers/fastqc:v0.11.9_cv8", "fastqc", fastq1, fastq2, "--outdir", output_dir ] subprocess.run(cmd, check=True)The patterns here are validation before execution, Docker isolation for reproducibility, clear function signatures, and type hints for editor support.
apps/fastqc/tests/test_fastq_in_pairs.py (unit tests)
def test_validate_fastq_files_valid_pair(): """Test that valid paired files pass validation.""" fastq1 = "/path/sample_R1_001.fastq.gz" fastq2 = "/path/sample_R2_001.fastq.gz" validate_fastq_files(fastq1, fastq2) # Should not raise
def test_validate_fastq_files_invalid_pair(): """Test that mismatched files raise error.""" fastq1 = "/path/sample_R1_001.fastq.gz" fastq2 = "/path/sample_R3_001.fastq.gz" with pytest.raises(ValueError): validate_fastq_files(fastq1, fastq2)apps/fastqc/tests/test_e2e.py (end-to-end tests)
@pytest.fixturedef dummy_fastq_files(): """Create minimal FASTQ files for testing.""" fastq1.write_text("@SEQ_ID\nGATTT...\n+\nIIIII...\n") fastq2.write_text("@SEQ_ID\nGATTT...\n+\nIIIII...\n") return str(fastq1), str(fastq2)
@pytest.mark.skipif( not subprocess.run(["docker", "--version"]).returncode == 0, reason="Docker is not available")def test_run_fastqc_e2e(dummy_fastq_files, data_dir): """Test actual FastQC execution with real (dummy) data.""" fastq1, fastq2 = dummy_fastq_files run_fastqc(fastq1, fastq2, str(data_dir / "results")) # Assert output files existThe two test classes serve different purposes:
test_fastq_in_pairs.py): fast, no Docker requiredtest_e2e.py): slower, require Docker, exercise the actual tools# Clone the templategit clone git@github.com:riverxdata/bioinfor-wf-template.git my-pipelinecd my-pipeline
# Install dependenciespip install -r requirements.txt
# Run all tests locallypytest -v
# Or with Pixi (recommended)pixi global install actpixi run testsEach app and workflow has a Makefile so the commands are consistent:
apps/fastqc/Makefile
.PHONY: unittest e2e
unittest: pytest -v -k "not e2e" tests/
e2e: pytest -v -k "e2e" tests/Run tests locally:
# Unit tests only (fast - 10 seconds)make -C apps/fastqc unittest
# End-to-end tests (slower - 2 minutes)make -C apps/fastqc e2e
# All testsmake -C apps/fastqc unittest e2eRun tests for whole workflows:
# All unit tests in all appsfor app in apps/*; do make -C $app unittest; done
# All E2E tests in all workflowsfor workflow in workflows/*; do make -C $workflow e2e; done.github/workflows/tests.yaml runs tests only for the files that changed:
jobs: unittest_and_e2e: runs-on: ubuntu-latest steps: # 1. Detect changed files - uses: tj-actions/changed-files@v46.0.5 id: changed-files with: files: apps/** base: ${{ github.event.pull_request.base.ref }}
# 2. Run unit tests for changed apps - name: Unit tests if: steps.changed-files.outputs.all_changed_files != '' run: | for app in ${{ steps.changed-files.outputs.all_changed_files }}; do make -C $app unittest done
# 3. Run E2E tests for changed apps - name: E2E tests if: steps.changed-files.outputs.all_changed_files != '' run: | for app in ${{ steps.changed-files.outputs.all_changed_files }}; do make -C $app e2e done
# 4. Run all workflow E2E tests - name: Workflow tests run: | for workflow in workflows/*; do make -C $workflow e2e doneEditing apps/fastqc/main.py
GitHub detects change → Run only fastqc testsEditing workflows/qc/main.py
GitHub detects change → Run qc workflow E2EIncludes fastqc + multiqc + orchestrationEditing README.md
GitHub detects no code changes → Skip all testsRunning only the affected tests is what keeps the CI time proportional to the size of a change, rather than to the size of the repository.
The template works for any bioinformatics tool wrapped in Python. A few patterns:
Most bioinformatics tools are containerized. Wrapping them in Python keeps a single calling convention:
def run_bowtie2_alignment(reference, fastq1, fastq2, output_bam): """Align reads using Bowtie2 via Docker.""" cmd = [ "docker", "run", "--rm", "-v", f"{Path.cwd()}:{Path.cwd()}", "biocontainers/bowtie2:v2.5.1_cv1", "bowtie2-build", reference, "index", "-x", "index", "-1", fastq1, "-2", fastq2, "-S", output_bam ] subprocess.run(cmd, check=True)
# apps/bowtie2/tests/test_e2e.pydef test_bowtie2_alignment_e2e(reference_fasta, fastq_files): """Test alignment with real (dummy) data.""" run_bowtie2_alignment(*reference_fasta, *fastq_files, "output.bam") assert Path("output.bam").exists()Some tools have Python packages, which can be used directly:
import cutadapt
def trim_adapters(fastq1, fastq2, output_dir): """Trim adapters from FASTQ files.""" Path(output_dir).mkdir(exist_ok=True)
# Use cutadapt Python API adapter = "AGATCGGAAGAGC" # Common Illumina adapter results = cutadapt.main([ "-a", adapter, "-A", adapter, "-o", f"{output_dir}/trimmed_R1.fastq.gz", "-p", f"{output_dir}/trimmed_R2.fastq.gz", fastq1, fastq2 ]) return results
# apps/cutadapt/tests/test_e2e.pydef test_trim_adapters_e2e(fastq_files, tmp_path): """Test adapter trimming.""" trim_adapters(fastq_files[0], fastq_files[1], str(tmp_path)) assert (tmp_path / "trimmed_R1.fastq.gz").exists() assert (tmp_path / "trimmed_R2.fastq.gz").exists()Custom analysis code fits the same structure:
import pandas as pd
def count_genes(bam_file, annotation_gtf, output_csv): """Count reads per gene from BAM file.""" # Load annotation gtf = pd.read_csv(annotation_gtf, sep="\t", comment="#")
# Count using samtools + Python import pysam bam = pysam.AlignmentFile(bam_file)
counts = {} for read in bam: gene = read.get_tag("XG") if read.has_tag("XG") else "unknown" counts[gene] = counts.get(gene, 0) + 1
# Save results df = pd.DataFrame(list(counts.items()), columns=["gene", "count"]) df.to_csv(output_csv, index=False)
return df
# apps/gene_counter/tests/test_e2e.pydef test_gene_counting_e2e(bam_file, annotation_gtf, tmp_path): """Test gene counting.""" output_csv = tmp_path / "counts.csv" count_genes(bam_file, annotation_gtf, str(output_csv))
results = pd.read_csv(output_csv) assert len(results) > 0 assert "count" in results.columnsCreate the structure:
mkdir -p apps/myapp/teststouch apps/myapp/__init__.pytouch apps/myapp/main.pytouch apps/myapp/tests/test_unit.pytouch apps/myapp/tests/test_e2e.pytouch apps/myapp/Makefileapps/myapp/main.py
import subprocessfrom pathlib import Path
def validate_input(input_file: str): """Validate input data format.""" if not Path(input_file).exists(): raise FileNotFoundError(f"Input file not found: {input_file}")
def run_myapp(input_file: str, output_dir: str): """Run my bioinformatics tool.""" Path(output_dir).mkdir(parents=True, exist_ok=True)
cmd = [ "docker", "run", "--rm", "-v", f"{Path.cwd()}:{Path.cwd()}", "myregistry/myapp:latest", "myapp", input_file, "--output", output_dir ] subprocess.run(cmd, check=True)apps/myapp/tests/test_unit.py
from apps.myapp.main import validate_inputimport pytest
def test_validate_input_exists(): """Test validation of existing file.""" # Create temp file with open("/tmp/test_input.txt", "w") as f: f.write("test data")
# Should not raise validate_input("/tmp/test_input.txt")
def test_validate_input_missing(): """Test validation of missing file.""" with pytest.raises(FileNotFoundError): validate_input("/nonexistent/file.txt")apps/myapp/tests/test_e2e.py
import pytestfrom pathlib import Pathimport subprocessfrom apps.myapp.main import run_myapp
@pytest.mark.skipif( not subprocess.run(["docker", "--version"]).returncode == 0, reason="Docker not available")def test_run_myapp_e2e(tmp_path): """Test complete myapp execution.""" input_file = tmp_path / "input.txt" input_file.write_text("test data")
output_dir = tmp_path / "output" run_myapp(str(input_file), str(output_dir))
# Verify output assert output_dir.exists() assert (output_dir / "result.txt").exists()apps/myapp/Makefile
.PHONY: unittest e2e
unittest: pytest -v -k "not e2e" tests/
e2e: pytest -v -k "e2e" tests/Create the structure:
mkdir -p workflows/mypipeline/teststouch workflows/mypipeline/main.pytouch workflows/mypipeline/tests/test_e2e.pytouch workflows/mypipeline/Makefileworkflows/mypipeline/main.py
import argparsefrom apps.myapp.main import run_myappfrom apps.anotherap.main import run_anotherap
def run_mypipeline(input_file, output_dir): """Compose myapp and anotherap into a pipeline."""
# Step 1: Run first app intermediate_dir = f"{output_dir}/intermediate" run_myapp(input_file, intermediate_dir)
# Step 2: Run second app with output from first final_dir = f"{output_dir}/final" run_anotherap(f"{intermediate_dir}/result.txt", final_dir)
print(f"Pipeline complete. Results in: {final_dir}")
if __name__ == "__main__": parser = argparse.ArgumentParser(description="My bioinformatics pipeline") parser.add_argument("input_file") parser.add_argument("output_dir") args = parser.parse_args()
run_mypipeline(args.input_file, args.output_dir)workflows/mypipeline/tests/test_e2e.py
import subprocessfrom pathlib import Pathfrom workflows.mypipeline.main import run_mypipeline
def test_mypipeline_e2e(tmp_path): """Test complete pipeline execution.""" input_file = tmp_path / "input.txt" input_file.write_text("test data")
output_dir = tmp_path / "output" run_mypipeline(str(input_file), str(output_dir))
# Verify all outputs exist assert (output_dir / "intermediate").exists() assert (output_dir / "final").exists()workflows/mypipeline/Makefile
.PHONY: e2e
e2e: pytest -v -k "e2e" tests/For environment reproducibility, Pixi can be added to the template:
pixi.toml
[project]name = "bioinfor-wf"version = "0.1.0"channels = ["conda-forge", "bioconda"]
[dependencies]python = "3.12"pytest = ">=7.0"numpy = ">=1.24"pandas = ">=1.5"
[tasks]test = "pytest -v"unittest = "pytest -v -k 'not e2e'"e2e = "pytest -v -k 'e2e'"ci = "act push"
[environments]test = { channels = ["conda-forge", "bioconda", "nvidia"], features = ["gpu"] }dev = { features = ["dev"] }Usage:
# Install dependenciespixi install
# Run testspixi run test
# Run GitHub Actions locallypixi run ciThe table below is illustrative rather than a measured result; the actual figures depend on the team and the project.
| Aspect | Before | After |
|---|---|---|
| Onboarding time | typically days | about half a day |
| Test setup | different per project | standardized pytest |
| CI/CD setup | written from scratch | clone the workflow |
| Running tests locally | "How do I test this?" | make -C apps/fastqc unittest |
| Code consistency | varies | type hints, validation |
| New app creation | copy-paste existing code | use the template structure |
| App reusability | one-off scripts | modular components |
| Team onboarding | longer ramp-up | structure plus documentation |
Each function should do one thing:
# Avoid: multiple responsibilitiesdef process_fastq_and_align(fastq1, fastq2, ref, output): validate_fastq(fastq1, fastq2) align(fastq1, fastq2, ref, output) quality_check(output)
# Prefer: single responsibilitydef validate_fastq(fastq1, fastq2): ...def run_alignment(fastq1, fastq2, ref, output): ...def quality_check(bam_file): ...def run_analysis(input_file: str): """Validate before processing.""" input_path = Path(input_file) if not input_path.exists(): raise FileNotFoundError(f"Input file not found: {input_file}") if input_path.stat().st_size == 0: raise ValueError("Input file is empty")from pathlib import Pathfrom typing import List, Tuple
def process_samples(samples: List[str], output_dir: str) -> Tuple[Path, Path]: """Type hints help catch errors early.""" ...# Unit: Fast, no Docker neededdef test_validation(): assert validate(valid_input) == True
# E2E: Slow, includes Docker@pytest.mark.skipif(no_docker, reason="Docker required")def test_full_workflow_e2e(): ...Keep requirements.txt updated:
pytest>=7.0docker>=6.0numpy>=1.24pandas>=1.5import subprocessimport sys
def run_command(cmd: List[str]) -> bool: """Run shell command with proper error handling.""" try: result = subprocess.run(cmd, check=True, capture_output=True, text=True) return True except subprocess.CalledProcessError as e: print(f"Error: Command failed with exit code {e.returncode}") print(f"stderr: {e.stderr}") sys.exit(1)import logging
logger = logging.getLogger(__name__)
def process_pipeline(samples: List[str]): """Process with logging.""" for i, sample in enumerate(samples, 1): logger.info(f"Processing sample {i}/{len(samples)}: {sample}") # Process... logger.info(f"✓ Completed {sample}")from pathlib import Pathimport tempfile
def run_with_temp_files(input_file: str) -> str: """Create and clean temporary files automatically.""" with tempfile.TemporaryDirectory() as tmp_dir: tmp_path = Path(tmp_dir)
# Work with temp files intermediate = tmp_path / "intermediate.txt" # ... process ...
# Copy final result to output final_output = "final_result.txt" # ... copy ...
# Temp dir automatically cleaned up when exiting with block return final_outputAs the number of apps grows, grouping them by domain keeps the repository navigable:
apps/├── alignment/ # Group by domain│ ├── bowtie2/│ ├── bwa/│ └── hisat2/├── quality_control/│ ├── fastqc/│ ├── multiqc/│ └── qualimap/└── variant_calling/ ├── gatk/ └── samtools/
workflows/├── rnaseq/├── wgs/├── amplicon/└── metagenomics/#!/bin/bash# test_all.sh - Run all tests
failed_tests=0total_tests=0
for app in apps/*/*/; do if [ -f "$app/Makefile" ]; then total_tests=$((total_tests + 1)) if ! make -C "$app" unittest; then failed_tests=$((failed_tests + 1)) echo "❌ Failed: $app" else echo "✓ Passed: $app" fi fidone
echo "Tests: $((total_tests - failed_tests))/$total_tests passed"exit $failed_testsA central CONTRIBUTING.md keeps the workflow discoverable:
## Adding a New App
1. Create directory: `mkdir -p apps/category/myapp/tests`2. Copy template: `cp -r apps/fastqc/* apps/category/myapp/`3. Edit `main.py` with your logic4. Write tests in `tests/`5. Update `README.md`6. Create PR
## Adding a New Workflow
1. Create directory: `mkdir -p workflows/mypipeline/tests`2. Create `main.py` that composes apps3. Write E2E test in `tests/`4. Add to `.github/workflows/tests.yaml`# Clone the templategit clone git@github.com:riverxdata/bioinfor-wf-template.git my-analysis
# Install dependenciescd my-analysispip install -r requirements.txt
# Run testspytest -v
# Or with Pixipixi global install actpixi run test
# Or locally simulate GitHub Actionsact push



