Files
vue-driven-cloud-storage/backend/test_download_quota_defaults.js
2026-06-13 18:45:12 +08:00

106 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const fs = require('fs');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'wanwanyun-download-quota-'));
const tempDbPath = path.join(tempDir, 'database.db');
process.env.DATABASE_PATH = tempDbPath;
process.env.ENCRYPTION_KEY = crypto.randomBytes(32).toString('hex');
process.env.JWT_SECRET = crypto.randomBytes(32).toString('hex');
process.env.REFRESH_SECRET = crypto.randomBytes(32).toString('hex');
process.env.WAL_CHECKPOINT_ENABLED = 'false';
let db;
try {
const { db: loadedDb, UserDB } = require('./database');
const { authMiddleware, generateToken } = require('./auth');
db = loadedDb;
const adminUser = UserDB.findByUsername(process.env.ADMIN_USERNAME || 'admin');
assert(adminUser, '应自动创建默认管理员账号');
assert(
Number(adminUser.download_traffic_quota) === -1,
`默认管理员下载配额应为 -1实际: ${adminUser.download_traffic_quota}`
);
const username = `quota_test_${Date.now()}`;
const userId = UserDB.create({
username,
email: `${username}@example.com`,
password: 'secret123',
is_verified: 1
});
const createdUser = UserDB.findById(userId);
assert(createdUser, '新用户应创建成功');
assert(
Number(createdUser.download_traffic_quota) === -1,
`新用户默认下载配额应为 -1实际: ${createdUser.download_traffic_quota}`
);
const token = generateToken(createdUser);
const req = {
headers: {
authorization: `Bearer ${token}`
},
cookies: {},
ip: '127.0.0.1',
socket: {
remoteAddress: '127.0.0.1'
},
get() {
return 'quota-test-agent';
}
};
let nextCalled = false;
const res = {
statusCode: 200,
payload: null,
status(code) {
this.statusCode = code;
return this;
},
json(body) {
this.payload = body;
return this;
}
};
authMiddleware(req, res, () => {
nextCalled = true;
});
assert(nextCalled, `authMiddleware 应放行不限流量用户,实际状态码: ${res.statusCode}`);
assert(req.user, 'authMiddleware 应写入 req.user');
assert(
Number(req.user.download_traffic_quota) === -1,
`authMiddleware 中的下载配额应保留 -1实际: ${req.user.download_traffic_quota}`
);
console.log('PASS test_download_quota_defaults');
process.exit(0);
} catch (error) {
console.error('FAIL test_download_quota_defaults');
console.error(error && error.stack ? error.stack : error);
process.exit(1);
} finally {
if (db) {
try {
db.close();
} catch (closeError) {
console.error('关闭测试数据库失败:', closeError.message);
}
}
}