Hello fellow developers,
I wrote a RESTful API server, based on node.js and mongoose. While writing the coresponding tests, I had a weird experience of a significant different bevahior between automated testing using chai-http and a manual API test using ARC (advanced REST client, chrome plugin).
My user model (see definitions below) has a "username" field which is unique. When I /POST a new user with an existing username using ARC, I get a E11000 from the mongodb driver, as expected.
When I do the same (at least I think so) using chai-http.request.post, I get a statuscode 200, a SUCCESS result and I have two users with the same username in my test database collection!
User model schema, includes/hooks/export etc. ommited:
const userSchema = new Schema({
admin_info: AdminInfo,
role: { type: String, required: true},
username: { type: String, required: true, unique: true, index: { unique: true } },
password: { type: String, required: true },
firstname: String,
lastname: String,
mail: String,
});
generic route handler function for POST /users, where "model" is an instance of the above user schema:
function addEntry(req, res, next, model) {
var entry = new model(req.body);
entry.save((err, obj) => {
if(err) {
res.status(500).json({'ERROR': err});
} else {
res.json({'SUCCESS': obj});
}
});
}
chai test case which yields a status code 200 and an SUCCESSful insert (NOT as expected!):
describe('Users API', () => {
beforeEach((done) => {
var user = createUser();
user.save((err) => {
if (err) {
console.error(err);
}
done();
})
});
afterEach((done) => {
User.collection.drop();
done();
});
...
it('should NOT add a SINGLE user if the username already exists on /users POST' , (done) => {
var user = new User({
admin_info: {
author: 'NEC'
},
role: 'mod',
username: 'Lycidas',
password: 'abcd'
});
chai.request(server)
.post('/users')
.send(user)
.end((err, res) => {
console.log(res.body);
res.should.have.status(500);
res.should.be.json;
res.body.should.be.a('object');
res.body.should.have.property('ERROR');
done();
});
});
same chai test case log ouput with a GET /users after the POST request:
[
{
"_id": 689,
"role": "admin",
"username": "Lycidas",
"password": "$2a$10$RmDbg4rvtP147i6Rt2C9.Okx1pZ96cIWUoNW/TxzrD4UbZIHvJRw.",
"__v": 0,
"admin_info": {
"modified_at": "2017-08-07T08:42:10.355Z",
"author": "NEC",
"created_at": "2017-08-07T08:42:10.355Z"
}
},
{
"_id": 690,
"role": "mod",
"username": "Lycidas",
"password": "$2a$10$O1yrYmO42lLyW8nOyqlnauJSGJB/3MLp0mHrDISWMh1AgNAViuzB.",
"__v": 0,
"admin_info": {
"modified_at": "2017-08-07T08:42:10.453Z",
"author": "NEC",
"created_at": "2017-08-07T08:42:10.448Z"
}
}
]
As you can see, the 2nd user has an existing username but gets added without an error. Any ideas? Is my test case wrong, and my API working it should? Or did I create a - potentially dangerous - bug in my server? I have the same (different) behavior for PUT /users/, too.
Any help will be kindly appreciated, Lycidas
Aucun commentaire:
Enregistrer un commentaire