/** * 测试设备API和数据导入功能 */ const { Device, Farm } = require('./models'); const express = require('express'); const app = express(); async function testDevicesData() { try { console.log('=== 测试设备数据导入功能 ===\n'); // 1. 检查数据库中的设备数据 console.log('1. 检查数据库中的设备数据:'); const devices = await Device.findAll({ include: [{ model: Farm, as: 'farm', attributes: ['id', 'name', 'location'] }], limit: 10 }); console.log(` - 数据库中共有 ${await Device.count()} 个设备`); console.log(' - 前10个设备信息:'); devices.forEach((device, index) => { console.log(` ${index + 1}. ID: ${device.id}, 名称: ${device.name}, 类型: ${device.type}, 状态: ${device.status}`); if (device.farm) { console.log(` 所属农场: ${device.farm.name}`); } }); // 2. 测试设备API响应格式 console.log('\n2. 测试设备API响应格式:'); const deviceController = require('./controllers/deviceController'); // 模拟API请求 const mockReq = { query: { page: 1, limit: 5 } }; const mockRes = { json: (data) => { console.log(' - API响应格式正确'); console.log(` - 返回设备数量: ${data.data ? data.data.length : 0}`); if (data.data && data.data.length > 0) { console.log(' - 第一个设备数据结构:'); const firstDevice = data.data[0]; console.log(` * ID: ${firstDevice.id}`); console.log(` * 名称: ${firstDevice.name}`); console.log(` * 类型: ${firstDevice.type}`); console.log(` * 状态: ${firstDevice.status}`); console.log(` * 农场: ${firstDevice.farm ? firstDevice.farm.name : '未关联'}`); console.log(` * 安装日期: ${firstDevice.installation_date}`); console.log(` * 最后维护: ${firstDevice.last_maintenance}`); } return data; }, status: (code) => ({ json: (data) => { console.log(` - API返回状态码: ${code}`); if (code !== 200) { console.log(` - 错误信息: ${data.message}`); } return data; } }) }; await deviceController.getAllDevices(mockReq, mockRes); // 3. 检查数据完整性 console.log('\n3. 检查数据完整性:'); const deviceTypes = await Device.findAll({ attributes: ['type'], group: ['type'] }); console.log(' - 设备类型统计:'); for (const deviceType of deviceTypes) { const count = await Device.count({ where: { type: deviceType.type } }); console.log(` * ${deviceType.type}: ${count} 个`); } const statusStats = await Device.findAll({ attributes: ['status'], group: ['status'] }); console.log(' - 设备状态统计:'); for (const status of statusStats) { const count = await Device.count({ where: { status: status.status } }); console.log(` * ${status.status}: ${count} 个`); } console.log('\n=== 设备数据导入功能测试完成 ==='); console.log('✅ 数据库中的设备数据已成功准备好,可以在前端设备管理模块中正常显示'); } catch (error) { console.error('❌ 测试过程中出现错误:', error.message); console.error(error.stack); } } // 运行测试 if (require.main === module) { testDevicesData().then(() => { process.exit(0); }).catch((error) => { console.error('测试失败:', error); process.exit(1); }); } module.exports = { testDevicesData };