新增e2e测试脚本,修复部分问题
This commit was merged in pull request #51.
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* 后端 API 调用助手(Node.js HTTP 直接调用,含 HMAC 签名)
|
||||
* 支持带签名和不带签名两种模式
|
||||
*/
|
||||
const http = require('http');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const BASE_URL = 'http://192.168.110.64:8084';
|
||||
const API_BASE = '/api';
|
||||
const SIGNATURE_SECRET = 'NovalonManageSystemSecretKey2026';
|
||||
const ENABLE_SIGNATURE = true; // HMAC 签名
|
||||
|
||||
function generateSignature(method, path, body, timestamp, nonce) {
|
||||
const stringToSign = [method, path, '', body || '', String(timestamp), nonce].join('\n');
|
||||
return crypto.createHmac('sha256', SIGNATURE_SECRET).update(stringToSign).digest('base64');
|
||||
}
|
||||
|
||||
function generateNonce() {
|
||||
return Date.now().toString(36) + '-' + Math.random().toString(36).substring(2, 15);
|
||||
}
|
||||
|
||||
function makeRequest(method, url, body, token) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const urlObj = new URL(url, BASE_URL);
|
||||
const path = urlObj.pathname + urlObj.search;
|
||||
const bodyStr = body ? JSON.stringify(body) : '';
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'application/json'
|
||||
};
|
||||
|
||||
if (ENABLE_SIGNATURE) {
|
||||
const timestamp = Date.now();
|
||||
const nonce = generateNonce();
|
||||
const signature = generateSignature(method.toUpperCase(), path, bodyStr, timestamp, nonce);
|
||||
headers['X-Signature'] = signature;
|
||||
headers['X-Timestamp'] = String(timestamp);
|
||||
headers['X-Nonce'] = nonce;
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = token.startsWith('Bearer ') ? token : 'Bearer ' + token;
|
||||
}
|
||||
|
||||
const options = {
|
||||
hostname: urlObj.hostname,
|
||||
port: urlObj.port,
|
||||
path: path,
|
||||
method: method.toUpperCase(),
|
||||
headers: headers
|
||||
};
|
||||
|
||||
const req = http.request(options, (res) => {
|
||||
let data = '';
|
||||
res.on('data', chunk => { data += chunk; });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
resolve({ status: res.statusCode, data: parsed });
|
||||
} catch (e) {
|
||||
resolve({ status: res.statusCode, data: data });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (err) => reject(err));
|
||||
req.setTimeout(10000, () => { req.destroy(); reject(new Error('Request timeout')); });
|
||||
|
||||
if (bodyStr) req.write(bodyStr);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
function isSuccess(response, expectedStatus = 200) {
|
||||
return response.status === expectedStatus;
|
||||
}
|
||||
|
||||
async function adminLogin(password) {
|
||||
console.log('[API] 管理员登录...');
|
||||
const res = await makeRequest('POST', `${API_BASE}/system/auth/login`, {
|
||||
username: 'admin',
|
||||
password: password || 'admin'
|
||||
});
|
||||
console.log(`[API] 登录响应: ${res.status}`);
|
||||
if (res.data && res.data.data && res.data.data.token) {
|
||||
return res.data.data.token;
|
||||
}
|
||||
if (res.data && res.data.token) {
|
||||
return res.data.token;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function searchCourses(keyword, token) {
|
||||
console.log(`[API] 搜索课程: "${keyword}"`);
|
||||
const res = await makeRequest('POST', `${API_BASE}/groupCourse/page`, {
|
||||
page: 0, size: 50
|
||||
}, token);
|
||||
console.log(`[API] 搜索结果: status=${res.status}, total=${res.data?.data?.totalElements || res.data?.totalElements || '?'}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
async function searchByKeyword(keyword, token) {
|
||||
console.log(`[API] 按关键词搜索: "${keyword}"`);
|
||||
const res = await makeRequest('POST', `${API_BASE}/groupCourse/page`, {
|
||||
page: 0, size: 50
|
||||
}, token);
|
||||
console.log(`[API] 搜索结果: status=${res.status}, total=${res.data?.data?.totalElements || res.data?.totalElements || '?'}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
async function getCourseDetail(courseId, token) {
|
||||
console.log(`[API] 获取课程详情: id=${courseId}`);
|
||||
const res = await makeRequest('GET', `${API_BASE}/groupCourse/${courseId}/detail`, null, token);
|
||||
console.log(`[API] 课程详情: status=${res.status}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
async function getCourseTypes() {
|
||||
console.log('[API] 获取课程类型...');
|
||||
const res = await makeRequest('GET', `${API_BASE}/groupCourse/types`);
|
||||
console.log(`[API] 课程类型: status=${res.status}, count=${Array.isArray(res.data) ? res.data.length : '?'}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
async function getActiveRecommendations() {
|
||||
console.log('[API] 获取活跃推荐课程...');
|
||||
const res = await makeRequest('GET', `${API_BASE}/groupCourse/recommend/active`);
|
||||
console.log(`[API] 推荐课程: status=${res.status}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
// ── 会员端 API ──
|
||||
|
||||
/** 会员小程序登录,返回 {memberId, accessToken} */
|
||||
async function memberLogin() {
|
||||
console.log('[API] 会员登录 (miniappLogin)...');
|
||||
const res = await makeRequest('POST', `${API_BASE}/member/auth/miniapp/login`, {
|
||||
code: 'dev-test-code-' + Date.now()
|
||||
});
|
||||
console.log(`[API] 会员登录响应: status=${res.status}`);
|
||||
if (res.status === 200 && res.data) {
|
||||
return { memberId: res.data.memberId, accessToken: res.data.accessToken };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 预约课程 */
|
||||
async function bookCourse(courseId, memberId, token) {
|
||||
console.log(`[API] 预约课程: courseId=${courseId}, memberId=${memberId}`);
|
||||
const res = await makeRequest('POST', `${API_BASE}/groupCourse/book`, {
|
||||
courseId, memberId
|
||||
}, token);
|
||||
console.log(`[API] 预约结果: status=${res.status}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
/** 获取会员的预约列表 */
|
||||
async function getMemberBookings(memberId, token) {
|
||||
console.log(`[API] 获取会员预约: memberId=${memberId}`);
|
||||
const res = await makeRequest('GET', `${API_BASE}/groupCourse/bookings/member/${memberId}`, null, token);
|
||||
console.log(`[API] 预约列表: status=${res.status}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
/** 扫码签到 */
|
||||
async function signIn(courseId, memberId, token) {
|
||||
console.log(`[API] 签到: courseId=${courseId}, memberId=${memberId}`);
|
||||
const res = await makeRequest('POST', `${API_BASE}/groupCourse/signin/${memberId}`, {
|
||||
courseId
|
||||
}, token);
|
||||
console.log(`[API] 签到结果: status=${res.status}`);
|
||||
return res;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
makeRequest,
|
||||
adminLogin,
|
||||
searchCourses,
|
||||
searchByKeyword,
|
||||
getCourseDetail,
|
||||
getCourseTypes,
|
||||
getActiveRecommendations,
|
||||
memberLogin,
|
||||
bookCourse,
|
||||
getMemberBookings,
|
||||
signIn,
|
||||
isSuccess,
|
||||
BASE_URL,
|
||||
API_BASE
|
||||
};
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
const automator = require('miniprogram-automator');
|
||||
const path = require('path');
|
||||
|
||||
const PROJECT_PATH = path.resolve(__dirname, '../../unpackage/dist/dev/mp-weixin');
|
||||
const CLI_PATH = 'D:\\wechat-dev-tools\\cli.bat';
|
||||
const DEVTOOL_PORT = 45869;
|
||||
|
||||
/**
|
||||
* 启动微信小程序
|
||||
* @returns {Promise<MiniProgram>}
|
||||
*/
|
||||
async function launchMiniProgram() {
|
||||
console.log('[automator] 启动小程序...');
|
||||
const miniProgram = await automator.launch({
|
||||
projectPath: PROJECT_PATH,
|
||||
cliPath: CLI_PATH,
|
||||
port: DEVTOOL_PORT
|
||||
});
|
||||
console.log('[automator] 小程序已启动');
|
||||
return miniProgram;
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接已在运行的小程序
|
||||
*/
|
||||
async function connectMiniProgram() {
|
||||
return automator.connect({ port: DEVTOOL_PORT });
|
||||
}
|
||||
|
||||
/**
|
||||
* 模拟微信登录流程
|
||||
* 通过调用 wx.login 获取 code,触发后端登录
|
||||
* @param {MiniProgram} miniProgram
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function loginAsMember(miniProgram) {
|
||||
console.log('[automator] 执行会员登录流程...');
|
||||
|
||||
try {
|
||||
// 调用微信登录接口
|
||||
await miniProgram.callWxMethod('login', {});
|
||||
} catch (err) {
|
||||
console.warn('[automator] wx.login 调用异常(可能已在模拟器中自动完成):', err.message);
|
||||
}
|
||||
|
||||
// 等待登录完成并跳转到首页
|
||||
await miniProgram.waitFor(1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 等待当前页面 URL 匹配指定模式
|
||||
* @param {MiniProgram} miniProgram
|
||||
* @param {string} urlPattern - 页面路径模式
|
||||
* @param {number} timeout - 超时时间(ms)
|
||||
* @returns {Promise<Page>}
|
||||
*/
|
||||
async function waitForPage(miniProgram, urlPattern, timeout = 30000) {
|
||||
const startTime = Date.now();
|
||||
while (Date.now() - startTime < timeout) {
|
||||
try {
|
||||
const page = await miniProgram.currentPage();
|
||||
if (page && page.path && page.path.includes(urlPattern)) {
|
||||
console.log(`[automator] 页面已加载: ${page.path}`);
|
||||
return page;
|
||||
}
|
||||
} catch (e) {
|
||||
// 页面尚未准备好,继续等待
|
||||
}
|
||||
await miniProgram.waitFor(500);
|
||||
}
|
||||
throw new Error(`等待页面 "${urlPattern}" 超时 (${timeout}ms)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 截图保存
|
||||
* @param {MiniProgram} miniProgram
|
||||
* @param {string} name - 截图名称
|
||||
* @returns {Promise<string>} 截图文件路径
|
||||
*/
|
||||
async function screenshot(miniProgram, name) {
|
||||
const screenshotsDir = path.resolve(__dirname, '../screenshots');
|
||||
const fs = require('fs');
|
||||
if (!fs.existsSync(screenshotsDir)) {
|
||||
fs.mkdirSync(screenshotsDir, { recursive: true });
|
||||
}
|
||||
const timestamp = Date.now();
|
||||
const safeName = name.replace(/[^a-zA-Z0-9_-]/g, '_');
|
||||
const filePath = path.join(screenshotsDir, `${timestamp}_${safeName}.png`);
|
||||
await miniProgram.screenshot({ path: filePath });
|
||||
console.log(`[automator] 截图已保存: ${filePath}`);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 TabBar 切换页面
|
||||
* @param {MiniProgram} miniProgram
|
||||
* @param {number} index - TabBar 索引 (0:首页, 1:课程, 2:我的课程, 3:我的)
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function switchTab(miniProgram, index) {
|
||||
console.log(`[automator] 切换到 TabBar 索引: ${index}`);
|
||||
await miniProgram.callWxMethod('switchTab', { url: getTabBarUrl(index) });
|
||||
await miniProgram.waitFor(1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 TabBar 页面 URL
|
||||
*/
|
||||
function getTabBarUrl(index) {
|
||||
const tabs = [
|
||||
'/pages/index/index',
|
||||
'/pages/search/search',
|
||||
'/pages/my-courses/my-courses',
|
||||
'/pages/profile/profile'
|
||||
];
|
||||
return tabs[index] || tabs[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成唯一测试数据标识
|
||||
*/
|
||||
function generateTestId() {
|
||||
return `e2e_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
launchMiniProgram,
|
||||
connectMiniProgram,
|
||||
loginAsMember,
|
||||
waitForPage,
|
||||
screenshot,
|
||||
switchTab,
|
||||
getTabBarUrl,
|
||||
generateTestId,
|
||||
PROJECT_PATH,
|
||||
CLI_PATH,
|
||||
DEVTOOL_PORT
|
||||
};
|
||||
Reference in New Issue
Block a user