返回顶部
t

test-patterns测试模式

Write and run tests across languages and frameworks. Use when setting up test suites, writing unit/integration/E2E tests, measuring coverage, mocking dependencies, or debugging test failures. Covers Node.js (Jest/Vitest), Python (pytest), Go, Rust, and Bash.

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 1.0.0
安全检测
已通过
3,228
下载量
免费
免费
1
收藏
概述
安装方式
版本历史

test-patterns

测试模式

跨语言编写、运行和调试测试。涵盖单元测试、集成测试、端到端测试、模拟、覆盖率以及测试驱动开发工作流。

使用场景

  • - 为新项目搭建测试套件
  • 为函数或模块编写单元测试
  • 为API或数据库交互编写集成测试
  • 设置代码覆盖率测量
  • 模拟外部依赖(API、数据库、文件系统)
  • 调试不稳定或失败的测试
  • 实施测试驱动开发

Node.js (Jest / Vitest)

安装

bash

Jest


npm install -D jest

添加到 package.json: scripts: { test: jest }

Vitest(更快,原生支持ESM)

npm install -D vitest

添加到 package.json: scripts: { test: vitest }

单元测试

javascript
// math.js
export function add(a, b) { return a + b; }
export function divide(a, b) {
if (b === 0) throw new Error(Division by zero);
return a / b;
}

// math.test.js
import { add, divide } from ./math.js;

describe(add, () => {
test(两个正数相加, () => {
expect(add(2, 3)).toBe(5);
});

test(处理负数, () => {
expect(add(-1, 1)).toBe(0);
});

test(处理零, () => {
expect(add(0, 0)).toBe(0);
});
});

describe(divide, () => {
test(两个数相除, () => {
expect(divide(10, 2)).toBe(5);
});

test(除以零抛出异常, () => {
expect(() => divide(10, 0)).toThrow(Division by zero);
});

test(处理浮点数, () => {
expect(divide(1, 3)).toBeCloseTo(0.333, 3);
});
});

异步测试

javascript
// api.test.js
import { fetchUser } from ./api.js;

test(根据ID获取用户, async () => {
const user = await fetchUser(123);
expect(user).toHaveProperty(id, 123);
expect(user).toHaveProperty(name);
expect(user.name).toBeTruthy();
});

test(用户不存在时抛出异常, async () => {
await expect(fetchUser(nonexistent)).rejects.toThrow(Not found);
});

模拟

javascript
// 模拟模块
jest.mock(./database.js);
import { getUser } from ./database.js;
import { processUser } from ./service.js;

test(从数据库处理用户, async () => {
// 设置模拟返回值
getUser.mockResolvedValue({ id: 1, name: Alice, active: true });

const result = await processUser(1);
expect(result.processed).toBe(true);
expect(getUser).toHaveBeenCalledWith(1);
expect(getUser).toHaveBeenCalledTimes(1);
});

// 模拟fetch
global.fetch = jest.fn();

test(使用正确参数调用API, async () => {
fetch.mockResolvedValue({
ok: true,
json: async () => ({ data: test }),
});

const result = await myApiCall(/endpoint);
expect(fetch).toHaveBeenCalledWith(/endpoint, expect.objectContaining({
method: GET,
}));
});

// 监视现有方法(不替换,仅观察)
const consoleSpy = jest.spyOn(console, log).mockImplementation();
// ... 运行代码 ...
expect(consoleSpy).toHaveBeenCalledWith(expected message);
consoleSpy.mockRestore();

覆盖率

bash

Jest


npx jest --coverage

Vitest

npx vitest --coverage

检查覆盖率阈值(jest.config.js)

coverageThreshold: { global: { branches: 80, functions: 80, lines: 80, statements: 80 } }

Python (pytest)

安装

bash
pip install pytest pytest-cov

单元测试

python

calculator.py


def add(a, b):
return a + b

def divide(a, b):
if b == 0:
raise ValueError(Division by zero)
return a / b

test_calculator.py

import pytest from calculator import add, divide

def test_add():
assert add(2, 3) == 5

def testaddnegative():
assert add(-1, 1) == 0

def test_divide():
assert divide(10, 2) == 5.0

def testdivideby_zero():
with pytest.raises(ValueError, match=Division by zero):
divide(10, 0)

def testdividefloat():
assert divide(1, 3) == pytest.approx(0.333, abs=0.001)

参数化测试

python
@pytest.mark.parametrize(a,b,expected, [
(2, 3, 5),
(-1, 1, 0),
(0, 0, 0),
(100, -50, 50),
])
def testaddcases(a, b, expected):
assert add(a, b) == expected

夹具

python
import pytest
import json
import tempfile
import os

@pytest.fixture
def sample_users():
提供测试用户数据。
return [
{id: 1, name: Alice, email: alice@test.com},
{id: 2, name: Bob, email: bob@test.com},
]

@pytest.fixture
def tempdb(tmppath):
提供临时SQLite数据库。
import sqlite3
dbpath = tmppath / test.db
conn = sqlite3.connect(str(db_path))
conn.execute(CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT))
conn.commit()
yield conn
conn.close()

def testinsertusers(tempdb, sampleusers):
for user in sample_users:
temp_db.execute(INSERT INTO users VALUES (?, ?, ?),
(user[id], user[name], user[email]))
temp_db.commit()
count = temp_db.execute(SELECT COUNT(*) FROM users).fetchone()[0]
assert count == 2

带清理的夹具

@pytest.fixture def tempconfigfile(): path = tempfile.mktemp(suffix=.json) with open(path, w) as f: json.dump({key: value}, f) yield path os.unlink(path)

模拟

python
from unittest.mock import patch, MagicMock, AsyncMock

模拟函数

@patch(mymodule.requests.get) def testfetchdata(mock_get): mockget.returnvalue.status_code = 200 mockget.returnvalue.json.return_value = {data: test}

result = fetch_data(https://api.example.com)
assert result == {data: test}
mockget.assertcalledoncewith(https://api.example.com)

模拟异步

@patch(mymodule.aiohttp.ClientSession.get, new_callable=AsyncMock) async def testasyncfetch(mock_get): mockget.returnvalue.aenter.returnvalue.json = AsyncMock(returnvalue={ok: True}) result = await async_fetch(/endpoint) assert result[ok] is True

上下文管理器模拟

def testfilereader(): with patch(builtins.open, MagicMock(return_value=MagicMock( read=MagicMock(return_value={key: val}), enter=MagicMock(returnvalue=MagicMock(read=MagicMock(returnvalue={key: val}))), exit=MagicMock(return_value=False), ))): result = read_config(fake.json) assert result[key] == val

覆盖率

bash

运行覆盖率


pytest --cov=mypackage --cov-report=term-missing

HTML报告

pytest --cov=mypackage --cov-report=html

打开 htmlcov/index.html

覆盖率低于阈值则失败

pytest --cov=mypackage --cov-fail-under=80

Go

单元测试

go
// math.go
package math

import errors

func Add(a, b int) int { return a + b }

func Divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New(division by zero)
}
return a / b, nil
}

// math_test.go
package math

import (
testing
math
)

func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 test-patterns-1776366253 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 test-patterns-1776366253 技能

通过命令行安装

skillhub install test-patterns-1776366253

下载

⬇ 下载 test-patterns v1.0.0(免费)

文件大小: 5.96 KB | 发布时间: 2026-4-17 14:16

v1.0.0 最新 2026-4-17 14:16
Initial release: Testing across Node.js, Python, Go, Rust, Bash - unit tests, mocking, fixtures, coverage, TDD, integration testing

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部