Testing Cheat Sheet
Commands, flags, and patterns for test runners across languages.
pytest (Python)
Section titled “pytest (Python)”pytest # Run all testspytest tests/ # Run directorypytest test_file.py # Run filepytest test_file.py::test_func # Run specific testpytest -k "pattern" # Run tests matching patternpytest -x # Stop on first failurepytest -v # Verbose outputpytest -s # Show print statementspytest --lf # Rerun last failedpytest --ff # Failed first, then restpytest -n auto # Parallel (pytest-xdist)pytest --cov=src # Coverage reportpytest --cov-report=html # HTML coveragepytest -m "slow" # Run marked testspytest -m "not slow" # Skip marked testsFixtures
Section titled “Fixtures”import pytest
@pytest.fixturedef db(): conn = create_connection() yield conn conn.close()
@pytest.fixture(scope="module")def shared_resource(): return expensive_setup()
def test_query(db): result = db.execute("SELECT 1") assert result == 1Parametrize
Section titled “Parametrize”@pytest.mark.parametrize("input,expected", [ (1, 2), (2, 4), (3, 6),])def test_double(input, expected): assert double(input) == expectedMarkers
Section titled “Markers”@pytest.mark.slowdef test_integration(): pass
@pytest.mark.skip(reason="Not implemented")def test_future(): pass
@pytest.mark.xfaildef test_known_bug(): passJest / Vitest (JavaScript/TypeScript)
Section titled “Jest / Vitest (JavaScript/TypeScript)”jest # Run all testsjest path/to/test # Run specific filejest -t "pattern" # Run tests matching namejest --watch # Watch modejest --watchAll # Watch all filesjest --coverage # Coverage reportjest --runInBand # Serial executionjest --bail # Stop on first failurejest --verbose # Verbose outputjest --detectOpenHandles # Debug hanging testsjest --testPathPattern="api" # Filter by pathStructure
Section titled “Structure”describe("Calculator", () => { let calc: Calculator;
beforeEach(() => { calc = new Calculator(); });
afterEach(() => { calc.reset(); });
it("adds numbers", () => { expect(calc.add(1, 2)).toBe(3); });
it.each([ [1, 2, 3], [0, 0, 0], [-1, 1, 0], ])("adds %i + %i = %i", (a, b, expected) => { expect(calc.add(a, b)).toBe(expected); });
it.skip("not implemented yet", () => {});
it.todo("add multiplication");});Matchers
Section titled “Matchers”expect(value).toBe(exact);expect(value).toEqual(deepEqual);expect(value).toBeTruthy();expect(value).toBeNull();expect(value).toContain(item);expect(value).toHaveLength(n);expect(value).toMatch(/regex/);expect(value).toThrow(Error);expect(fn).toHaveBeenCalled();expect(fn).toHaveBeenCalledWith(arg);Mocking
Section titled “Mocking”// Mock modulejest.mock("./api");
// Mock implementationconst mockFn = jest.fn().mockReturnValue(42);const mockAsync = jest.fn().mockResolvedValue(data);
// Spy on methodjest.spyOn(object, "method").mockImplementation(() => {});
// Clear mocksjest.clearAllMocks();jest.resetAllMocks();go test # Run package testsgo test ./... # Run all testsgo test -v # Verbosego test -run TestName # Run specific testgo test -run "Test.*Pattern" # Pattern matchgo test -count=1 # Disable cachego test -race # Race detectorgo test -cover # Coverage summarygo test -coverprofile=c.out # Coverage filego tool cover -html=c.out # HTML reportgo test -bench=. # Run benchmarksgo test -short # Skip long testsgo test -timeout 30s # Set timeoutTable-Driven Tests
Section titled “Table-Driven Tests”func TestAdd(t *testing.T) { tests := []struct { name string a, b int expected int }{ {"positive", 1, 2, 3}, {"zero", 0, 0, 0}, {"negative", -1, 1, 0}, }
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := Add(tt.a, tt.b) if got != tt.expected { t.Errorf("Add(%d, %d) = %d; want %d", tt.a, tt.b, got, tt.expected) } }) }}Setup/Teardown
Section titled “Setup/Teardown”func TestMain(m *testing.M) { setup() code := m.Run() teardown() os.Exit(code)}
func TestWithCleanup(t *testing.T) { f := createTempFile(t) t.Cleanup(func() { os.Remove(f) }) // test using f}cargo test # Run all testscargo test test_name # Run specific testcargo test module:: # Run module testscargo test -- --nocapture # Show println!cargo test -- --test-threads=1 # Serial executioncargo test -- --ignored # Run ignored testscargo test --release # Release modecargo test --doc # Doctest onlycargo test --lib # Library onlycargo test --bins # Binaries onlyTest Module
Section titled “Test Module”#[cfg(test)]mod tests { use super::*;
#[test] fn test_add() { assert_eq!(add(1, 2), 3); }
#[test] #[should_panic(expected = "divide by zero")] fn test_divide_zero() { divide(1, 0); }
#[test] #[ignore] fn expensive_test() { // Only runs with --ignored }
#[test] fn test_result() -> Result<(), String> { if add(1, 2) == 3 { Ok(()) } else { Err("math is broken".into()) } }}Assertions
Section titled “Assertions”assert!(condition);assert_eq!(left, right);assert_ne!(left, right);assert!(result.is_ok());assert!(result.is_err());debug_assert!(condition); // Debug builds onlyCommon Patterns
Section titled “Common Patterns”Watch Mode
Section titled “Watch Mode”# Pythonptw # pytest-watchpytest-watch --onpass "say passed"
# JavaScriptjest --watchvitest
# Rustcargo watch -x testFiltering
Section titled “Filtering”# Run only fast testspytest -m "not slow"jest --testPathIgnorePatterns="e2e"go test -short ./...
# Run only integration testspytest -m integrationjest --testPathPattern="integration"Coverage Thresholds
Section titled “Coverage Thresholds”# Python (pytest-cov)pytest --cov=src --cov-fail-under=80
# JavaScript (jest.config.js)# coverageThreshold: { global: { lines: 80 } }
# Gogo test -coverprofile=c.out && go tool cover -func=c.outCI Commands
Section titled “CI Commands”# Pythonpytest --junitxml=results.xml --cov=src --cov-report=xml
# JavaScriptjest --ci --coverage --reporters=default --reporters=jest-junit
# Gogo test -v -race -coverprofile=coverage.out ./... 2>&1 | go-junit-report > report.xmlSee Also
Section titled “See Also”- Testing Principles — Strategy, pyramid, what to test
- Python — pytest fixtures and assertions
- TypeScript — Type-safe test patterns
- CI/CD
- Debugging Tools
- Performance Profiling
- Python CLI
- Rust
- API Design
- Go Lesson Plan
- Python Lesson Plan
- Rust Lesson Plan
- TypeScript Lesson Plan