

Bắt đầu một dự án bioinformatics mới thường có nghĩa là phải quyết định lại xem script đặt ở đâu, viết kiểm thử thế nào và cấu hình continuous integration ra sao. Mỗi dự án có xu hướng trả lời những câu hỏi đó theo một cách khác nhau, khiến việc tiếp nhận và bảo trì khó hơn.
Bài viết này mô tả một template workflow viết bằng Python mà chúng tôi dùng làm điểm khởi đầu (bioinfor-wf-template). Template cung cấp một cấu trúc nhất quán cho các app và workflow, một cách tiếp cận kiểm thử duy nhất (pytest), và một workflow CI chỉ chạy kiểm thử cho những tệp đã thay đổi. Nó hướng tới các dự án proof-of-concept; những nguyên tắc tương tự có thể áp dụng cho dự án Snakemake hoặc Nextflow bằng cơ chế kiểm thử gốc của chúng, và việc hỗ trợ các framework đó là một hướng mở rộng có thể có.
Một vài khó khăn lặp lại ở nhiều dự án bioinformatics:
Không có cấu trúc chuẩn
Kiểm thử thiếu đồng đều
CI/CD thiếu nhất quán
Tiếp nhận tốn thời gian
Template cung cấp:
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.mdÝ chính là app là những khối xây dựng tái sử dụng, còn workflow tổ hợp chúng thành pipeline.
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)Các mẫu hình ở đây là kiểm tra trước khi thực thi, cô lập bằng Docker để tái lập, chữ ký hàm rõ ràng, và type hints cho trình soạn thảo.
apps/fastqc/tests/test_fastq_in_pairs.py (kiểm thử đơn vị)
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 (kiểm thử end-to-end)
@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 existHai lớp kiểm thử phục vụ những mục đích khác nhau:
test_fastq_in_pairs.py): nhanh, không cần Dockertest_e2e.py): chậm hơn, cần Docker, chạy chính các công cụ# 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 testsMỗi app và workflow có một Makefile để các lệnh nhất quán:
apps/fastqc/Makefile
.PHONY: unittest e2e
unittest: pytest -v -k "not e2e" tests/
e2e: pytest -v -k "e2e" tests/Chạy kiểm thử cục bộ:
# 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 e2eChạy kiểm thử cho toàn bộ workflow:
# 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 chỉ chạy kiểm thử cho những tệp đã thay đổi:
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 doneSửa apps/fastqc/main.py
GitHub detects change → Run only fastqc testsSửa workflows/qc/main.py
GitHub detects change → Run qc workflow E2EIncludes fastqc + multiqc + orchestrationSửa README.md
GitHub detects no code changes → Skip all testsViệc chỉ chạy những kiểm thử bị ảnh hưởng là điều giữ cho thời gian CI tỉ lệ với kích thước thay đổi, thay vì kích thước kho.
Template dùng được cho bất kỳ công cụ bioinformatics nào được bọc trong Python. Một vài mẫu hình:
Hầu hết công cụ bioinformatics được đóng gói trong container. Bọc chúng trong Python giữ một quy ước gọi duy nhất:
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()Một số công cụ có gói Python, có thể dùng trực tiếp:
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()Mã phân tích tự viết nằm trong cùng cấu trúc:
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.columnsTạo cấu trúc:
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/Tạo cấu trúc:
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/Để tái lập môi trường, có thể thêm Pixi vào 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"] }Cách dùng:
# Install dependenciespixi install
# Run testspixi run test
# Run GitHub Actions locallypixi run ciBảng dưới đây mang tính minh hoạ, không phải một kết quả đo được; con số thực tế phụ thuộc vào nhóm và dự án.
| Khía cạnh | Trước | Sau |
|---|---|---|
| Thời gian tiếp nhận | thường tính bằng ngày | khoảng nửa ngày |
| Thiết lập kiểm thử | khác nhau theo dự án | pytest chuẩn hoá |
| Thiết lập CI/CD | viết từ đầu | sao chép workflow |
| Chạy kiểm thử cục bộ | "Làm sao để kiểm thử cái này?" | make -C apps/fastqc unittest |
| Tính nhất quán của mã | tuỳ nơi | type hints, kiểm tra đầu vào |
| Tạo app mới | sao chép mã có sẵn | dùng cấu trúc template |
| Tái sử dụng app | script dùng một lần | thành phần mô-đun |
| Tiếp nhận trong nhóm | mất nhiều thời gian | cấu trúc kèm tài liệu |
Mỗi hàm nên làm một việc:
# 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(): ...Giữ requirements.txt được cập nhật:
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_outputKhi số lượng app tăng, nhóm chúng theo lĩnh vực giúp kho dễ điều hướng hơn:
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_testsMột CONTRIBUTING.md trung tâm giúp quy trình dễ tìm thấy:
## 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



