service/main_test.js

73 lines
2.3 KiB
JavaScript
Raw Permalink 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.

import http from 'http'
import u from 'util'
import file from 'file'
let bakDB = false
// 用于测试的http客户端设置默认URL前缀方便后续调用
let hc = http.new({ baseURL: 'http://localhost:8080', timeout: 1000 })
// 测试开始前,启动服务
function onStart() {
// 备份数据库文件
bakDB = file.exists('user.db')
if (bakDB) file.rename('user.db', 'user.db.bak')
// 启动服务
u.shell(__startExec, 'start')
// 等待服务启动
u.sleep(100)
}
// 测试结束后,停止服务
function onStop() {
// 停止服务
u.shell(__startExec, 'stop')
// 恢复数据库文件
file.remove('user.db')
if (bakDB) file.rename('user.db.bak', 'user.db')
}
function testNotLoggedIn() {
// 未登录应该返回403
let r = hc.get('/userInfo')
return r.statusCode === 403 || r.status + ' ' + r.string()
}
function testBadUserId() {
// 注册时传入错误的用户ID应该返回400
let r = hc.post('/register', { id: 'test.User', password: u.hex(u.sha256('123456')), name: '测试用户' })
return r.statusCode === 400 || r.status + ' ' + r.string()
}
function testRegister() {
// 注册一个新用户code应该返回1
let r = hc.post('/register', { id: 'testUser', password: u.hex(u.sha256('123456')), name: '测试用户' })
if (r.statusCode !== 200) return r.status + ' ' + r.string()
let o = r.object()
return o.code === 1 || o
}
function testLoginWithBadPassword() {
// 登录时传入错误的密码code应该返回401
let r = hc.post('/login', { id: 'testUser', password: u.hex(u.sha256('1234567')) })
if (r.statusCode !== 200) return r.status + ' ' + r.string()
let o = r.object()
return o.code === 401 || o
}
function testLogin() {
// 登录code应该返回1
let r = hc.post('/login', { id: 'testUser', password: u.hex(u.sha256('123456')) })
if (r.statusCode !== 200) return r.status + ' ' + r.string()
let o = r.object()
return o.code === 1 || o
}
function testGetUserInfo() {
// 获取用户信息code应该返回1id和name应该正确
let r = hc.get('/userInfo')
if (r.statusCode !== 200) return r.status + ' ' + r.string()
let o = r.object()
return o.code === 1 && o.data.id === 'testUser' && o.data.name === '测试用户' || o
}