跳转到内容
搜索文档

自动化测试流水线

最后更新 查看 MarkdownAgent 设置

构建测试流水线:克隆 Git 仓库、安装依赖、运行测试并报告结果。

预计完成时间:25 分钟

前提条件

  1. 注册 Cloudflare 账户
  2. 安装 Node.js

Node.js 版本管理器

使用 Voltanvm 等 Node 版本管理器,以避免权限问题并切换 Node.js 版本。本指南后续将介绍的 Wrangler 需要 Node 版本 16.17.0 或更高。

你还需要一个带测试的 GitHub 仓库(公开仓库,或带访问令牌的私有仓库)。

1. 创建项目

npm create cloudflare@latest -- test-pipeline --template=cloudflare/sandbox-sdk/examples/minimal
cd test-pipeline

2. 构建流水线

替换 src/index.ts

import { getSandbox, proxyToSandbox, parseSSEStream, type Sandbox, type ExecEvent } from '@cloudflare/sandbox';

export { Sandbox } from '@cloudflare/sandbox';

interface Env {
	Sandbox: DurableObjectNamespace<Sandbox>;
	GITHUB_TOKEN?: string;
}

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const proxyResponse = await proxyToSandbox(request, env);
		if (proxyResponse) return proxyResponse;

		if (request.method !== 'POST') {
			return new Response('POST { "repoUrl": "https://github.com/owner/repo", "branch": "main" }');
		}

		try {
			const { repoUrl, branch } = await request.json();

			if (!repoUrl) {
				return Response.json({ error: 'repoUrl required' }, { status: 400 });
			}

			const sandbox = getSandbox(env.Sandbox, `test-${Date.now()}`);

			try {
				// Clone repository
				console.log('Cloning repository...');
				let cloneUrl = repoUrl;
				
				if (env.GITHUB_TOKEN && cloneUrl.includes('github.com')) {
					cloneUrl = cloneUrl.replace('https://', `https://${env.GITHUB_TOKEN}@`);
				}

				await sandbox.gitCheckout(cloneUrl, {
					...(branch && { branch }),
					depth: 1,
					targetDir: 'repo'
				});
				console.log('Repository cloned');

				// Detect project type
				const projectType = await detectProjectType(sandbox);
				console.log(`Detected ${projectType} project`);

				// Install dependencies
				const installCmd = getInstallCommand(projectType);
				if (installCmd) {
					console.log('Installing dependencies...');
					const installStream = await sandbox.execStream(`cd /workspace/repo && ${installCmd}`);
					
					let installExitCode = 0;
					for await (const event of parseSSEStream<ExecEvent>(installStream)) {
						if (event.type === 'stdout' || event.type === 'stderr') {
							console.log(event.data);
						} else if (event.type === 'complete') {
							installExitCode = event.exitCode;
						}
					}
					
					if (installExitCode !== 0) {
						return Response.json({
							success: false,
							error: 'Install failed',
							exitCode: installExitCode
						});
					}
					console.log('Dependencies installed');
				}

				// Run tests
				console.log('Running tests...');
				const testCmd = getTestCommand(projectType);
				const testStream = await sandbox.execStream(`cd /workspace/repo && ${testCmd}`);
				
				let testExitCode = 0;
				for await (const event of parseSSEStream<ExecEvent>(testStream)) {
					if (event.type === 'stdout' || event.type === 'stderr') {
						console.log(event.data);
					} else if (event.type === 'complete') {
						testExitCode = event.exitCode;
					}
				}
				console.log(`Tests completed with exit code ${testExitCode}`);

				return Response.json({
					success: testExitCode === 0,
					exitCode: testExitCode,
					projectType,
					message: testExitCode === 0 ? 'All tests passed' : 'Tests failed'
				});

			} finally {
				await sandbox.destroy();
			}

		} catch (error: any) {
			return Response.json({ error: error.message }, { status: 500 });
		}
	},
};

async function detectProjectType(sandbox: any): Promise<string> {
	try {
		await sandbox.readFile('/workspace/repo/package.json');
		return 'nodejs';
	} catch {}

	try {
		await sandbox.readFile('/workspace/repo/requirements.txt');
		return 'python';
	} catch {}

	try {
		await sandbox.readFile('/workspace/repo/go.mod');
		return 'go';
	} catch {}

	return 'unknown';
}

function getInstallCommand(projectType: string): string {
	switch (projectType) {
		case 'nodejs': return 'npm install';
		case 'python': return 'pip install -r requirements.txt || pip install -e .';
		case 'go': return 'go mod download';
		default: return '';
	}
}

function getTestCommand(projectType: string): string {
	switch (projectType) {
		case 'nodejs': return 'npm test';
		case 'python': return 'python -m pytest || python -m unittest discover';
		case 'go': return 'go test ./...';
		default: return 'echo "Unknown project type"';
	}
}

3. 本地测试

启动开发服务器:

npm run dev

使用仓库进行测试:

curl -X POST http://localhost:8787 \
  -H "Content-Type: application/json" \
  -d '{
    "repoUrl": "https://github.com/cloudflare/sandbox-sdk"
  }'

你会在 wrangler 控制台中看到进度日志,并收到 JSON 响应:

{
  "success": true,
  "exitCode": 0,
  "projectType": "nodejs",
  "message": "All tests passed"
}

4. 部署

npx wrangler deploy

对于私有仓库,设置 GitHub 令牌:

npx wrangler secret put GITHUB_TOKEN

你构建了什么

一条自动化测试流水线,它能够:

  • 克隆 Git 仓库
  • 检测项目类型(Node.js、Python、Go)
  • 自动安装依赖
  • 运行测试并报告结果

后续步骤

这篇文档对您有帮助吗?