我正在尝试使用Mocha,Chai和Superagent编写一些基本的身份验证测试,其中SailsJS和Passport作为身份验证框架。以下是我的测试场景,由于某些原因,我无法保持持久会话,这似乎是我上次测试,看看用户是否有权访问/userplansetting/edit
失败。注意:我已经确认,当我通过网络界面登录时,这是有效的。
更新:这是一个包含类似代码和结果的仓库https://github.com/robksawyer/sailsjs-starter-template
request = require("superagent")
crypto = require("crypto")
async = require("async")
chai = require("chai")
expect = chai.expect
should = chai.should()
assert = chai.assert
userStub = ->
randString = crypto.randomBytes(20).toString("hex")
username: randString.slice(0, 15)
biography: randString + " is a auto generated user!"
email: randString + "@gmail.com"
password: "123123123123"
displayName: "John Doe"
language: "en-us"
describe "Auth", ->
appURL = "http://localhost:1335"
user = undefined
agent1 = request.agent() # sails.hooks.http.app
loginUser = (agent, userObj) ->
(done) ->
onResponse = (err, res) ->
should.not.exist(err)
res.status.should.eql 200
res.text.should.include "Your Campaigns"
done()
agent.post(appURL + "/login")
.send(userObj)
.end onResponse
registerUser = (agent, userObj) ->
(done) ->
onResponse = (err, res) ->
should.not.exist(err)
res.status.should.eql 200
res.text.should.include "Your Campaigns"
done()
agent.post(appURL + "/auth/local/register")
.send(userObj)
.end onResponse
describe "Register User", ->
describe "JSON Requests", ->
describe "POST", ->
it "/auth/local/register should register a user", (done) ->
uStub = userStub()
password = uStub.password
userObj =
email: uStub.email
username: uStub.username
biography: uStub.biography
displayName: uStub.displayName
language: uStub.language
password: password
registerUser(agent1, userObj)
done()
describe "Sign Out Registered User", ->
describe "JSON Requests", ->
describe "GET", ->
agent = request.agent()
it "should start with signin", (done) ->
userObj =
email: global.fixtures.user[0].email
password: global.fixtures.passport[0].password
loginUser(agent, userObj)
done()
it "should sign the user out", (done) ->
agent.get(appURL + "/auth/local/logout")
.end (err, res) ->
if err then done(err)
res.status.should.eql 200
res.redirects.should.eql [ appURL + "/login" ]
done()
it "should destroy the user session", (done) ->
agent.get(appURL + "/plan")
.end (err, res) ->
should.exist(err)
expect(res).to.have.property('error')
res.status.should.eql 403
res.text.should.include 'You are not permitted to perform this action.'
done()
describe "UnAuthenticated", ->
describe "JSON Requests", ->
describe "POST", ->
agent2 = request.agent()
it "/auth/local should login user", (done) ->
userObj =
email: global.fixtures.user[1].email
password: global.fixtures.passport[1].password
loginUser(agent2, userObj)
done()
it "/userplansetting/edit should allow access", (done) ->
# do a seccond request to ensures how user is logged in
agent2.get(appURL + "/userplansetting/edit")
.end (err, res) ->
should.not.exist(err)
sails.log res
res.status.should.eql 200
done()
测试结果
+------------------------------------+
| Running mocha tests |
+------------------------------------+
Debugger listening on port 5858
warn: Lifting sails...
debug: Loading models from /Users/robsawyer/Sites/specs/test/fixtures/models
i18n:debug will write to /Users/robsawyer/Sites/specs/config/locales/en.json +0ms
i18n:debug read /Users/robsawyer/Sites/specs/config/locales/en.json for locale: en +1ms
i18n:debug will write to /Users/robsawyer/Sites/specs/config/locales/es.json +1ms
i18n:debug read /Users/robsawyer/Sites/specs/config/locales/es.json for locale: es +0ms
i18n:debug will write to /Users/robsawyer/Sites/specs/config/locales/fr.json +0ms
i18n:debug read /Users/robsawyer/Sites/specs/config/locales/fr.json for locale: fr +0ms
i18n:debug will write to /Users/robsawyer/Sites/specs/config/locales/de.json +1ms
i18n:debug read /Users/robsawyer/Sites/specs/config/locales/de.json for locale: de +0ms
debug: --------------------------------------------------------
debug: :: Mon Jul 06 2015 10:34:11 GMT-0700 (PDT)
debug: Environment : test/bootstrap.test.*,test
debug: Port : 1335
debug: --------------------------------------------------------
debug: --- Populated the database. ---
Barrels
constructor
✓ should load all the json files from default folder
✓ should set generate lowercase property names for models
populate()
populate(cb)
✓ should populate the DB with users
Auth
Register User
JSON Requests
POST
✓ /auth/local/register should register a user
Sign Out Registered User
JSON Requests
GET
✓ should start with signin
✓ should sign the user out (57ms)
✓ should destroy the user session
UnAuthenticated
JSON Requests
POST
✓ /auth/local should login user
debug: { jar:
{ setCookie: [Function: setCookie],
getCookie: [Function: getCookie],
getCookies: [Function: getCookies] } }
1) /userplansetting/edit should allow access
actions
login
✓ should assume auth method if only one is required
actions
logout
✓ should trigger default logout if params.type is undefined
UserModel
to have
✓ attributes
warn: Lowering sails...
11 passing (4s)
1 failing
1) Auth UnAuthenticated JSON Requests POST /userplansetting/edit should allow access:
Uncaught AssertionError: expected [Error: Forbidden] to not exist
更新:注册模拟用户时,似乎未生成护照记录。因此,当我尝试稍后记录这些用户时,他们没有通过授权墙。
我的注册方法是生成一个空的护照数组。
###
# Handles registering a user based on the user id
###
registerUser: (key, logout) ->
if not logout then logout = true
promise = new RSVP.Promise( (fulfill, reject) ->
if not global.agent
global.agent = request.agent(sails.hooks.http.app)
uStub = userStub()
password = global.fixtures.passport[key].password
userObj =
email: global.fixtures.user[key].email
username: global.fixtures.user[key].username
biography: uStub.biography
displayName: global.fixtures.user[key].displayName
language: uStub.language
password: password
global.agent
.post("/auth/local/register")
.send(userObj)
.redirects(1)
.end( (err, res) ->
if err
sails.log.error err
reject(err)
else
global.agent.saveCookies(res)
if logout
User.findOne({email: userObj.email})
.populate('passports')
.exec(
(err, user) ->
if err then reject(err)
console.log user
sails.log.warn "Registered user " + user.id + " and now logging user out."
# Log the user out
authHelper.logoutUser()
.then(
(res) ->
fulfill(res)
, (err) ->
reject(err)
)
)
else
fulfill(res)
)
)
生成:
[ { passports: [],
username: 'test3',
displayName: 'Test Three',
email: 'test3@test.com',
language: 'en-us',
email_on_end_date: false,
online: false,
admin: false,
createdAt: Tue Jul 07 2015 15:30:02 GMT-0700 (PDT),
updatedAt: Tue Jul 07 2015 15:30:02 GMT-0700 (PDT),
id: 471 } ]
什么时候应该生成:
{ passports:
[ { protocol: 'local',
password: '$2a$10$SVjd6HPwS6k.68E2gAKpC.iS3ibsUZj.n7C3bMkcCRbBoyNJnz8Ru',
accessToken: 'kHTFCeZ7Gd82G1xRSbl6Zm2+FLavt2IJy0qX9mdejD4HAOduzPz+UPa2ovYUfrWC',
provider: null,
identifier: null,
tokens: null,
user: 3,
id: 2,
createdAt: Mon Jul 06 2015 10:29:42 GMT-0700 (PDT),
updatedAt: Mon Jul 06 2015 10:29:42 GMT-0700 (PDT) } ],
planSetting: null,
username: 'test3',
email: 'test3@test.com',
displayName: 'Test Three',
biography: null,
language: 'en-us',
email_on_end_date: false,
online: false,
admin: false,
id: 3,
createdAt: Mon Jul 06 2015 10:29:42 GMT-0700 (PDT),
updatedAt: Mon Jul 06 2015 10:29:42 GMT-0700 (PDT) }
答案 0 :(得分:1)
当您执行需要进行身份验证的请求时,您必须附加Cookie。
it "/userplansetting/edit should allow access", (done) ->
# do a seccond request to ensures how user is logged in
var req = agent2.get(appURL + "/userplansetting/edit");
# set the cookie
agent2.attachCookies(req);
req.end (err, res) ->
should.not.exist(err)
sails.log res
res.status.should.eql 200
done()