Skip to content

Commit

Permalink
test: validator unit test (#157)
Browse files Browse the repository at this point in the history
* test: validator unit test

* fix: instance of RegExp

* test: pattern type
  • Loading branch information
JimmyDaddy authored Aug 11, 2021
1 parent dd30c4b commit b77da6b
Show file tree
Hide file tree
Showing 2 changed files with 162 additions and 25 deletions.
40 changes: 21 additions & 19 deletions src/validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ class LeoricValidateError extends Error {
}
}

function regex(str, pattern, modifiers) {
str += '';
if (typeof pattern === 'string') {
pattern = new RegExp(pattern, modifiers);
}
const result = str.match(pattern);
return result ? result.length > 0 : false;
}

const validators = {
...Validator,
notIn(str, values) {
Expand All @@ -35,21 +44,14 @@ const validators = {
return !!elem && str.includes(elem);
},
notContains(str, elem) {
return !this.contains(str, elem);
},
regex(str, pattern, modifiers) {
str += '';
if (Object.prototype.toString.call(pattern).slice(8, -1) !== 'RegExp') {
pattern = new RegExp(pattern, modifiers);
}
const result = str.match(pattern);
return result ? result.length > 0 : false;
return !Validator.contains(str, elem);
},
regex,
notRegex(str, pattern, modifiers) {
return !this.regex(str, pattern, modifiers);
return !regex(str, pattern, modifiers);
},
is(str, pattern, modifiers) {
return this.regex(str, pattern, modifiers);
return regex(str, pattern, modifiers);
},
notEmpty(str) {
return /[^\s]/.test(str);
Expand All @@ -74,29 +76,29 @@ function executeValidator(ctx, name, attribute, setValue) {
// custom validator
try {
// Make sure this[name] callable and not return undefined or previous value (instance only) during validator executing while updating or saving
if (ctx.raw) {
if (ctx.getRaw) {
needToRevert = true;
originValue = ctx.raw[field];
ctx.raw[field] = value;
originValue = ctx.getRaw(field);
ctx._setRaw(field, value);
}
const execRes = validateArgs.call(ctx, value);
if (execRes === false) throw new LeoricValidateError(name, field);
} catch (err) {
// revert value (instance only)
if (ctx.raw && needToRevert) ctx.raw[field] = originValue;
if (ctx.getRaw && needToRevert) ctx._setRaw(field, originValue);
err.name = ERR_NAME;
throw err;
}
// revert value (instance only)
if (ctx.raw && needToRevert) ctx.raw[field] = originValue;
if (ctx.getRaw && needToRevert) ctx._setRaw(field, originValue);
} else {
const validator = validators[name];
if (typeof validator !== 'function') throw new LeoricValidateError(`Invalid validator function: ${name}`);
let args = validateArgs;
let msg;
if (isPlainObject(validateArgs)) {
if ('args' in validateArgs) args = validateArgs.args;
msg = validateArgs.msg || msg;
msg = validateArgs.msg;
}

if (['true', 'false'].indexOf(String(validateArgs)) >= 0) {
Expand All @@ -105,8 +107,8 @@ function executeValidator(ctx, name, attribute, setValue) {
}
return;
}
let callableArgs = [ String(value) ];
callableArgs = callableArgs.concat(args);
const callableArgs = [ String(value) ];
callableArgs.push(args);
if (!validator.apply(ctx, callableArgs)) throw new LeoricValidateError(name, field, msg);
}
}
Expand Down
147 changes: 141 additions & 6 deletions test/unit/validator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,16 @@ describe('validator', () => {
unique: true,
validate: {
isEmail: true,
is: '\\w+(@e.com)\\w{0}',
}
},
nickname: {
type: DataTypes.STRING(256),
allowNull: false,
validate: {
isNumeric: false,
notIn: [ 'Yhorm', 'Gwyn' ],
notContains: 'closePease',
}
},
meta: {
Expand All @@ -46,6 +49,7 @@ describe('validator', () => {
type: DataTypes.STRING,
validate: {
notNull: true,
notEmpty: true,
isValid() {
if (this.desc && this.desc.length < 2) {
throw new Error('Invalid desc');
Expand All @@ -55,13 +59,16 @@ describe('validator', () => {
if (value && value.length >= 10) {
return false;
}
}
},
regex: /^\d{3}\w+/g,
}
},
fingerprint: {
type: DataTypes.TEXT,
validate: {
contains: 'finger',
notRegex: /^\d{3}\w+/g,
is: /\w+\d{2}$/g
}
}
};
Expand Down Expand Up @@ -97,6 +104,21 @@ describe('validator', () => {
}, /Validation isEmail on email failed/);
});

it('is** true', async () => {
await assert.rejects(async () => {
await User.create({
email: 'sss@e.cn',
nickname: 's',
});
}, /Validation is on email failed/);

await User.create({
email: 'sss@e.com',
nickname: 's',
});
});


it('is** false', async () => {
await assert.rejects(async () => {
await User.create({
Expand Down Expand Up @@ -135,6 +157,95 @@ describe('validator', () => {
}, /Validation notNull on desc failed/);
});

it('notIn', async () => {
await assert.rejects(async () => {
await User.create({
email: 'a@e.com',
nickname: 'Gwyn'
});
}, /Validation notIn on nickname failed/);
const user = await User.create({
email: 'a@e.com',
nickname: 'sss'
});
assert(user);
assert(user.email);
assert(user.nickname);
});

it('notContaines', async () => {
await assert.rejects(async () => {
await User.create({
email: 'a@e.com',
nickname: 'hou closePease'
});
}, /Validation notContains on nickname failed/);
});

it('regex', async () => {
await assert.rejects(async () => {
await User.create({
email: 'a@e.com',
nickname: 'yes',
desc: 'hhhawww'
});
}, /Validation regex on desc failed/);

await User.create({
email: 'a@e.com',
nickname: 'yes',
desc: '123hhha22'
});
});

it('notRegex', async () => {
await assert.rejects(async () => {
await User.create({
email: 'a@e.com',
nickname: 'yes',
fingerprint: '123yellowfingersss12',
});
}, /Validation notRegex on fingerprint failed/);

await User.create({
email: 'a@e.com',
nickname: 'yes',
fingerprint: 'yellofingerwsss12',
});
});

it('is', async () => {
await assert.rejects(async () => {
await User.create({
email: 'a@e.com',
nickname: 'yes',
fingerprint: 'yellowfingersss',
});
}, /Validation is on fingerprint failed/);

await User.create({
email: 'a@e.com',
nickname: 'yes',
fingerprint: 'yellofingerwsss12',
});
});

it('notEmpty', async () => {
await assert.rejects(async () => {
await User.create({
email: 'a@e.com',
nickname: 'yes',
desc: ''
});
}, /Validation notEmpty on desc failed/);

await User.create({
email: 'a@e.com',
nickname: 'yes',
desc: '123fin22',
});
});

it('multiple validator and custom msg', async () => {
await assert.rejects(async () => {
await User.create({
Expand Down Expand Up @@ -175,7 +286,7 @@ describe('validator', () => {
email: 'a1@e.com',
nickname: 'sss1',
status: 1,
desc: '222'
desc: '222www22'
});
assert(user);
});
Expand All @@ -185,13 +296,13 @@ describe('validator', () => {
await User.create({
email: 'a@e.com',
nickname: 'sss',
fingerprint: 'aaa'
fingerprint: 'aaa12'
});
}, /Validation contains on fingerprint failed/);
const user = await User.create({
email: 'a1@e.com',
nickname: 'sss1',
fingerprint: 'fingerprint:1'
fingerprint: 'fingerprints12'
});
assert(user);
});
Expand Down Expand Up @@ -342,7 +453,7 @@ describe('validator', () => {
const users = [];
while (i < 10) {
users.push({
email: `a@e${i}.com`,
email: `a${i}@e.com`,
nickname: `sss${i}`,
fingerprint: 'aaa'
});
Expand All @@ -359,7 +470,7 @@ describe('validator', () => {
const users = [];
while (i < 10) {
users.push({
email: `a@e${i}.com`,
email: `a${i}@e.com`,
nickname: `sss${i}`,
fingerprint: 'aaa'
});
Expand All @@ -373,4 +484,28 @@ describe('validator', () => {
});

});

describe('executeValidator', () => {
it('revert should work while validate faield', async () => {
const user = await User.create({
email: 'a@e.com',
nickname: 'sss',
desc: '231hjjj'
});

await assert.rejects(async () => {
await user.update({
desc: '1'
});
}, /Invalid desc/);

assert(user.desc === '231hjjj');

await user.update({
desc: '121hhhh'
});

assert(user.getRawPrevious('desc') === '231hjjj');
});
});
});

0 comments on commit b77da6b

Please sign in to comment.