Best Python code snippet using tavern
validation.test.js
Source:validation.test.js
1/**2 * Copyright © Magento, Inc. All rights reserved.3 * See COPYING.txt for license details.4 */5define([6 'jquery',7 'mage/validation'8], function ($) {9 'use strict';10 describe('Testing credit card validation', function () {11 it('Card type matches credit card number', function () {12 expect($.validator.methods['validate-cc-type-select'].call(13 this, 'VI', null, $('<input id="visa-valid" type="text" value="4916808263499650"/>'))14 ).toEqual(true);15 expect($.validator.methods['validate-cc-type-select'].call(16 this, 'VI', null, $('<input id="visa-invalid" type="text" value="1234567890123456"/>'))17 ).toEqual(false);18 expect($.validator.methods['validate-cc-type-select'].call(19 this, 'MC', null, $('<input id="mc-valid" type="text" value="5203731841177490"/>'))20 ).toEqual(true);21 expect($.validator.methods['validate-cc-type-select'].call(22 this, 'MC', null, $('<input id="mc-invalid" type="text" value="1111222233334444"/>'))23 ).toEqual(false);24 expect($.validator.methods['validate-cc-type-select'].call(25 this, 'MC', null, $('<input id="mc-valid" type="text" value="2221220000000003"/>'))26 ).toEqual(true);27 expect($.validator.methods['validate-cc-type-select'].call(28 this, 'MC', null, $('<input id="mc-invalid" type="text" value="2721220000000008"/>'))29 ).toEqual(false);30 expect($.validator.methods['validate-cc-type-select'].call(31 this, 'AE', null, $('<input id="ae-valid" type="text" value="376244899619217"/>'))32 ).toEqual(true);33 expect($.validator.methods['validate-cc-type-select'].call(34 this, 'AE', null, $('<input id="ae-invalid" type="text" value="123451234512345"/>'))35 ).toEqual(false);36 expect($.validator.methods['validate-cc-type-select'].call(37 this, 'DI', null, $('<input id="di-valid" type="text" value="601109020000000003"/>'))38 ).toEqual(true);39 expect($.validator.methods['validate-cc-type-select'].call(40 this, 'DI', null, $('<input id="di-invalid" type="text" value="6011111144444444"/>'))41 ).toEqual(false);42 expect($.validator.methods['validate-cc-type-select'].call(43 this, 'DI', null, $('<input id="di-valid" type="text" value="6011222233334444"/>'))44 ).toEqual(true);45 expect($.validator.methods['validate-cc-type-select'].call(46 this, 'DI', null, $('<input id="di-invalid" type="text" value="6011522233334447"/>'))47 ).toEqual(false);48 expect($.validator.methods['validate-cc-type-select'].call(49 this, 'DI', null, $('<input id="di-valid" type="text" value="601174455555553"/>'))50 ).toEqual(true);51 expect($.validator.methods['validate-cc-type-select'].call(52 this, 'DI', null, $('<input id="di-invalid" type="text" value="6011755555555550"/>'))53 ).toEqual(false);54 expect($.validator.methods['validate-cc-type-select'].call(55 this, 'DI', null, $('<input id="di-valid" type="text" value="601177455555556"/>'))56 ).toEqual(true);57 expect($.validator.methods['validate-cc-type-select'].call(58 this, 'DI', null, $('<input id="di-invalid" type="text" value="601182455555556"/>'))59 ).toEqual(false);60 expect($.validator.methods['validate-cc-type-select'].call(61 this, 'DI', null, $('<input id="di-valid" type="text" value="601187999555558"/>'))62 ).toEqual(true);63 expect($.validator.methods['validate-cc-type-select'].call(64 this, 'DI', null, $('<input id="di-invalid" type="text" value="601287999555556"/>'))65 ).toEqual(false);66 expect($.validator.methods['validate-cc-type-select'].call(67 this, 'DI', null, $('<input id="di-valid" type="text" value="6444444444444443"/>'))68 ).toEqual(true);69 expect($.validator.methods['validate-cc-type-select'].call(70 this, 'DI', null, $('<input id="di-invalid" type="text" value="6644444444444441"/>'))71 ).toEqual(false);72 expect($.validator.methods['validate-cc-type-select'].call(73 this, 'DN', null, $('<input id="dn-valid" type="text" value="3095434000000001"/>'))74 ).toEqual(true);75 expect($.validator.methods['validate-cc-type-select'].call(76 this, 'DN', null, $('<input id="dn-invalid" type="text" value="3799999900000003"/>'))77 ).toEqual(false);78 expect($.validator.methods['validate-cc-type-select'].call(79 this, 'DN', null, $('<input id="dn-valid" type="text" value="3044444444444444"/>'))80 ).toEqual(true);81 expect($.validator.methods['validate-cc-type-select'].call(82 this, 'DN', null, $('<input id="dn-invalid" type="text" value="3064444444444449"/>'))83 ).toEqual(false);84 expect($.validator.methods['validate-cc-type-select'].call(85 this, 'DN', null, $('<input id="dn-valid" type="text" value="3095444444444442"/>'))86 ).toEqual(true);87 expect($.validator.methods['validate-cc-type-select'].call(88 this, 'DN', null, $('<input id="dn-invalid" type="text" value="3096444444444441"/>'))89 ).toEqual(false);90 expect($.validator.methods['validate-cc-type-select'].call(91 this, 'DN', null, $('<input id="dn-valid" type="text" value="3696444444444445"/>'))92 ).toEqual(true);93 expect($.validator.methods['validate-cc-type-select'].call(94 this, 'DN', null, $('<input id="dn-invalid" type="text" value="3796444444444444"/>'))95 ).toEqual(false);96 expect($.validator.methods['validate-cc-type-select'].call(97 this, 'DN', null, $('<input id="dn-valid" type="text" value="3696444444444445"/>'))98 ).toEqual(true);99 expect($.validator.methods['validate-cc-type-select'].call(100 this, 'DN', null, $('<input id="dn-valid" type="text" value="3896444444444443"/>'))101 ).toEqual(true);102 expect($.validator.methods['validate-cc-type-select'].call(103 this, 'DN', null, $('<input id="dn-invalid" type="text" value="3796444444444444"/>'))104 ).toEqual(false);105 expect($.validator.methods['validate-cc-type-select'].call(106 this, 'JCB', null, $('<input id="jcb-valid" type="text" value="3528444444444449"/>'))107 ).toEqual(true);108 expect($.validator.methods['validate-cc-type-select'].call(109 this, 'JCB', null, $('<input id="jcb-invalid" type="text" value="3527444444444448"/>'))110 ).toEqual(false);111 expect($.validator.methods['validate-cc-type-select'].call(112 this, 'JCB', null, $('<input id="jcb-invalid" type="text" value="3590444444444448"/>'))113 ).toEqual(false);114 expect($.validator.methods['validate-cc-type-select'].call(115 this, 'UN', null, $('<input id="un-valid" type="text" value="6221262244444440"/>'))116 ).toEqual(true);117 expect($.validator.methods['validate-cc-type-select'].call(118 this, 'UN', null, $('<input id="un-invalid" type="text" value="6229981111111111"/>'))119 ).toEqual(false);120 expect($.validator.methods['validate-cc-type-select'].call(121 this, 'UN', null, $('<input id="un-valid" type="text" value="6249981111111117"/>'))122 ).toEqual(true);123 expect($.validator.methods['validate-cc-type-select'].call(124 this, 'UN', null, $('<input id="un-invalid" type="text" value="6279981111111110"/>'))125 ).toEqual(false);126 expect($.validator.methods['validate-cc-type-select'].call(127 this, 'UN', null, $('<input id="un-valid" type="text" value="6282981111111115"/>'))128 ).toEqual(true);129 expect($.validator.methods['validate-cc-type-select'].call(130 this, 'UN', null, $('<input id="un-invalid" type="text" value="6289981111111118"/>'))131 ).toEqual(false);132 });133 });134 describe('Testing UK Mobile number validation', function () {135 it('Valid UK Mobile Number', function () {136 var element = $('<input id="telephone" type="text" value="07400123456" />');137 expect($.validator.methods.mobileUK.call(138 $.validator.prototype, element.val(), element.get(0)139 )).toBeTruthy();140 });141 it('Invalid UK Mobile Number', function () {142 var element = $('<input id="telephone" type="text" value="06400123456" />');143 expect($.validator.methods.mobileUK.call(144 $.validator.prototype, element.val(), element.get(0)145 )).toBeFalsy();146 });147 it('Valid UK Mobile Number (International)', function () {148 var element = $('<input id="telephone" type="text" value="+447400123456" />');149 expect($.validator.methods.mobileUK.call(150 $.validator.prototype, element.val(), element.get(0)151 )).toBeTruthy();152 });153 it('Invalid UK Mobile Number', function () {154 var element = $('<input id="telephone" type="text" value="+446400123456" />');155 expect($.validator.methods.mobileUK.call(156 $.validator.prototype, element.val(), element.get(0)157 )).toBeFalsy();158 });159 });160 describe('Validation of the password against the user name', function () {161 it('rejects data, if password is the same as user name', function () {162 var password = $('<input id="password" type="password" value="EmailPasswordTheSame" />'),163 email = $('<input id="email" type="email" value="EmailPasswordTheSame" />');164 expect($.validator.methods['password-not-equal-to-user-name'].call(165 $.validator.prototype, password.val(), null, email.val()166 )).toEqual(false);167 });168 it('approves data, if password is different from user name', function () {169 var password = $('<input id="password" type="password" value="SomePassword" />'),170 email = $('<input id="email" type="email" value="SomeEmail" />');171 expect($.validator.methods['password-not-equal-to-user-name'].call(172 $.validator.prototype, password.val(), null, email.val()173 )).toEqual(true);174 });175 });176 describe('Testing validate-no-html-tags', function () {177 it('validate-no-html-tags', function () {178 expect($.validator.methods['validate-no-html-tags']179 .call($.validator.prototype, '')).toEqual(true);180 expect($.validator.methods['validate-no-html-tags']181 .call($.validator.prototype, null)).toEqual(true);182 expect($.validator.methods['validate-no-html-tags']183 .call($.validator.prototype, 'abc')).toEqual(true);184 expect($.validator.methods['validate-no-html-tags']185 .call($.validator.prototype, '<div>abc</div>')).toEqual(false);186 });187 });188 describe('Testing allow-container-className', function () {189 it('allow-container-className', function () {190 var radio = $('<input type="radio" class="change-container-classname"/>'),191 checkbox = $('<input type="checkbox" class="change-container-classname"/>'),192 radio2 = $('<input type="radio"/>'),193 checkbox2 = $('<input type="checkbox"/>');194 expect($.validator.methods['allow-container-className']195 .call($.validator.prototype, radio[0])).toEqual(true);196 expect($.validator.methods['allow-container-className']197 .call($.validator.prototype, checkbox[0])).toEqual(true);198 expect($.validator.methods['allow-container-className']199 .call($.validator.prototype, radio2[0])).toEqual(false);200 expect($.validator.methods['allow-container-className']201 .call($.validator.prototype, checkbox2[0])).toEqual(false);202 });203 });204 describe('Testing validate-select', function () {205 it('validate-select', function () {206 expect($.validator.methods['validate-select']207 .call($.validator.prototype, '')).toEqual(false);208 expect($.validator.methods['validate-select']209 .call($.validator.prototype, 'none')).toEqual(false);210 expect($.validator.methods['validate-select']211 .call($.validator.prototype, null)).toEqual(false);212 expect($.validator.methods['validate-select']213 .call($.validator.prototype, undefined)).toEqual(false);214 expect($.validator.methods['validate-select']215 .call($.validator.prototype, 'abc')).toEqual(true);216 });217 });218 describe('Testing validate-no-empty', function () {219 it('validate-no-empty', function () {220 expect($.validator.methods['validate-no-empty']221 .call($.validator.prototype, '')).toEqual(false);222 expect($.validator.methods['validate-no-empty']223 .call($.validator.prototype, null)).toEqual(false);224 expect($.validator.methods['validate-no-empty']225 .call($.validator.prototype, undefined)).toEqual(false);226 expect($.validator.methods['validate-no-empty']227 .call($.validator.prototype, ' ')).toEqual(false);228 expect($.validator.methods['validate-no-empty']229 .call($.validator.prototype, 'test')).toEqual(true);230 });231 });232 describe('Testing validate-alphanum-with-spaces', function () {233 it('validate-alphanum-with-spaces', function () {234 expect($.validator.methods['validate-alphanum-with-spaces']235 .call($.validator.prototype, '')).toEqual(true);236 expect($.validator.methods['validate-alphanum-with-spaces']237 .call($.validator.prototype, null)).toEqual(true);238 expect($.validator.methods['validate-alphanum-with-spaces']239 .call($.validator.prototype, undefined)).toEqual(true);240 expect($.validator.methods['validate-alphanum-with-spaces']241 .call($.validator.prototype, ' ')).toEqual(true);242 expect($.validator.methods['validate-alphanum-with-spaces']243 .call($.validator.prototype, 'abc ')).toEqual(true);244 expect($.validator.methods['validate-alphanum-with-spaces']245 .call($.validator.prototype, ' 123 ')).toEqual(true);246 expect($.validator.methods['validate-alphanum-with-spaces']247 .call($.validator.prototype, ' abc123 ')).toEqual(true);248 expect($.validator.methods['validate-alphanum-with-spaces']249 .call($.validator.prototype, ' !@# ')).toEqual(false);250 expect($.validator.methods['validate-alphanum-with-spaces']251 .call($.validator.prototype, ' abc.123 ')).toEqual(false);252 });253 });254 describe('Testing validate-phoneStrict', function () {255 it('validate-phoneStrict', function () {256 expect($.validator.methods['validate-phoneStrict']257 .call($.validator.prototype, '')).toEqual(true);258 expect($.validator.methods['validate-phoneStrict']259 .call($.validator.prototype, null)).toEqual(true);260 expect($.validator.methods['validate-phoneStrict']261 .call($.validator.prototype, undefined)).toEqual(true);262 expect($.validator.methods['validate-phoneStrict']263 .call($.validator.prototype, ' ')).toEqual(false);264 expect($.validator.methods['validate-phoneStrict']265 .call($.validator.prototype, '5121231234')).toEqual(false);266 expect($.validator.methods['validate-phoneStrict']267 .call($.validator.prototype, '512.123.1234')).toEqual(false);268 expect($.validator.methods['validate-phoneStrict']269 .call($.validator.prototype, '512-123-1234')).toEqual(true);270 expect($.validator.methods['validate-phoneStrict']271 .call($.validator.prototype, '(512)123-1234')).toEqual(true);272 expect($.validator.methods['validate-phoneStrict']273 .call($.validator.prototype, '(512) 123-1234')).toEqual(true);274 });275 });276 describe('Testing validate-phoneLax', function () {277 it('validate-phoneLax', function () {278 expect($.validator.methods['validate-phoneLax']279 .call($.validator.prototype, '')).toEqual(true);280 expect($.validator.methods['validate-phoneLax']281 .call($.validator.prototype, null)).toEqual(true);282 expect($.validator.methods['validate-phoneLax']283 .call($.validator.prototype, undefined)).toEqual(true);284 expect($.validator.methods['validate-phoneLax']285 .call($.validator.prototype, ' ')).toEqual(false);286 expect($.validator.methods['validate-phoneLax']287 .call($.validator.prototype, '5121231234')).toEqual(true);288 expect($.validator.methods['validate-phoneLax']289 .call($.validator.prototype, '512.123.1234')).toEqual(true);290 expect($.validator.methods['validate-phoneLax']291 .call($.validator.prototype, '512-123-1234')).toEqual(true);292 expect($.validator.methods['validate-phoneLax']293 .call($.validator.prototype, '(512)123-1234')).toEqual(true);294 expect($.validator.methods['validate-phoneLax']295 .call($.validator.prototype, '(512) 123-1234')).toEqual(true);296 expect($.validator.methods['validate-phoneLax']297 .call($.validator.prototype, '(512)1231234')).toEqual(true);298 expect($.validator.methods['validate-phoneLax']299 .call($.validator.prototype, '(512)_123_1234')).toEqual(false);300 });301 });302 describe('Testing validate-fax', function () {303 it('validate-fax', function () {304 expect($.validator.methods['validate-fax']305 .call($.validator.prototype, '')).toEqual(true);306 expect($.validator.methods['validate-fax']307 .call($.validator.prototype, null)).toEqual(true);308 expect($.validator.methods['validate-fax']309 .call($.validator.prototype, undefined)).toEqual(true);310 expect($.validator.methods['validate-fax']311 .call($.validator.prototype, ' ')).toEqual(false);312 expect($.validator.methods['validate-fax']313 .call($.validator.prototype, '5121231234')).toEqual(false);314 expect($.validator.methods['validate-fax']315 .call($.validator.prototype, '512.123.1234')).toEqual(false);316 expect($.validator.methods['validate-fax']317 .call($.validator.prototype, '512-123-1234')).toEqual(true);318 expect($.validator.methods['validate-fax']319 .call($.validator.prototype, '(512)123-1234')).toEqual(true);320 expect($.validator.methods['validate-fax']321 .call($.validator.prototype, '(512) 123-1234')).toEqual(true);322 });323 });324 describe('Testing validate-email', function () {325 it('validate-email', function () {326 expect($.validator.methods['validate-email']327 .call($.validator.prototype, '')).toEqual(true);328 expect($.validator.methods['validate-email']329 .call($.validator.prototype, null)).toEqual(true);330 expect($.validator.methods['validate-email']331 .call($.validator.prototype, undefined)).toEqual(true);332 expect($.validator.methods['validate-email']333 .call($.validator.prototype, ' ')).toEqual(false);334 expect($.validator.methods['validate-email']335 .call($.validator.prototype, '123@123.com')).toEqual(true);336 expect($.validator.methods['validate-email']337 .call($.validator.prototype, 'abc@124.en')).toEqual(true);338 expect($.validator.methods['validate-email']339 .call($.validator.prototype, 'abc@abc.commmmm')).toEqual(true);340 expect($.validator.methods['validate-email']341 .call($.validator.prototype, 'abc.abc.abc@abc.commmmm')).toEqual(true);342 expect($.validator.methods['validate-email']343 .call($.validator.prototype, 'abc.abc-abc@abc.commmmm')).toEqual(true);344 expect($.validator.methods['validate-email']345 .call($.validator.prototype, 'abc.abc_abc@abc.commmmm')).toEqual(true);346 expect($.validator.methods['validate-email']347 .call($.validator.prototype, 'abc.abc_abc@abc')).toEqual(false);348 });349 });350 describe('Testing validate-emailSender', function () {351 it('validate-emailSender', function () {352 expect($.validator.methods['validate-emailSender']353 .call($.validator.prototype, '')).toEqual(true);354 expect($.validator.methods['validate-emailSender']355 .call($.validator.prototype, null)).toEqual(true);356 expect($.validator.methods['validate-emailSender']357 .call($.validator.prototype, undefined)).toEqual(true);358 expect($.validator.methods['validate-emailSender']359 .call($.validator.prototype, ' ')).toEqual(true);360 expect($.validator.methods['validate-emailSender']361 .call($.validator.prototype, '123@123.com')).toEqual(true);362 expect($.validator.methods['validate-emailSender']363 .call($.validator.prototype, 'abc@124.en')).toEqual(true);364 expect($.validator.methods['validate-emailSender']365 .call($.validator.prototype, 'abc@abc.commmmm')).toEqual(true);366 expect($.validator.methods['validate-emailSender']367 .call($.validator.prototype, 'abc.abc.abc@abc.commmmm')).toEqual(true);368 expect($.validator.methods['validate-emailSender']369 .call($.validator.prototype, 'abc.abc-abc@abc.commmmm')).toEqual(true);370 expect($.validator.methods['validate-emailSender']371 .call($.validator.prototype, 'abc.abc_abc@abc.commmmm')).toEqual(true);372 });373 });374 describe('Testing validate-password', function () {375 it('validate-password', function () {376 expect($.validator.methods['validate-password']377 .call($.validator.prototype, '')).toEqual(true);378 expect($.validator.methods['validate-password']379 .call($.validator.prototype, null)).toEqual(false);380 expect($.validator.methods['validate-password']381 .call($.validator.prototype, undefined)).toEqual(false);382 expect($.validator.methods['validate-password']383 .call($.validator.prototype, ' ')).toEqual(true);384 expect($.validator.methods['validate-password']385 .call($.validator.prototype, '123@123.com')).toEqual(true);386 expect($.validator.methods['validate-password']387 .call($.validator.prototype, 'abc')).toEqual(false);388 expect($.validator.methods['validate-password']389 .call($.validator.prototype, 'abc ')).toEqual(false);390 expect($.validator.methods['validate-password']391 .call($.validator.prototype, ' abc ')).toEqual(false);392 expect($.validator.methods['validate-password']393 .call($.validator.prototype, 'dddd')).toEqual(false);394 });395 });396 describe('Testing validate-admin-password', function () {397 it('validate-admin-password', function () {398 expect($.validator.methods['validate-admin-password']399 .call($.validator.prototype, '')).toEqual(true);400 expect($.validator.methods['validate-admin-password']401 .call($.validator.prototype, null)).toEqual(false);402 expect($.validator.methods['validate-admin-password']403 .call($.validator.prototype, undefined)).toEqual(false);404 expect($.validator.methods['validate-admin-password']405 .call($.validator.prototype, ' ')).toEqual(true);406 expect($.validator.methods['validate-admin-password']407 .call($.validator.prototype, '123@123.com')).toEqual(true);408 expect($.validator.methods['validate-admin-password']409 .call($.validator.prototype, 'abc')).toEqual(false);410 expect($.validator.methods['validate-admin-password']411 .call($.validator.prototype, 'abc ')).toEqual(false);412 expect($.validator.methods['validate-admin-password']413 .call($.validator.prototype, ' abc ')).toEqual(false);414 expect($.validator.methods['validate-admin-password']415 .call($.validator.prototype, 'dddd')).toEqual(false);416 });417 });418 describe('Testing validate-url', function () {419 it('validate-url', function () {420 expect($.validator.methods['validate-url']421 .call($.validator.prototype, '')).toEqual(true);422 expect($.validator.methods['validate-url']423 .call($.validator.prototype, null)).toEqual(true);424 expect($.validator.methods['validate-url']425 .call($.validator.prototype, undefined)).toEqual(true);426 expect($.validator.methods['validate-url']427 .call($.validator.prototype, ' ')).toEqual(false);428 expect($.validator.methods['validate-url']429 .call($.validator.prototype, 'http://www.google.com')).toEqual(true);430 expect($.validator.methods['validate-url']431 .call($.validator.prototype, 'http://127.0.0.1:8080/index.php')).toEqual(true);432 expect($.validator.methods['validate-url']433 .call($.validator.prototype, 'http://app-spot.com/index.php')).toEqual(true);434 expect($.validator.methods['validate-url']435 .call($.validator.prototype, 'http://app-spot_space.com/index.php')).toEqual(true);436 });437 });438 describe('Testing validate-clean-url', function () {439 it('validate-clean-url', function () {440 expect($.validator.methods['validate-clean-url']441 .call($.validator.prototype, '')).toEqual(true);442 expect($.validator.methods['validate-clean-url']443 .call($.validator.prototype, null)).toEqual(true);444 expect($.validator.methods['validate-clean-url']445 .call($.validator.prototype, undefined)).toEqual(true);446 expect($.validator.methods['validate-clean-url']447 .call($.validator.prototype, ' ')).toEqual(false);448 expect($.validator.methods['validate-clean-url']449 .call($.validator.prototype, 'http://www.google.com')).toEqual(true);450 expect($.validator.methods['validate-clean-url']451 .call($.validator.prototype, 'http://127.0.0.1:8080/index.php')).toEqual(false);452 expect($.validator.methods['validate-clean-url']453 .call($.validator.prototype, 'http://127.0.0.1:8080')).toEqual(false);454 expect($.validator.methods['validate-clean-url']455 .call($.validator.prototype, 'http://127.0.0.1')).toEqual(false);456 });457 });458 describe('Testing validate-xml-identifier', function () {459 it('validate-xml-identifier', function () {460 expect($.validator.methods['validate-xml-identifier']461 .call($.validator.prototype, '')).toEqual(true);462 expect($.validator.methods['validate-xml-identifier']463 .call($.validator.prototype, null)).toEqual(true);464 expect($.validator.methods['validate-xml-identifier']465 .call($.validator.prototype, undefined)).toEqual(true);466 expect($.validator.methods['validate-xml-identifier']467 .call($.validator.prototype, ' ')).toEqual(false);468 expect($.validator.methods['validate-xml-identifier']469 .call($.validator.prototype, 'abc')).toEqual(true);470 expect($.validator.methods['validate-xml-identifier']471 .call($.validator.prototype, 'abc_123')).toEqual(true);472 expect($.validator.methods['validate-xml-identifier']473 .call($.validator.prototype, 'abc-123')).toEqual(true);474 expect($.validator.methods['validate-xml-identifier']475 .call($.validator.prototype, '123-abc')).toEqual(false);476 });477 });478 describe('Testing validate-ssn', function () {479 it('validate-ssn', function () {480 expect($.validator.methods['validate-ssn']481 .call($.validator.prototype, '')).toEqual(true);482 expect($.validator.methods['validate-ssn']483 .call($.validator.prototype, null)).toEqual(true);484 expect($.validator.methods['validate-ssn']485 .call($.validator.prototype, undefined)).toEqual(true);486 expect($.validator.methods['validate-ssn']487 .call($.validator.prototype, ' ')).toEqual(false);488 expect($.validator.methods['validate-ssn']489 .call($.validator.prototype, 'abc')).toEqual(false);490 expect($.validator.methods['validate-ssn']491 .call($.validator.prototype, '123-13-1234')).toEqual(true);492 expect($.validator.methods['validate-ssn']493 .call($.validator.prototype, '012-12-1234')).toEqual(true);494 expect($.validator.methods['validate-ssn']495 .call($.validator.prototype, '23-12-1234')).toEqual(false);496 });497 });498 describe('Testing validate-zip-us', function () {499 it('validate-zip-us', function () {500 expect($.validator.methods['validate-zip-us']501 .call($.validator.prototype, '')).toEqual(true);502 expect($.validator.methods['validate-zip-us']503 .call($.validator.prototype, null)).toEqual(true);504 expect($.validator.methods['validate-zip-us']505 .call($.validator.prototype, undefined)).toEqual(true);506 expect($.validator.methods['validate-zip-us']507 .call($.validator.prototype, ' ')).toEqual(false);508 expect($.validator.methods['validate-zip-us']509 .call($.validator.prototype, '12345-1234')).toEqual(true);510 expect($.validator.methods['validate-zip-us']511 .call($.validator.prototype, '02345')).toEqual(true);512 expect($.validator.methods['validate-zip-us']513 .call($.validator.prototype, '1234')).toEqual(false);514 expect($.validator.methods['validate-zip-us']515 .call($.validator.prototype, '1234-1234')).toEqual(false);516 });517 });518 describe('Testing validate-date-au', function () {519 it('validate-date-au', function () {520 expect($.validator.methods['validate-date-au']521 .call($.validator.prototype, '')).toEqual(true);522 expect($.validator.methods['validate-date-au']523 .call($.validator.prototype, null)).toEqual(true);524 expect($.validator.methods['validate-date-au']525 .call($.validator.prototype, undefined)).toEqual(true);526 expect($.validator.methods['validate-date-au']527 .call($.validator.prototype, ' ')).toEqual(false);528 expect($.validator.methods['validate-date-au']529 .call($.validator.prototype, '01/01/2012')).toEqual(true);530 expect($.validator.methods['validate-date-au']531 .call($.validator.prototype, '30/01/2012')).toEqual(true);532 expect($.validator.methods['validate-date-au']533 .call($.validator.prototype, '01/30/2012')).toEqual(false);534 expect($.validator.methods['validate-date-au']535 .call($.validator.prototype, '1/1/2012')).toEqual(false);536 });537 });538 describe('Testing validate-currency-dollar', function () {539 it('validate-currency-dollar', function () {540 expect($.validator.methods['validate-currency-dollar']541 .call($.validator.prototype, '')).toEqual(true);542 expect($.validator.methods['validate-currency-dollar']543 .call($.validator.prototype, null)).toEqual(true);544 expect($.validator.methods['validate-currency-dollar']545 .call($.validator.prototype, undefined)).toEqual(true);546 expect($.validator.methods['validate-currency-dollar']547 .call($.validator.prototype, ' ')).toEqual(false);548 expect($.validator.methods['validate-currency-dollar']549 .call($.validator.prototype, '$123')).toEqual(true);550 expect($.validator.methods['validate-currency-dollar']551 .call($.validator.prototype, '$1,123.00')).toEqual(true);552 expect($.validator.methods['validate-currency-dollar']553 .call($.validator.prototype, '$1234')).toEqual(true);554 expect($.validator.methods['validate-currency-dollar']555 .call($.validator.prototype, '$1234.1234')).toEqual(false);556 });557 });558 describe('Testing validate-not-negative-number', function () {559 it('validate-not-negative-number', function () {560 expect($.validator.methods['validate-not-negative-number']561 .call($.validator.prototype, '')).toEqual(true);562 expect($.validator.methods['validate-not-negative-number']563 .call($.validator.prototype, null)).toEqual(true);564 expect($.validator.methods['validate-not-negative-number']565 .call($.validator.prototype, undefined)).toEqual(true);566 expect($.validator.methods['validate-not-negative-number']567 .call($.validator.prototype, ' ')).toEqual(false);568 expect($.validator.methods['validate-not-negative-number']569 .call($.validator.prototype, '0')).toEqual(true);570 expect($.validator.methods['validate-not-negative-number']571 .call($.validator.prototype, '1')).toEqual(true);572 expect($.validator.methods['validate-not-negative-number']573 .call($.validator.prototype, '1234')).toEqual(true);574 expect($.validator.methods['validate-not-negative-number']575 .call($.validator.prototype, '1,234.1234')).toEqual(true);576 expect($.validator.methods['validate-not-negative-number']577 .call($.validator.prototype, '-1')).toEqual(false);578 expect($.validator.methods['validate-not-negative-number']579 .call($.validator.prototype, '-1e')).toEqual(false);580 expect($.validator.methods['validate-not-negative-number']581 .call($.validator.prototype, '-1,234.1234')).toEqual(false);582 });583 });584 describe('Testing validate-greater-than-zero', function () {585 it('validate-greater-than-zero', function () {586 expect($.validator.methods['validate-greater-than-zero']587 .call($.validator.prototype, '')).toEqual(true);588 expect($.validator.methods['validate-greater-than-zero']589 .call($.validator.prototype, null)).toEqual(true);590 expect($.validator.methods['validate-greater-than-zero']591 .call($.validator.prototype, undefined)).toEqual(true);592 expect($.validator.methods['validate-greater-than-zero']593 .call($.validator.prototype, ' ')).toEqual(false);594 expect($.validator.methods['validate-greater-than-zero']595 .call($.validator.prototype, '0')).toEqual(false);596 expect($.validator.methods['validate-greater-than-zero']597 .call($.validator.prototype, '1')).toEqual(true);598 expect($.validator.methods['validate-greater-than-zero']599 .call($.validator.prototype, '1234')).toEqual(true);600 expect($.validator.methods['validate-greater-than-zero']601 .call($.validator.prototype, '1,234.1234')).toEqual(true);602 expect($.validator.methods['validate-greater-than-zero']603 .call($.validator.prototype, '-1')).toEqual(false);604 expect($.validator.methods['validate-greater-than-zero']605 .call($.validator.prototype, '-1e')).toEqual(false);606 expect($.validator.methods['validate-greater-than-zero']607 .call($.validator.prototype, '-1,234.1234')).toEqual(false);608 });609 });610 describe('Testing validate-css-length', function () {611 it('validate-css-length', function () {612 expect($.validator.methods['validate-css-length']613 .call($.validator.prototype, '')).toEqual(true);614 expect($.validator.methods['validate-css-length']615 .call($.validator.prototype, null)).toEqual(false);616 expect($.validator.methods['validate-css-length']617 .call($.validator.prototype, undefined)).toEqual(false);618 expect($.validator.methods['validate-css-length']619 .call($.validator.prototype, ' ')).toEqual(false);620 expect($.validator.methods['validate-css-length']621 .call($.validator.prototype, '0')).toEqual(true);622 expect($.validator.methods['validate-css-length']623 .call($.validator.prototype, '1')).toEqual(true);624 expect($.validator.methods['validate-css-length']625 .call($.validator.prototype, '1234')).toEqual(true);626 expect($.validator.methods['validate-css-length']627 .call($.validator.prototype, '1,234.1234')).toEqual(false);628 expect($.validator.methods['validate-css-length']629 .call($.validator.prototype, '-1')).toEqual(false);630 expect($.validator.methods['validate-css-length']631 .call($.validator.prototype, '-1e')).toEqual(false);632 expect($.validator.methods['validate-css-length']633 .call($.validator.prototype, '-1,234.1234')).toEqual(false);634 });635 });636 describe('Testing validate-data', function () {637 it('validate-data', function () {638 expect($.validator.methods['validate-data']639 .call($.validator.prototype, '')).toEqual(true);640 expect($.validator.methods['validate-data']641 .call($.validator.prototype, null)).toEqual(true);642 expect($.validator.methods['validate-data']643 .call($.validator.prototype, undefined)).toEqual(true);644 expect($.validator.methods['validate-data']645 .call($.validator.prototype, ' ')).toEqual(false);646 expect($.validator.methods['validate-data']647 .call($.validator.prototype, '123abc')).toEqual(false);648 expect($.validator.methods['validate-data']649 .call($.validator.prototype, 'abc')).toEqual(true);650 expect($.validator.methods['validate-data']651 .call($.validator.prototype, ' abc')).toEqual(false);652 expect($.validator.methods['validate-data']653 .call($.validator.prototype, 'abc123')).toEqual(true);654 expect($.validator.methods['validate-data']655 .call($.validator.prototype, 'abc-123')).toEqual(false);656 });657 });658 describe('Testing validate-one-required-by-name', function () {659 it('validate-one-required-by-name', function () {660 var radio = $('<input type="radio" name="radio"/>'),661 radio2 = $('<input type="radio" name="radio" checked/>'),662 checkbox = $('<input type="checkbox" name="checkbox"/>'),663 checkbox2 = $('<input type="checkbox" name="checkbox" checked/>'),664 $test = $('<div id="test-block" />'),665 prevForm = $.validator.prototype.currentForm;666 $.validator.prototype.currentForm = $test[0];667 $test.append(radio);668 expect($.validator.methods['validate-one-required-by-name']669 .call($.validator.prototype, null, radio[0], true)).toEqual(false);670 $test.append(radio2);671 expect($.validator.methods['validate-one-required-by-name']672 .call($.validator.prototype, null, radio2[0], true)).toEqual(true);673 $test.append(checkbox);674 expect($.validator.methods['validate-one-required-by-name']675 .call($.validator.prototype, null, checkbox[0], true)).toEqual(false);676 $test.append(checkbox2);677 expect($.validator.methods['validate-one-required-by-name']678 .call($.validator.prototype, null, checkbox2[0], true)).toEqual(true);679 $.validator.prototype.currentForm = prevForm;680 });681 });682 describe('Testing less-than-equals-to', function () {683 it('less-than-equals-to', function () {684 var elm1 = $('<input type="text" value="6" id="element1" />'),685 elm2 = $('<input type="text" value="5" id="element2" />'),686 elm3 = $('<input type="text" id="element3" />'),687 elm4 = $('<input type="text" value=5 id="element4" />'),688 elm5 = $('<input type="text" id="element6" />'),689 elm6 = $('<input type="text" value=6 id="element5" />'),690 elm7 = $('<input type="text" value=20 id="element7" />'),691 elm8 = $('<input type="text" value=100 id="element8" />');692 expect($.validator.methods['less-than-equals-to']693 .call($.validator.prototype, elm1[0].value, elm1, elm2)).toEqual(false);694 elm1[0].value = 4;695 expect($.validator.methods['less-than-equals-to']696 .call($.validator.prototype, elm1[0].value, elm1, elm2)).toEqual(true);697 expect($.validator.methods['less-than-equals-to']698 .call($.validator.prototype, elm3[0].value, elm3, elm4)).toEqual(true);699 expect($.validator.methods['less-than-equals-to']700 .call($.validator.prototype, elm5[0].value, elm5, elm6)).toEqual(true);701 expect($.validator.methods['less-than-equals-to']702 .call($.validator.prototype, elm7[0].value, elm7, elm8)).toEqual(true);703 });704 });705 describe('Testing greater-than-equals-to', function () {706 it('greater-than-equals-to', function () {707 var elm1 = $('<input type="text" value=6 id="element1" />'),708 elm2 = $('<input type="text" value=7 id="element2" />'),709 elm3 = $('<input type="text" id="element3" />'),710 elm4 = $('<input type="text" value=5 id="element4" />'),711 elm5 = $('<input type="text" id="element6" />'),712 elm6 = $('<input type="text" value=6 id="element5" />'),713 elm7 = $('<input type="text" value=100 id="element7" />'),714 elm8 = $('<input type="text" value=20 id="element8" />');715 expect($.validator.methods['greater-than-equals-to']716 .call($.validator.prototype, elm1[0].value, elm1, elm2)).toEqual(false);717 elm1[0].value = 9;718 expect($.validator.methods['greater-than-equals-to']719 .call($.validator.prototype, elm1[0].value, elm1, elm2)).toEqual(true);720 expect($.validator.methods['greater-than-equals-to']721 .call($.validator.prototype, elm3[0].value, elm3, elm4)).toEqual(true);722 expect($.validator.methods['greater-than-equals-to']723 .call($.validator.prototype, elm5[0].value, elm5, elm6)).toEqual(true);724 expect($.validator.methods['greater-than-equals-to']725 .call($.validator.prototype, elm7[0].value, elm7, elm8)).toEqual(true);726 });727 });728 describe('Testing validate-cc-type-select', function () {729 it('validate-cc-type-select', function () {730 var visaValid = $('<input id="visa-valid" type="text" value="4916808263499650"/>'),731 visaInvalid = $('<input id="visa-invalid" type="text" value="1234567890123456"/>'),732 mcValid = $('<input id="mc-valid" type="text" value="5203731841177490"/>'),733 mcInvalid = $('<input id="mc-invalid" type="text" value="1111222233334444"/>'),734 aeValid = $('<input id="ae-valid" type="text" value="376244899619217"/>'),735 aeInvalid = $('<input id="ae-invalid" type="text" value="123451234512345"/>'),736 diValid = $('<input id="di-valid" type="text" value="6011050000000009"/>'),737 diInvalid = $('<input id="di-invalid" type="text" value="6011199900000005"/>'),738 dnValid = $('<input id="dn-valid" type="text" value="3095434000000001"/>'),739 dnInvalid = $('<input id="dn-invalid" type="text" value="3799999900000003"/>'),740 jcbValid = $('<input id="jcb-valid" type="text" value="3528000000000007"/>'),741 jcbInvalid = $('<input id="jcb-invalid" type="text" value="359000001111118"/>');742 expect($.validator.methods['validate-cc-type-select']743 .call($.validator.prototype, 'VI', null, visaValid)).toEqual(true);744 expect($.validator.methods['validate-cc-type-select']745 .call($.validator.prototype, 'VI', null, visaInvalid)).toEqual(false);746 expect($.validator.methods['validate-cc-type-select']747 .call($.validator.prototype, 'MC', null, mcValid)).toEqual(true);748 expect($.validator.methods['validate-cc-type-select']749 .call($.validator.prototype, 'MC', null, mcInvalid)).toEqual(false);750 expect($.validator.methods['validate-cc-type-select']751 .call($.validator.prototype, 'AE', null, aeValid)).toEqual(true);752 expect($.validator.methods['validate-cc-type-select']753 .call($.validator.prototype, 'AE', null, aeInvalid)).toEqual(false);754 expect($.validator.methods['validate-cc-type-select']755 .call($.validator.prototype, 'DI', null, diValid)).toEqual(true);756 expect($.validator.methods['validate-cc-type-select']757 .call($.validator.prototype, 'DI', null, diInvalid)).toEqual(false);758 expect($.validator.methods['validate-cc-type-select']759 .call($.validator.prototype, 'DN', null, dnValid)).toEqual(true);760 expect($.validator.methods['validate-cc-type-select']761 .call($.validator.prototype, 'DN', null, dnInvalid)).toEqual(false);762 expect($.validator.methods['validate-cc-type-select']763 .call($.validator.prototype, 'JCB', null, jcbValid)).toEqual(true);764 expect($.validator.methods['validate-cc-type-select']765 .call($.validator.prototype, 'JCB', null, jcbInvalid)).toEqual(false);766 });767 });768 describe('Testing validate-cc-number', function () {769 it('validate-cc-number', function () {770 expect($.validator.methods['validate-cc-number']771 .call($.validator.prototype, '4916835098995909', null, null)).toEqual(true);772 expect($.validator.methods['validate-cc-number']773 .call($.validator.prototype, '5265071363284878', null, null)).toEqual(true);774 expect($.validator.methods['validate-cc-number']775 .call($.validator.prototype, '6011120623356953', null, null)).toEqual(true);776 expect($.validator.methods['validate-cc-number']777 .call($.validator.prototype, '371293266574617', null, null)).toEqual(true);778 expect($.validator.methods['validate-cc-number']779 .call($.validator.prototype, '4916835098995901', null, null)).toEqual(false);780 expect($.validator.methods['validate-cc-number']781 .call($.validator.prototype, '5265071363284870', null, null)).toEqual(false);782 expect($.validator.methods['validate-cc-number']783 .call($.validator.prototype, '6011120623356951', null, null)).toEqual(false);784 expect($.validator.methods['validate-cc-number']785 .call($.validator.prototype, '371293266574619', null, null)).toEqual(false);786 expect($.validator.methods['validate-cc-number']787 .call($.validator.prototype, '2221220000000003', null, null)).toEqual(true);788 expect($.validator.methods['validate-cc-number']789 .call($.validator.prototype, '2721220000000008', null, null)).toEqual(true);790 expect($.validator.methods['validate-cc-number']791 .call($.validator.prototype, '601109020000000003', null, null)).toEqual(true);792 expect($.validator.methods['validate-cc-number']793 .call($.validator.prototype, '6011111144444444', null, null)).toEqual(true);794 expect($.validator.methods['validate-cc-number']795 .call($.validator.prototype, '6011222233334444', null, null)).toEqual(true);796 expect($.validator.methods['validate-cc-number']797 .call($.validator.prototype, '6011522233334447', null, null)).toEqual(true);798 expect($.validator.methods['validate-cc-number']799 .call($.validator.prototype, '601174455555553', null, null)).toEqual(true);800 expect($.validator.methods['validate-cc-number']801 .call($.validator.prototype, '6011745555555550', null, null)).toEqual(true);802 expect($.validator.methods['validate-cc-number']803 .call($.validator.prototype, '601177455555556', null, null)).toEqual(true);804 expect($.validator.methods['validate-cc-number']805 .call($.validator.prototype, '601182455555556', null, null)).toEqual(true);806 expect($.validator.methods['validate-cc-number']807 .call($.validator.prototype, '601187999555558', null, null)).toEqual(true);808 expect($.validator.methods['validate-cc-number']809 .call($.validator.prototype, '601287999555556', null, null)).toEqual(true);810 expect($.validator.methods['validate-cc-number']811 .call($.validator.prototype, '6444444444444443', null, null)).toEqual(true);812 expect($.validator.methods['validate-cc-number']813 .call($.validator.prototype, '6644444444444441', null, null)).toEqual(true);814 expect($.validator.methods['validate-cc-number']815 .call($.validator.prototype, '3044444444444444', null, null)).toEqual(true);816 expect($.validator.methods['validate-cc-number']817 .call($.validator.prototype, '3064444444444449', null, null)).toEqual(true);818 expect($.validator.methods['validate-cc-number']819 .call($.validator.prototype, '3095444444444442', null, null)).toEqual(true);820 expect($.validator.methods['validate-cc-number']821 .call($.validator.prototype, '3096444444444441', null, null)).toEqual(true);822 expect($.validator.methods['validate-cc-number']823 .call($.validator.prototype, '3696444444444445', null, null)).toEqual(true);824 expect($.validator.methods['validate-cc-number']825 .call($.validator.prototype, '3796444444444444', null, null)).toEqual(true);826 expect($.validator.methods['validate-cc-number']827 .call($.validator.prototype, '3896444444444443', null, null)).toEqual(true);828 expect($.validator.methods['validate-cc-number']829 .call($.validator.prototype, '3528444444444449', null, null)).toEqual(true);830 expect($.validator.methods['validate-cc-number']831 .call($.validator.prototype, '3529444444444448', null, null)).toEqual(true);832 expect($.validator.methods['validate-cc-number']833 .call($.validator.prototype, '6221262244444440', null, null)).toEqual(true);834 expect($.validator.methods['validate-cc-number']835 .call($.validator.prototype, '6229981111111111', null, null)).toEqual(true);836 expect($.validator.methods['validate-cc-number']837 .call($.validator.prototype, '6249981111111117', null, null)).toEqual(true);838 expect($.validator.methods['validate-cc-number']839 .call($.validator.prototype, '6279981111111110', null, null)).toEqual(true);840 expect($.validator.methods['validate-cc-number']841 .call($.validator.prototype, '6282981111111115', null, null)).toEqual(true);842 expect($.validator.methods['validate-cc-number']843 .call($.validator.prototype, '6289981111111118', null, null)).toEqual(true);844 });845 });846 describe('Testing validate-cc-type', function () {847 it('validate-cc-type', function () {848 var select = $('<select id="cc-type">' +849 '<option value="">' +850 '</option><option value="VI">' +851 '</option><option value="MC">' +852 '</option><option value="AE">' +853 '</option><option value="DI">' +854 '</option><option value="DN">' +855 '</option><option value="JCB">' +856 '</option><option value="UP">' +857 '</option>' +858 '</select>');859 select.val('VI');860 expect($.validator.methods['validate-cc-type']861 .call($.validator.prototype, '4916835098995909', null, select)).toEqual(true);862 expect($.validator.methods['validate-cc-type']863 .call($.validator.prototype, '5265071363284878', null, select)).toEqual(false);864 select.val('MC');865 expect($.validator.methods['validate-cc-type']866 .call($.validator.prototype, '5265071363284878', null, select)).toEqual(true);867 expect($.validator.methods['validate-cc-type']868 .call($.validator.prototype, '4916835098995909', null, select)).toEqual(false);869 select.val('AE');870 expect($.validator.methods['validate-cc-type']871 .call($.validator.prototype, '371293266574617', null, select)).toEqual(true);872 expect($.validator.methods['validate-cc-type']873 .call($.validator.prototype, '5265071363284878', null, select)).toEqual(false);874 select.val('DI');875 expect($.validator.methods['validate-cc-type']876 .call($.validator.prototype, '6011050000000009', null, select)).toEqual(true);877 expect($.validator.methods['validate-cc-type']878 .call($.validator.prototype, '371293266574617', null, select)).toEqual(false);879 select.val('DN');880 expect($.validator.methods['validate-cc-type']881 .call($.validator.prototype, '3095434000000001', null, select)).toEqual(true);882 expect($.validator.methods['validate-cc-type']883 .call($.validator.prototype, '6011050000000009', null, select)).toEqual(false);884 select.val('JCB');885 expect($.validator.methods['validate-cc-type']886 .call($.validator.prototype, '3528000000000007', null, select)).toEqual(true);887 expect($.validator.methods['validate-cc-type']888 .call($.validator.prototype, '3095434000000001', null, select)).toEqual(false);889 });890 });891 describe('Testing validate-cc-exp', function () {892 it('validate-cc-exp', function () {893 var year = $('<input id="year" type="text" value="4916808263499650"/>'),894 currentTime = new Date(),895 currentMonth = currentTime.getMonth() + 1,896 currentYear = currentTime.getFullYear();897 year.val(currentYear);898 if (currentMonth > 1) {899 expect($.validator.methods['validate-cc-exp']900 .call($.validator.prototype, currentMonth - 1, null, year)).toEqual(false);901 }902 expect($.validator.methods['validate-cc-exp']903 .call($.validator.prototype, currentMonth, null, year)).toEqual(true);904 year.val(currentYear + 1);905 expect($.validator.methods['validate-cc-exp']906 .call($.validator.prototype, currentMonth, null, year)).toEqual(true);907 });908 });909 describe('Testing validate-cc-cvn', function () {910 it('validate-cc-cvn', function () {911 var ccType = $('<select id="cc-type">' +912 '<option value=""></option>' +913 '<option value="VI"></option>' +914 '<option value="MC"></option>' +915 '<option value="AE"></option>' +916 '<option value="DI"></option>' +917 '</select>');918 ccType.val('VI');919 expect($.validator.methods['validate-cc-cvn']920 .call($.validator.prototype, '123', null, ccType)).toEqual(true);921 expect($.validator.methods['validate-cc-cvn']922 .call($.validator.prototype, '1234', null, ccType)).toEqual(false);923 ccType.val('MC');924 expect($.validator.methods['validate-cc-cvn']925 .call($.validator.prototype, '123', null, ccType)).toEqual(true);926 expect($.validator.methods['validate-cc-cvn']927 .call($.validator.prototype, '1234', null, ccType)).toEqual(false);928 ccType.val('AE');929 expect($.validator.methods['validate-cc-cvn']930 .call($.validator.prototype, '1234', null, ccType)).toEqual(true);931 expect($.validator.methods['validate-cc-cvn']932 .call($.validator.prototype, '123', null, ccType)).toEqual(false);933 ccType.val('DI');934 expect($.validator.methods['validate-cc-cvn']935 .call($.validator.prototype, '123', null, ccType)).toEqual(true);936 expect($.validator.methods['validate-cc-cvn']937 .call($.validator.prototype, '1234', null, ccType)).toEqual(false);938 });939 });940 describe('Testing validate-number-range', function () {941 it('validate-number-range', function () {942 var el1 = $('<input type="text" value="" ' +943 'class="validate-number-range number-range-10-20 number-range-10-100.20">').get(0);944 expect($.validator.methods['validate-number-range']945 .call($.validator.prototype, '-1', null, null)).toEqual(true);946 expect($.validator.methods['validate-number-range']947 .call($.validator.prototype, '1', null, null)).toEqual(true);948 expect($.validator.methods['validate-number-range']949 .call($.validator.prototype, '', null, null)).toEqual(true);950 expect($.validator.methods['validate-number-range']951 .call($.validator.prototype, null, null, null)).toEqual(true);952 expect($.validator.methods['validate-number-range']953 .call($.validator.prototype, '0', null, null)).toEqual(true);954 expect($.validator.methods['validate-number-range']955 .call($.validator.prototype, 'asds', null, null)).toEqual(false);956 expect($.validator.methods['validate-number-range']957 .call($.validator.prototype, '10', null, '10-20.06')).toEqual(true);958 expect($.validator.methods['validate-number-range']959 .call($.validator.prototype, '15', null, '10-20.06')).toEqual(true);960 expect($.validator.methods['validate-number-range']961 .call($.validator.prototype, '1', null, '10-20.06')).toEqual(false);962 expect($.validator.methods['validate-number-range']963 .call($.validator.prototype, '30', null, '10-20.06')).toEqual(false);964 expect($.validator.methods['validate-number-range']965 .call($.validator.prototype, '10', el1, null)).toEqual(true);966 expect($.validator.methods['validate-number-range']967 .call($.validator.prototype, '15', el1, null)).toEqual(true);968 expect($.validator.methods['validate-number-range']969 .call($.validator.prototype, '1', el1, null)).toEqual(false);970 expect($.validator.methods['validate-number-range']971 .call($.validator.prototype, '30', el1, null)).toEqual(true);972 });973 });974 describe('Testing validate-digits-range', function () {975 it('validate-digits-range', function () {976 var el1 = $('<input type="text" value="" ' +977 'class="validate-digits-range digits-range-10-20 digits-range-10-100.20">').get(0);978 expect($.validator.methods['validate-digits-range']979 .call($.validator.prototype, '-1', null, null)).toEqual(true);980 expect($.validator.methods['validate-digits-range']981 .call($.validator.prototype, '1', null, null)).toEqual(true);982 expect($.validator.methods['validate-digits-range']983 .call($.validator.prototype, '', null, null)).toEqual(true);984 expect($.validator.methods['validate-digits-range']985 .call($.validator.prototype, null, null, null)).toEqual(true);986 expect($.validator.methods['validate-digits-range']987 .call($.validator.prototype, '0', null, null)).toEqual(true);988 expect($.validator.methods['validate-digits-range']989 .call($.validator.prototype, 'asds', null, null)).toEqual(false);990 expect($.validator.methods['validate-digits-range']991 .call($.validator.prototype, '10', null, '10-20')).toEqual(true);992 expect($.validator.methods['validate-digits-range']993 .call($.validator.prototype, '15', null, '10-20')).toEqual(true);994 expect($.validator.methods['validate-digits-range']995 .call($.validator.prototype, '1', null, '10-20')).toEqual(false);996 expect($.validator.methods['validate-digits-range']997 .call($.validator.prototype, '30', null, '10-20')).toEqual(false);998 expect($.validator.methods['validate-digits-range']999 .call($.validator.prototype, '30', null, '10-20.06')).toEqual(false);1000 expect($.validator.methods['validate-digits-range']1001 .call($.validator.prototype, '10', el1, null)).toEqual(true);1002 expect($.validator.methods['validate-digits-range']1003 .call($.validator.prototype, '15', el1, null)).toEqual(true);1004 expect($.validator.methods['validate-digits-range']1005 .call($.validator.prototype, '1', el1, null)).toEqual(false);1006 expect($.validator.methods['validate-digits-range']1007 .call($.validator.prototype, '30', el1, null)).toEqual(false);1008 });1009 });1010 describe('Testing 3 bytes characters only policy (UTF-8)', function () {1011 it('rejects data, if any of the characters cannot be stored using UTF-8 collation', function () {1012 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1013 $.validator.prototype, 'ð
ð', null1014 )).toEqual(false);1015 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1016 $.validator.prototype, 'ð
test ð', null1017 )).toEqual(false);1018 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1019 $.validator.prototype, 'ð© ð» ð', null1020 )).toEqual(false);1021 });1022 it('approves data, if all the characters can be stored using UTF-8 collation', function () {1023 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1024 $.validator.prototype, '', null1025 )).toEqual(true);1026 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1027 $.validator.prototype, '!$-_%ç&#?!', null1028 )).toEqual(true);1029 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1030 $.validator.prototype, '1234567890', null1031 )).toEqual(true);1032 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1033 $.validator.prototype, ' ', null1034 )).toEqual(true);1035 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1036 $.validator.prototype, 'test', null1037 )).toEqual(true);1038 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1039 $.validator.prototype, 'иÑпÑÑание', null1040 )).toEqual(true);1041 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1042 $.validator.prototype, 'ÑеÑÑ', null1043 )).toEqual(true);1044 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1045 $.validator.prototype, 'ÖÕ¸ÖÕ±Õ¡ÖÕ¯Õ¸ÖÕ´', null1046 )).toEqual(true);1047 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1048 $.validator.prototype, 'परà¥à¤à¥à¤·à¤£', null1049 )).toEqual(true);1050 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1051 $.validator.prototype, 'ãã¹ã', null1052 )).toEqual(true);1053 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1054 $.validator.prototype, 'í
ì¤í¸', null1055 )).toEqual(true);1056 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1057 $.validator.prototype, 'æµè¯', null1058 )).toEqual(true);1059 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1060 $.validator.prototype, '測試', null1061 )).toEqual(true);1062 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1063 $.validator.prototype, 'à¸à¸à¸ªà¸à¸', null1064 )).toEqual(true);1065 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1066 $.validator.prototype, 'δοκιμή', null1067 )).toEqual(true);1068 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1069 $.validator.prototype, 'اختبار', null1070 )).toEqual(true);1071 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1072 $.validator.prototype, 'تست', null1073 )).toEqual(true);1074 expect($.validator.methods['validate-no-utf8mb4-characters'].call(1075 $.validator.prototype, '×Ö´×Ö°×Ö¸×', null1076 )).toEqual(true);1077 });1078 });1079 describe('Testing validate-forbidden-extensions', function () {1080 it('validate-forbidden-extensions', function () {1081 var el1 = $('<input type="text" value="" ' +1082 'class="validate-extensions" data-validation-params="php,phtml">').get(0);1083 expect($.validator.methods['validate-forbidden-extensions']1084 .call($.validator.prototype, 'php', el1, null)).toEqual(false);1085 expect($.validator.methods['validate-forbidden-extensions']1086 .call($.validator.prototype, 'php,phtml', el1, null)).toEqual(false);1087 expect($.validator.methods['validate-forbidden-extensions']1088 .call($.validator.prototype, 'html', el1, null)).toEqual(true);1089 expect($.validator.methods['validate-forbidden-extensions']1090 .call($.validator.prototype, 'html,png', el1, null)).toEqual(true);1091 expect($.validator.methods['validate-forbidden-extensions']1092 .call($.validator.prototype, 'php,html', el1, null)).toEqual(false);1093 expect($.validator.methods['validate-forbidden-extensions']1094 .call($.validator.prototype, 'html,php', el1, null)).toEqual(false);1095 });1096 });...
SKValidatingObjectTests.js
Source:SKValidatingObjectTests.js
1// Copyright 2020 Breakside Inc.2//3// Licensed under the Breakside Public License, Version 1.0 (the "License");4// you may not use this file except in compliance with the License.5// If a copy of the License was not distributed with this file, you may6// obtain a copy at7//8// http://breakside.io/licenses/LICENSE-1.0.txt9//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15// #import ServerKit16// #import TestKit17'use strict';18JSClass("SKValidatingObjectTests", TKTestSuite, {19 testObjectStringForKey: function(){20 var input = {21 stringKey: "testing",22 numberKey: 1.2,23 boolKey: true,24 nullKey: null,25 undefinedKey: undefined,26 arrayKey: ["zero", 1, 2, 3],27 objectKey: {stringKey: "one", numberKey: 2}28 };29 var validator = SKValidatingObject.initWithObject(input);30 var result = validator.stringForKey("stringKey");31 TKAssertEquals(result, "testing");32 result = validator.stringForKey("missingKey", "test");33 TKAssertEquals(result, "test");34 result = validator.stringForKey("missingKey", null);35 TKAssertNull(result);36 TKAssertThrows(function(){ validator.stringForKey("missingKey"); });37 TKAssertThrows(function(){ validator.stringForKey("numberKey"); });38 TKAssertThrows(function(){ validator.stringForKey("boolKey"); });39 TKAssertThrows(function(){ validator.stringForKey("nullKey"); });40 TKAssertThrows(function(){ validator.stringForKey("undefinedKey"); });41 TKAssertThrows(function(){ validator.stringForKey("arrayKey"); });42 TKAssertThrows(function(){ validator.stringForKey("objectKey"); });43 var customValidatorCalls = 0;44 result = validator.stringForKey("stringKey", null, function(value){45 ++customValidatorCalls;46 TKAssertEquals(value, "testing");47 });48 TKAssertEquals(customValidatorCalls, 1);49 customValidatorCalls = 0;50 result = validator.stringForKey("missingKey", null, function(value){51 ++customValidatorCalls;52 });53 TKAssertEquals(customValidatorCalls, 0);54 },55 testObjectStringForKeyInLengthRange: function(){56 var input = {57 stringKey: "testing",58 numberKey: 1.2,59 boolKey: true,60 nullKey: null,61 undefinedKey: undefined,62 arrayKey: ["zero", 1, 2, 3],63 objectKey: {stringKey: "one", numberKey: 2}64 };65 var validator = SKValidatingObject.initWithObject(input);66 var result = validator.stringForKeyInLengthRange("stringKey", 5, 10);67 TKAssertEquals(result, "testing");68 result = validator.stringForKeyInLengthRange("stringKey", 5);69 TKAssertEquals(result, "testing");70 result = validator.stringForKeyInLengthRange("stringKey", undefined, 10);71 TKAssertEquals(result, "testing");72 result = validator.stringForKeyInLengthRange("missingKey", 5, 10, "test");73 TKAssertEquals(result, "test");74 result = validator.stringForKeyInLengthRange("missingKey", 5, 10, null);75 TKAssertNull(result);76 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("missingKey"); });77 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("numberKey"); });78 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("boolKey"); });79 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("nullKey"); });80 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("undefinedKey"); });81 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("arrayKey"); });82 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("objectKey"); });83 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("stringKey", 10); });84 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("stringKey", 0, 5); });85 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("stringKey", undefined, 5); });86 },87 testObjectEmailForKey: function(){88 var input = {email: "test@breakside.io"};89 var validator = SKValidatingObject.initWithObject(input);90 var result = validator.emailForKey("email");91 TKAssertEquals(result, "test@breakside.io");92 input = {email: "test@breakside"};93 validator = SKValidatingObject.initWithObject(input);94 result = validator.emailForKey("missing", "test");95 TKAssertEquals(result, "test");96 input = {email: "test@breakside"};97 validator = SKValidatingObject.initWithObject(input);98 result = validator.emailForKey("missing", null);99 TKAssertNull(result);100 input = {email: "test@breakside"};101 validator = SKValidatingObject.initWithObject(input);102 result = validator.emailForKey("email");103 TKAssertEquals(result, "test@breakside");104 input = {email: "test+1@breakside"};105 validator = SKValidatingObject.initWithObject(input);106 result = validator.emailForKey("email");107 TKAssertEquals(result, "test+1@breakside");108 input = {email: "test.1@breakside"};109 validator = SKValidatingObject.initWithObject(input);110 result = validator.emailForKey("email");111 TKAssertEquals(result, "test.1@breakside");112 input = {email: "test-1@breakside"};113 validator = SKValidatingObject.initWithObject(input);114 result = validator.emailForKey("email");115 TKAssertEquals(result, "test-1@breakside");116 input = {email: "123@breakside"};117 validator = SKValidatingObject.initWithObject(input);118 result = validator.emailForKey("email");119 TKAssertEquals(result, "123@breakside");120 input = {email: "123@456"};121 validator = SKValidatingObject.initWithObject(input);122 result = validator.emailForKey("email");123 TKAssertEquals(result, "123@456");124 input = {email: "test"};125 validator = SKValidatingObject.initWithObject(input);126 TKAssertThrows(function(){ validator.emailForKey("email"); });127 input = {email: "test@"};128 validator = SKValidatingObject.initWithObject(input);129 TKAssertThrows(function(){ validator.emailForKey("email"); });130 input = {email: "@breakside"};131 validator = SKValidatingObject.initWithObject(input);132 TKAssertThrows(function(){ validator.emailForKey("email"); });133 input = {email: "test@breakside."};134 validator = SKValidatingObject.initWithObject(input);135 TKAssertThrows(function(){ validator.emailForKey("email"); });136 input = {email: "test@breakside.io."};137 validator = SKValidatingObject.initWithObject(input);138 TKAssertThrows(function(){ validator.emailForKey("email"); });139 input = {email: "te st@breakside.io."};140 validator = SKValidatingObject.initWithObject(input);141 TKAssertThrows(function(){ validator.emailForKey("email"); });142 input = {email: "test@break side.io"};143 validator = SKValidatingObject.initWithObject(input);144 TKAssertThrows(function(){ validator.emailForKey("email"); });145 input = {email: " test@breakside.io"};146 validator = SKValidatingObject.initWithObject(input);147 TKAssertThrows(function(){ validator.emailForKey("email"); });148 input = {email: "test@breakside.io "};149 validator = SKValidatingObject.initWithObject(input);150 TKAssertThrows(function(){ validator.emailForKey("email"); });151 },152 testObjectPhoneForKey: function(){153 var input = {phone: "(234) 567-8901"};154 var validator = SKValidatingObject.initWithObject(input);155 var result = validator.phoneForKey("phone");156 TKAssertEquals(result, "(234) 567-8901");157 input = {phone: "234-567-8901"};158 validator = SKValidatingObject.initWithObject(input);159 result = validator.phoneForKey("phone");160 TKAssertEquals(result, "234-567-8901");161 input = {phone: "234-567-8901"};162 validator = SKValidatingObject.initWithObject(input);163 result = validator.phoneForKey("missing", "test");164 TKAssertEquals(result, "test");165 input = {phone: "234-567-8901"};166 validator = SKValidatingObject.initWithObject(input);167 result = validator.phoneForKey("missing", null);168 TKAssertNull(result);169 input = {phone: "234 567 8901"};170 validator = SKValidatingObject.initWithObject(input);171 result = validator.phoneForKey("phone");172 TKAssertEquals(result, "234 567 8901");173 input = {phone: "234.567.8901"};174 validator = SKValidatingObject.initWithObject(input);175 result = validator.phoneForKey("phone");176 TKAssertEquals(result, "234.567.8901");177 input = {phone: "+1 234-567-8901"};178 validator = SKValidatingObject.initWithObject(input);179 result = validator.phoneForKey("phone");180 TKAssertEquals(result, "+1 234-567-8901");181 input = {phone: "2345678"};182 validator = SKValidatingObject.initWithObject(input);183 result = validator.phoneForKey("phone");184 TKAssertEquals(result, "2345678");185 input = {phone: "234567890123456"};186 validator = SKValidatingObject.initWithObject(input);187 result = validator.phoneForKey("phone");188 TKAssertEquals(result, "234567890123456");189 input = {phone: "2"};190 validator = SKValidatingObject.initWithObject(input);191 TKAssertThrows(function(){ validator.phoneForKey("phone"); });192 input = {phone: "23"};193 validator = SKValidatingObject.initWithObject(input);194 TKAssertThrows(function(){ validator.phoneForKey("phone"); });195 input = {phone: "234"};196 validator = SKValidatingObject.initWithObject(input);197 TKAssertThrows(function(){ validator.phoneForKey("phone"); });198 input = {phone: "2345"};199 validator = SKValidatingObject.initWithObject(input);200 TKAssertThrows(function(){ validator.phoneForKey("phone"); });201 input = {phone: "23456"};202 validator = SKValidatingObject.initWithObject(input);203 TKAssertThrows(function(){ validator.phoneForKey("phone"); });204 input = {phone: "234567"};205 validator = SKValidatingObject.initWithObject(input);206 TKAssertThrows(function(){ validator.phoneForKey("phone"); });207 input = {phone: "234+5678"};208 validator = SKValidatingObject.initWithObject(input);209 TKAssertThrows(function(){ validator.phoneForKey("phone"); });210 input = {phone: "2345678901234567"};211 validator = SKValidatingObject.initWithObject(input);212 TKAssertThrows(function(){ validator.phoneForKey("phone"); });213 input = {phone: "a 234 567 8901"};214 validator = SKValidatingObject.initWithObject(input);215 TKAssertThrows(function(){ validator.phoneForKey("phone"); });216 },217 testObjectNumberForKey: function(){218 var input = {219 stringKey: "testing",220 numberKey: 1.2,221 boolKey: true,222 nullKey: null,223 undefinedKey: undefined,224 arrayKey: ["zero", 1, 2, 3],225 objectKey: {stringKey: "one", numberKey: 2}226 };227 var validator = SKValidatingObject.initWithObject(input);228 var result = validator.numberForKey("numberKey");229 TKAssertFloatEquals(result, 1.2);230 result = validator.numberForKey("missingKey", 5);231 TKAssertEquals(result, 5);232 result = validator.numberForKey("missingKey", null);233 TKAssertNull(result);234 TKAssertThrows(function(){ validator.numberForKey("missingKey"); });235 TKAssertThrows(function(){ validator.numberForKey("stringKey"); });236 TKAssertThrows(function(){ validator.numberForKey("boolKey"); });237 TKAssertThrows(function(){ validator.numberForKey("nullKey"); });238 TKAssertThrows(function(){ validator.numberForKey("undefinedKey"); });239 TKAssertThrows(function(){ validator.numberForKey("arrayKey"); });240 TKAssertThrows(function(){ validator.numberForKey("objectKey"); });241 var customValidatorCalls = 0;242 result = validator.numberForKey("numberKey", null, function(value){243 ++customValidatorCalls;244 TKAssertFloatEquals(value, 1.2);245 });246 TKAssertEquals(customValidatorCalls, 1);247 customValidatorCalls = 0;248 result = validator.numberForKey("missingKey", null, function(value){249 ++customValidatorCalls;250 });251 TKAssertEquals(customValidatorCalls, 0);252 },253 testObjectNumberForKeyInRange: function(){254 var input = {255 stringKey: "testing",256 numberKey: 1.2,257 boolKey: true,258 nullKey: null,259 undefinedKey: undefined,260 arrayKey: ["zero", 1, 2, 3],261 objectKey: {stringKey: "one", numberKey: 2}262 };263 var validator = SKValidatingObject.initWithObject(input);264 var result = validator.numberForKeyInRange("numberKey", 0, 10);265 TKAssertFloatEquals(result, 1.2);266 result = validator.numberForKeyInRange("numberKey", 0);267 TKAssertFloatEquals(result, 1.2);268 result = validator.numberForKeyInRange("numberKey", undefined, 10);269 TKAssertFloatEquals(result, 1.2);270 result = validator.numberForKeyInRange("missingKey", 0, 10, 15);271 TKAssertEquals(result, 15);272 result = validator.numberForKeyInRange("missingKey", 0, 10, null);273 TKAssertNull(result);274 TKAssertThrows(function(){ validator.numberForKeyInRange("missingKey"); });275 TKAssertThrows(function(){ validator.numberForKeyInRange("stringKey"); });276 TKAssertThrows(function(){ validator.numberForKeyInRange("boolKey"); });277 TKAssertThrows(function(){ validator.numberForKeyInRange("nullKey"); });278 TKAssertThrows(function(){ validator.numberForKeyInRange("undefinedKey"); });279 TKAssertThrows(function(){ validator.numberForKeyInRange("arrayKey"); });280 TKAssertThrows(function(){ validator.numberForKeyInRange("objectKey"); });281 TKAssertThrows(function(){ validator.numberForKeyInRange("numberKey", 2); });282 TKAssertThrows(function(){ validator.numberForKeyInRange("numberKey", 0, 1); });283 TKAssertThrows(function(){ validator.numberForKeyInRange("numberKey", undefined, 1); });284 },285 testObjectIntegerForKey: function(){286 var input = {287 stringKey: "testing",288 numberKey: 1.2,289 integerKey: 12,290 boolKey: true,291 nullKey: null,292 undefinedKey: undefined,293 arrayKey: ["zero", 1, 2, 3],294 objectKey: {stringKey: "one", numberKey: 2}295 };296 var validator = SKValidatingObject.initWithObject(input);297 var result = validator.integerForKey("integerKey");298 TKAssertEquals(result, 12);299 result = validator.integerForKey("missingKey", 5);300 TKAssertEquals(result, 5);301 result = validator.integerForKey("missingKey", null);302 TKAssertNull(result);303 TKAssertThrows(function(){ validator.integerForKey("missingKey"); });304 TKAssertThrows(function(){ validator.integerForKey("numberKey"); });305 TKAssertThrows(function(){ validator.integerForKey("stringKey"); });306 TKAssertThrows(function(){ validator.integerForKey("boolKey"); });307 TKAssertThrows(function(){ validator.integerForKey("nullKey"); });308 TKAssertThrows(function(){ validator.integerForKey("undefinedKey"); });309 TKAssertThrows(function(){ validator.integerForKey("arrayKey"); });310 TKAssertThrows(function(){ validator.integerForKey("objectKey"); });311 var customValidatorCalls = 0;312 result = validator.integerForKey("integerKey", null, function(value){313 ++customValidatorCalls;314 TKAssertEquals(value, 12);315 });316 TKAssertEquals(customValidatorCalls, 1);317 customValidatorCalls = 0;318 result = validator.integerForKey("missingKey", null, function(value){319 ++customValidatorCalls;320 });321 TKAssertEquals(customValidatorCalls, 0);322 },323 testObjectIntegerForKeyInRange: function(){324 var input = {325 stringKey: "testing",326 numberKey: 1.2,327 integerKey: 12,328 boolKey: true,329 nullKey: null,330 undefinedKey: undefined,331 arrayKey: ["zero", 1, 2, 3],332 objectKey: {stringKey: "one", numberKey: 2}333 };334 var validator = SKValidatingObject.initWithObject(input);335 var result = validator.integerForKeyInRange("integerKey", 0, 20);336 TKAssertEquals(result, 12);337 result = validator.integerForKeyInRange("integerKey", 0);338 TKAssertEquals(result, 12);339 result = validator.integerForKeyInRange("integerKey", undefined, 20);340 TKAssertEquals(result, 12);341 result = validator.integerForKeyInRange("missingKey", 0, 10, 15);342 TKAssertEquals(result, 15);343 result = validator.integerForKeyInRange("missingKey", 0, 10, null);344 TKAssertNull(result);345 TKAssertThrows(function(){ validator.integerForKeyInRange("missingKey"); });346 TKAssertThrows(function(){ validator.integerForKeyInRange("stringKey"); });347 TKAssertThrows(function(){ validator.integerForKeyInRange("numberKey"); });348 TKAssertThrows(function(){ validator.integerForKeyInRange("boolKey"); });349 TKAssertThrows(function(){ validator.integerForKeyInRange("nullKey"); });350 TKAssertThrows(function(){ validator.integerForKeyInRange("undefinedKey"); });351 TKAssertThrows(function(){ validator.integerForKeyInRange("arrayKey"); });352 TKAssertThrows(function(){ validator.integerForKeyInRange("objectKey"); });353 TKAssertThrows(function(){ validator.integerForKeyInRange("integerKey", 20); });354 TKAssertThrows(function(){ validator.integerForKeyInRange("integerKey", 0, 10); });355 TKAssertThrows(function(){ validator.integerForKeyInRange("integerKey", undefined, 10); });356 },357 testObjectBooleanForKey: function(){358 var input = {359 stringKey: "testing",360 numberKey: 1.2,361 boolKey: true,362 nullKey: null,363 undefinedKey: undefined,364 arrayKey: ["zero", 1, 2, 3],365 objectKey: {stringKey: "one", numberKey: 2}366 };367 var validator = SKValidatingObject.initWithObject(input);368 var result = validator.booleanForKey("boolKey");369 TKAssertExactEquals(result, true);370 result = validator.booleanForKey("missingKey", false);371 TKAssertExactEquals(result, false);372 result = validator.booleanForKey("missingKey", null);373 TKAssertNull(result);374 TKAssertThrows(function(){ validator.booleanForKey("missingKey"); });375 TKAssertThrows(function(){ validator.booleanForKey("stringKey"); });376 TKAssertThrows(function(){ validator.booleanForKey("numberKey"); });377 TKAssertThrows(function(){ validator.booleanForKey("nullKey"); });378 TKAssertThrows(function(){ validator.booleanForKey("undefinedKey"); });379 TKAssertThrows(function(){ validator.booleanForKey("arrayKey"); });380 TKAssertThrows(function(){ validator.booleanForKey("objectKey"); });381 },382 testObjectObjectForKey: function(){383 var input = {384 stringKey: "testing",385 numberKey: 1.2,386 boolKey: true,387 nullKey: null,388 undefinedKey: undefined,389 arrayKey: ["zero", 1, 2, 3],390 objectKey: {stringKey: "one", numberKey: 2}391 };392 var validator = SKValidatingObject.initWithObject(input);393 var result = validator.objectForKey("objectKey");394 TKAssert(result instanceof SKValidatingObject);395 var result2 = result.stringForKey("stringKey");396 TKAssertEquals(result2, "one");397 result2 = result.numberForKey("numberKey");398 TKAssertEquals(result2, 2);399 result = validator.objectForKey("missingKey", null);400 TKAssertNull(result);401 TKAssertThrows(function(){ validator.objectForKey("missingKey"); });402 TKAssertThrows(function(){ validator.objectForKey("stringKey"); });403 TKAssertThrows(function(){ validator.objectForKey("numberKey"); });404 TKAssertThrows(function(){ validator.objectForKey("nullKey"); });405 TKAssertThrows(function(){ validator.objectForKey("undefinedKey"); });406 TKAssertThrows(function(){ validator.objectForKey("arrayKey"); });407 TKAssertThrows(function(){ validator.objectForKey("boolKey"); });408 },409 testObjectGetKeys: function(){410 var input = {411 stringKey: "testing",412 numberKey: 1.2,413 boolKey: true414 };415 var validator = SKValidatingObject.initWithObject(input);416 var keys = validator.getKeys();417 TKAssertEquals(keys.length, 3);418 TKAssertEquals(keys[0], "stringKey");419 TKAssertEquals(keys[1], "numberKey");420 TKAssertEquals(keys[2], "boolKey");421 },422 testObjectArrayForKey: function(){423 var input = {424 stringKey: "testing",425 numberKey: 1.2,426 boolKey: true,427 nullKey: null,428 undefinedKey: undefined,429 arrayKey: ["zero", 1, 2, 3],430 objectKey: {stringKey: "one", numberKey: 2}431 };432 var validator = SKValidatingObject.initWithObject(input);433 var result = validator.arrayForKey("arrayKey");434 TKAssert(result instanceof SKValidatingObject);435 TKAssertEquals(result.length, 4);436 var result2 = result.stringForKey(0);437 TKAssertEquals(result2, "zero");438 result2 = result.numberForKey(1);439 TKAssertEquals(result2, 1);440 result = validator.arrayForKey("missingKey", null);441 TKAssertNull(result);442 TKAssertThrows(function(){ validator.arrayForKey("missingKey"); });443 TKAssertThrows(function(){ validator.arrayForKey("stringKey"); });444 TKAssertThrows(function(){ validator.arrayForKey("numberKey"); });445 TKAssertThrows(function(){ validator.arrayForKey("nullKey"); });446 TKAssertThrows(function(){ validator.arrayForKey("undefinedKey"); });447 TKAssertThrows(function(){ validator.arrayForKey("objectKey"); });448 TKAssertThrows(function(){ validator.arrayForKey("boolKey"); });449 },450 testObjectBase64DataForKey: function(){451 var input = {data: JSData.initWithArray([0,1,2,3]).base64StringRepresentation()};452 var validator = SKValidatingObject.initWithObject(input);453 var result = validator.base64DataForKey("data");454 TKAssert(result instanceof JSData);455 TKAssertEquals(result.length, 4);456 TKAssertEquals(result[0], 0);457 TKAssertEquals(result[1], 1);458 TKAssertEquals(result[2], 2);459 TKAssertEquals(result[3], 3);460 validator = SKValidatingObject.initWithObject(input);461 var fallback = JSData.initWithLength(0);462 result = validator.base64DataForKey("missing", fallback);463 TKAssertExactEquals(result, fallback);464 TKAssertThrows(function(){465 var input = {data: "not!base64"};466 var validator = SKValidatingObject.initWithObject(input);467 var result = validator.base64DataForKey("data");468 });469 },470 testObjectBase64URLDataForKey: function(){471 var input = {data: JSData.initWithArray([0,1,2,3]).base64URLStringRepresentation()};472 var validator = SKValidatingObject.initWithObject(input);473 var result = validator.base64URLDataForKey("data");474 TKAssert(result instanceof JSData);475 TKAssertEquals(result.length, 4);476 TKAssertEquals(result[0], 0);477 TKAssertEquals(result[1], 1);478 TKAssertEquals(result[2], 2);479 TKAssertEquals(result[3], 3);480 validator = SKValidatingObject.initWithObject(input);481 var fallback = JSData.initWithLength(0);482 result = validator.base64URLDataForKey("missing", fallback);483 TKAssertExactEquals(result, fallback);484 TKAssertThrows(function(){485 var input = {data: "not!base64url"};486 var validator = SKValidatingObject.initWithObject(input);487 var result = validator.base64URLDataForKey("data");488 });489 },490 testFormStringForKey: function(){491 var input = JSFormFieldMap();492 input.add("stringKey", "testing");493 input.add("numberKey", "1.2");494 input.add("integerKey", "12");495 input.add("boolKey", "true");496 input.add("nullKey", null);497 input.add("arrayKey", "zero");498 input.add("arrayKey", "1");499 input.add("arrayKey", "2");500 input.add("arrayKey", "3");501 var validator = SKValidatingObject.initWithForm(input);502 var result = validator.stringForKey("stringKey");503 TKAssertExactEquals(result, "testing");504 result = validator.stringForKey("missingKey", "test");505 TKAssertExactEquals(result, "test");506 result = validator.stringForKey("missingKey", null);507 TKAssertNull(result);508 result = validator.stringForKey("numberKey");509 TKAssertExactEquals(result, "1.2");510 result = validator.stringForKey("boolKey");511 TKAssertExactEquals(result, "true");512 TKAssertThrows(function(){ validator.stringForKey("missingKey"); });513 TKAssertThrows(function(){ validator.stringForKey("arrayKey"); });514 TKAssertThrows(function(){ validator.stringForKey("nullKey"); });515 var customValidatorCalls = 0;516 result = validator.stringForKey("stringKey", null, function(value){517 ++customValidatorCalls;518 TKAssertEquals(value, "testing");519 });520 TKAssertEquals(customValidatorCalls, 1);521 customValidatorCalls = 0;522 result = validator.stringForKey("missingKey", null, function(value){523 ++customValidatorCalls;524 });525 TKAssertEquals(customValidatorCalls, 0);526 },527 testFormStringForKeyInLengthRange: function(){528 var input = JSFormFieldMap();529 input.add("stringKey", "testing");530 input.add("numberKey", "1.2");531 input.add("integerKey", "12");532 input.add("boolKey", "true");533 input.add("nullKey", null);534 input.add("arrayKey", "zero");535 input.add("arrayKey", "1");536 input.add("arrayKey", "2");537 input.add("arrayKey", "3");538 var validator = SKValidatingObject.initWithForm(input);539 var result = validator.stringForKeyInLengthRange("stringKey", 5, 10);540 TKAssertEquals(result, "testing");541 result = validator.stringForKeyInLengthRange("stringKey", 5);542 TKAssertEquals(result, "testing");543 result = validator.stringForKeyInLengthRange("stringKey", undefined, 10);544 TKAssertEquals(result, "testing");545 result = validator.stringForKeyInLengthRange("missingKey", 5, 10, "test");546 TKAssertEquals(result, "test");547 result = validator.stringForKeyInLengthRange("missingKey", 5, 10, null);548 TKAssertNull(result);549 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("missingKey"); });550 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("nullKey"); });551 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("arrayKey"); });552 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("objectKey"); });553 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("stringKey", 10); });554 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("stringKey", 0, 5); });555 TKAssertThrows(function(){ validator.stringForKeyInLengthRange("stringKey", undefined, 5); });556 },557 testFormEmailForKey: function(){558 var input = JSFormFieldMap();559 input.add("email", "test@breakside.io");560 var validator = SKValidatingObject.initWithForm(input);561 var result = validator.emailForKey("email");562 TKAssertEquals(result, "test@breakside.io");563 input = JSFormFieldMap();564 input.add("email", "test@breakside");565 validator = SKValidatingObject.initWithForm(input);566 result = validator.emailForKey("missing", "test");567 TKAssertEquals(result, "test");568 input = JSFormFieldMap();569 input.add("email", "test@breakside");570 validator = SKValidatingObject.initWithForm(input);571 result = validator.emailForKey("missing", null);572 TKAssertNull(result);573 input = JSFormFieldMap();574 input.add("email", "test@breakside");575 validator = SKValidatingObject.initWithForm(input);576 result = validator.emailForKey("email");577 TKAssertEquals(result, "test@breakside");578 input = JSFormFieldMap();579 input.add("email", "test+1@breakside");580 validator = SKValidatingObject.initWithForm(input);581 result = validator.emailForKey("email");582 TKAssertEquals(result, "test+1@breakside");583 input = JSFormFieldMap();584 input.add("email", "test.1@breakside");585 validator = SKValidatingObject.initWithForm(input);586 result = validator.emailForKey("email");587 TKAssertEquals(result, "test.1@breakside");588 input = JSFormFieldMap();589 input.add("email", "test-1@breakside");590 validator = SKValidatingObject.initWithForm(input);591 result = validator.emailForKey("email");592 TKAssertEquals(result, "test-1@breakside");593 input = JSFormFieldMap();594 input.add("email", "123@breakside");595 validator = SKValidatingObject.initWithForm(input);596 result = validator.emailForKey("email");597 TKAssertEquals(result, "123@breakside");598 input = JSFormFieldMap();599 input.add("email", "123@456");600 validator = SKValidatingObject.initWithForm(input);601 result = validator.emailForKey("email");602 TKAssertEquals(result, "123@456");603 input = JSFormFieldMap();604 input.add("email", "test");605 validator = SKValidatingObject.initWithForm(input);606 TKAssertThrows(function(){ validator.emailForKey("email"); });607 input = JSFormFieldMap();608 input.add("email", "test@");609 validator = SKValidatingObject.initWithForm(input);610 TKAssertThrows(function(){ validator.emailForKey("email"); });611 input = JSFormFieldMap();612 input.add("email", "@breakside");613 validator = SKValidatingObject.initWithForm(input);614 TKAssertThrows(function(){ validator.emailForKey("email"); });615 input = JSFormFieldMap();616 input.add("email", "test@breakside.");617 validator = SKValidatingObject.initWithForm(input);618 TKAssertThrows(function(){ validator.emailForKey("email"); });619 input = JSFormFieldMap();620 input.add("email", "test@breakside.io.");621 validator = SKValidatingObject.initWithForm(input);622 TKAssertThrows(function(){ validator.emailForKey("email"); });623 input = JSFormFieldMap();624 input.add("email", "te st@breakside.io.");625 validator = SKValidatingObject.initWithForm(input);626 TKAssertThrows(function(){ validator.emailForKey("email"); });627 input = JSFormFieldMap();628 input.add("email", "test@break side.io");629 validator = SKValidatingObject.initWithForm(input);630 TKAssertThrows(function(){ validator.emailForKey("email"); });631 input = JSFormFieldMap();632 input.add("email", " test@breakside.io");633 validator = SKValidatingObject.initWithForm(input);634 TKAssertThrows(function(){ validator.emailForKey("email"); });635 input = JSFormFieldMap();636 input.add("email", "test@breakside.io ");637 validator = SKValidatingObject.initWithForm(input);638 TKAssertThrows(function(){ validator.emailForKey("email"); });639 },640 testFormPhoneForKey: function(){641 var input = JSFormFieldMap();642 input.add("phone", "(234) 567-8901");643 var validator = SKValidatingObject.initWithForm(input);644 var result = validator.phoneForKey("phone");645 TKAssertEquals(result, "(234) 567-8901");646 input = JSFormFieldMap();647 input.add("phone", "234-567-8901");648 validator = SKValidatingObject.initWithForm(input);649 result = validator.phoneForKey("phone");650 TKAssertEquals(result, "234-567-8901");651 input = JSFormFieldMap();652 input.add("phone", "234-567-8901");653 validator = SKValidatingObject.initWithForm(input);654 result = validator.phoneForKey("missing", "test");655 TKAssertEquals(result, "test");656 input = JSFormFieldMap();657 input.add("phone", "234-567-8901");658 validator = SKValidatingObject.initWithForm(input);659 result = validator.phoneForKey("missing", null);660 TKAssertNull(result);661 input = JSFormFieldMap();662 input.add("phone", "234 567 8901");663 validator = SKValidatingObject.initWithForm(input);664 result = validator.phoneForKey("phone");665 TKAssertEquals(result, "234 567 8901");666 input = JSFormFieldMap();667 input.add("phone", "234.567.8901");668 validator = SKValidatingObject.initWithForm(input);669 result = validator.phoneForKey("phone");670 TKAssertEquals(result, "234.567.8901");671 input = JSFormFieldMap();672 input.add("phone", "+1 234-567-8901");673 validator = SKValidatingObject.initWithForm(input);674 result = validator.phoneForKey("phone");675 TKAssertEquals(result, "+1 234-567-8901");676 input = JSFormFieldMap();677 input.add("phone", "2345678");678 validator = SKValidatingObject.initWithForm(input);679 result = validator.phoneForKey("phone");680 TKAssertEquals(result, "2345678");681 input = JSFormFieldMap();682 input.add("phone", "234567890123456");683 validator = SKValidatingObject.initWithForm(input);684 result = validator.phoneForKey("phone");685 TKAssertEquals(result, "234567890123456");686 input = JSFormFieldMap();687 input.add("phone", "2");688 validator = SKValidatingObject.initWithForm(input);689 TKAssertThrows(function(){ validator.phoneForKey("phone"); });690 input = JSFormFieldMap();691 input.add("phone", "23");692 validator = SKValidatingObject.initWithForm(input);693 TKAssertThrows(function(){ validator.phoneForKey("phone"); });694 input = JSFormFieldMap();695 input.add("phone", "234");696 validator = SKValidatingObject.initWithForm(input);697 TKAssertThrows(function(){ validator.phoneForKey("phone"); });698 input = JSFormFieldMap();699 input.add("phone", "2345");700 validator = SKValidatingObject.initWithForm(input);701 TKAssertThrows(function(){ validator.phoneForKey("phone"); });702 input = JSFormFieldMap();703 input.add("phone", "23456");704 validator = SKValidatingObject.initWithForm(input);705 TKAssertThrows(function(){ validator.phoneForKey("phone"); });706 input = JSFormFieldMap();707 input.add("phone", "234567");708 validator = SKValidatingObject.initWithForm(input);709 TKAssertThrows(function(){ validator.phoneForKey("phone"); });710 input = JSFormFieldMap();711 input.add("phone", "234+5678");712 validator = SKValidatingObject.initWithForm(input);713 TKAssertThrows(function(){ validator.phoneForKey("phone"); });714 input = JSFormFieldMap();715 input.add("phone", "2345678901234567");716 validator = SKValidatingObject.initWithForm(input);717 TKAssertThrows(function(){ validator.phoneForKey("phone"); });718 input = JSFormFieldMap();719 input.add("phone", "a 234 567 8901");720 validator = SKValidatingObject.initWithForm(input);721 TKAssertThrows(function(){ validator.phoneForKey("phone"); });722 },723 testFormNumberForKey: function(){724 var input = JSFormFieldMap();725 input.add("stringKey", "testing");726 input.add("numberKey", "1.2");727 input.add("integerKey", "12");728 input.add("boolKey", "true");729 input.add("nullKey", null);730 input.add("arrayKey", "zero");731 input.add("arrayKey", "1");732 input.add("arrayKey", "2");733 input.add("arrayKey", "3");734 var validator = SKValidatingObject.initWithForm(input);735 var result = validator.numberForKey("numberKey");736 TKAssertType(result, "number");737 TKAssertFloatEquals(result, 1.2);738 result = validator.numberForKey("missingKey", 5);739 TKAssertEquals(result, 5);740 result = validator.numberForKey("missingKey", null);741 TKAssertNull(result);742 TKAssertThrows(function(){ validator.numberForKey("missingKey"); });743 TKAssertThrows(function(){ validator.numberForKey("stringKey"); });744 TKAssertThrows(function(){ validator.numberForKey("boolKey"); });745 TKAssertThrows(function(){ validator.numberForKey("nullKey"); });746 TKAssertThrows(function(){ validator.numberForKey("arrayKey"); });747 var customValidatorCalls = 0;748 result = validator.numberForKey("numberKey", null, function(value){749 ++customValidatorCalls;750 TKAssertType(value, "number");751 TKAssertFloatEquals(value, 1.2);752 });753 TKAssertEquals(customValidatorCalls, 1);754 customValidatorCalls = 0;755 result = validator.numberForKey("missingKey", null, function(value){756 ++customValidatorCalls;757 });758 TKAssertEquals(customValidatorCalls, 0);759 },760 testFormNumberForKeyInRange: function(){761 var input = JSFormFieldMap();762 input.add("stringKey", "testing");763 input.add("numberKey", "1.2");764 input.add("integerKey", "12");765 input.add("boolKey", "true");766 input.add("nullKey", null);767 input.add("arrayKey", "zero");768 input.add("arrayKey", "1");769 input.add("arrayKey", "2");770 input.add("arrayKey", "3");771 var validator = SKValidatingObject.initWithForm(input);772 var result = validator.numberForKeyInRange("numberKey", 0, 10);773 TKAssertFloatEquals(result, 1.2);774 result = validator.numberForKeyInRange("numberKey", 0);775 TKAssertFloatEquals(result, 1.2);776 result = validator.numberForKeyInRange("numberKey", undefined, 10);777 TKAssertFloatEquals(result, 1.2);778 result = validator.numberForKeyInRange("missingKey", 0, 10, 15);779 TKAssertEquals(result, 15);780 result = validator.numberForKeyInRange("missingKey", 0, 10, null);781 TKAssertNull(result);782 TKAssertThrows(function(){ validator.numberForKeyInRange("missingKey"); });783 TKAssertThrows(function(){ validator.numberForKeyInRange("stringKey"); });784 TKAssertThrows(function(){ validator.numberForKeyInRange("boolKey"); });785 TKAssertThrows(function(){ validator.numberForKeyInRange("nullKey"); });786 TKAssertThrows(function(){ validator.numberForKeyInRange("arrayKey"); });787 TKAssertThrows(function(){ validator.numberForKeyInRange("numberKey", 2); });788 TKAssertThrows(function(){ validator.numberForKeyInRange("numberKey", 0, 1); });789 TKAssertThrows(function(){ validator.numberForKeyInRange("numberKey", undefined, 1); });790 },791 testFormIntegerForKey: function(){792 var input = JSFormFieldMap();793 input.add("stringKey", "testing");794 input.add("numberKey", "1.2");795 input.add("integerKey", "12");796 input.add("boolKey", "true");797 input.add("nullKey", null);798 input.add("arrayKey", "zero");799 input.add("arrayKey", "1");800 input.add("arrayKey", "2");801 input.add("arrayKey", "3");802 var validator = SKValidatingObject.initWithForm(input);803 var result = validator.integerForKey("integerKey");804 TKAssertExactEquals(result, 12);805 result = validator.integerForKey("missingKey", 5);806 TKAssertEquals(result, 5);807 result = validator.integerForKey("missingKey", null);808 TKAssertNull(result);809 TKAssertThrows(function(){ validator.integerForKey("missingKey"); });810 TKAssertThrows(function(){ validator.integerForKey("numberKey"); });811 TKAssertThrows(function(){ validator.integerForKey("stringKey"); });812 TKAssertThrows(function(){ validator.integerForKey("boolKey"); });813 TKAssertThrows(function(){ validator.integerForKey("nullKey"); });814 TKAssertThrows(function(){ validator.integerForKey("arrayKey"); });815 var customValidatorCalls = 0;816 result = validator.integerForKey("integerKey", null, function(value){817 ++customValidatorCalls;818 TKAssertEquals(value, 12);819 });820 TKAssertEquals(customValidatorCalls, 1);821 customValidatorCalls = 0;822 result = validator.integerForKey("missingKey", null, function(value){823 ++customValidatorCalls;824 });825 TKAssertEquals(customValidatorCalls, 0);826 },827 testFormIntegerForKeyInRange: function(){828 var input = JSFormFieldMap();829 input.add("stringKey", "testing");830 input.add("numberKey", "1.2");831 input.add("integerKey", "12");832 input.add("boolKey", "true");833 input.add("nullKey", null);834 input.add("arrayKey", "zero");835 input.add("arrayKey", "1");836 input.add("arrayKey", "2");837 input.add("arrayKey", "3");838 var validator = SKValidatingObject.initWithForm(input);839 var result = validator.integerForKeyInRange("integerKey", 0, 20);840 TKAssertExactEquals(result, 12);841 result = validator.integerForKeyInRange("integerKey", 0);842 TKAssertEquals(result, 12);843 result = validator.integerForKeyInRange("integerKey", undefined, 20);844 TKAssertEquals(result, 12);845 result = validator.integerForKeyInRange("missingKey", 0, 10, 15);846 TKAssertEquals(result, 15);847 result = validator.integerForKeyInRange("missingKey", 0, 10, null);848 TKAssertNull(result);849 TKAssertThrows(function(){ validator.integerForKeyInRange("missingKey"); });850 TKAssertThrows(function(){ validator.integerForKeyInRange("stringKey"); });851 TKAssertThrows(function(){ validator.integerForKeyInRange("numberKey"); });852 TKAssertThrows(function(){ validator.integerForKeyInRange("boolKey"); });853 TKAssertThrows(function(){ validator.integerForKeyInRange("nullKey"); });854 TKAssertThrows(function(){ validator.integerForKeyInRange("arrayKey"); });855 TKAssertThrows(function(){ validator.integerForKeyInRange("integerKey", 20); });856 TKAssertThrows(function(){ validator.integerForKeyInRange("integerKey", 0, 10); });857 TKAssertThrows(function(){ validator.integerForKeyInRange("integerKey", undefined, 10); });858 },859 testFormBooleanForKey: function(){860 var input = JSFormFieldMap();861 input.add("stringKey", "testing");862 input.add("numberKey", "1.2");863 input.add("integerKey", "12");864 input.add("boolKey", "true");865 input.add("boolKey2", "off");866 input.add("boolKey3", "yes");867 input.add("boolKey4", "0");868 input.add("nullKey", null);869 input.add("arrayKey", "zero");870 input.add("arrayKey", "1");871 input.add("arrayKey", "2");872 input.add("arrayKey", "3");873 var validator = SKValidatingObject.initWithForm(input);874 var result = validator.booleanForKey("boolKey");875 TKAssertExactEquals(result, true);876 result = validator.booleanForKey("boolKey2");877 TKAssertExactEquals(result, false);878 result = validator.booleanForKey("boolKey3");879 TKAssertExactEquals(result, true);880 result = validator.booleanForKey("boolKey4");881 TKAssertExactEquals(result, false);882 result = validator.booleanForKey("missingKey", false);883 TKAssertExactEquals(result, false);884 result = validator.booleanForKey("missingKey", null);885 TKAssertNull(result);886 TKAssertThrows(function(){ validator.booleanForKey("missingKey"); });887 TKAssertThrows(function(){ validator.booleanForKey("stringKey"); });888 TKAssertThrows(function(){ validator.booleanForKey("numberKey"); });889 TKAssertThrows(function(){ validator.booleanForKey("nullKey"); });890 TKAssertThrows(function(){ validator.booleanForKey("arrayKey"); });891 },892 testFormObjectForKey: function(){893 var input = JSFormFieldMap();894 input.add("stringKey", "testing");895 input.add("numberKey", "1.2");896 input.add("integerKey", "12");897 input.add("boolKey", "true");898 input.add("nullKey", null);899 input.add("arrayKey", "zero");900 input.add("arrayKey", "1");901 input.add("arrayKey", "2");902 input.add("arrayKey", "3");903 var validator = SKValidatingObject.initWithForm(input);904 var result = validator.objectForKey("missingKey", null);905 TKAssertNull(result);906 TKAssertThrows(function(){ validator.objectForKey("missingKey"); });907 TKAssertThrows(function(){ validator.objectForKey("stringKey"); });908 TKAssertThrows(function(){ validator.objectForKey("numberKey"); });909 TKAssertThrows(function(){ validator.objectForKey("nullKey"); });910 TKAssertThrows(function(){ validator.objectForKey("arrayKey"); });911 TKAssertThrows(function(){ validator.objectForKey("boolKey"); });912 },913 testFormGetKeys: function(){914 var input = JSFormFieldMap();915 input.add("stringKey", "testing");916 input.add("numberKey", "1.2");917 input.add("integerKey", "12");918 var validator = SKValidatingObject.initWithForm(input);919 var keys = validator.getKeys();920 TKAssertEquals(keys.length, 3);921 TKAssertEquals(keys[0], "stringKey");922 TKAssertEquals(keys[1], "numberKey");923 TKAssertEquals(keys[2], "integerKey");924 },925 testFormArrayForKey: function(){926 var input = JSFormFieldMap();927 input.add("stringKey", "testing");928 input.add("numberKey", "1.2");929 input.add("integerKey", "12");930 input.add("boolKey", "true");931 input.add("nullKey", null);932 input.add("arrayKey", "zero");933 input.add("arrayKey", "1");934 input.add("arrayKey", "2");935 input.add("arrayKey", "3");936 var validator = SKValidatingObject.initWithForm(input);937 var result = validator.arrayForKey("arrayKey");938 TKAssert(result instanceof SKValidatingObject);939 TKAssertEquals(result.length, 4);940 var result2 = result.stringForKey(0);941 TKAssertEquals(result2, "zero");942 result2 = result.numberForKey(1);943 TKAssertEquals(result2, 1);944 result = validator.arrayForKey("stringKey");945 TKAssert(result instanceof SKValidatingObject);946 TKAssertEquals(result.length, 1);947 result2 = result.stringForKey(0);948 TKAssertEquals(result2, "testing");949 result = validator.arrayForKey("numberKey");950 TKAssert(result instanceof SKValidatingObject);951 TKAssertEquals(result.length, 1);952 result2 = result.stringForKey(0);953 TKAssertExactEquals(result2, "1.2");954 result2 = result.numberForKey(0);955 TKAssertType(result2, "number");956 TKAssertEquals(result2, 1.2);957 result = validator.arrayForKey("nullKey");958 TKAssert(result instanceof SKValidatingObject);959 TKAssertEquals(result.length, 1);960 TKAssertThrows(function(){ result.stringForKey(0); });961 TKAssertThrows(function(){ result.numberForKey(0); });962 result = validator.arrayForKey("boolKey");963 TKAssert(result instanceof SKValidatingObject);964 TKAssertEquals(result.length, 1);965 result2 = result.stringForKey(0);966 TKAssertExactEquals(result2, "true");967 result2 = result.booleanForKey(0);968 TKAssertExactEquals(result2, true);969 result = validator.arrayForKey("missingKey", null);970 TKAssertNull(result);971 TKAssertThrows(function(){ validator.arrayForKey("missingKey"); });972 },973 testFormBase64DataForKey: function(){974 var input = JSFormFieldMap();975 input.add("data", JSData.initWithArray([0,1,2,3]).base64StringRepresentation());976 var validator = SKValidatingObject.initWithForm(input);977 var result = validator.base64DataForKey("data");978 TKAssert(result instanceof JSData);979 TKAssertEquals(result.length, 4);980 TKAssertEquals(result[0], 0);981 TKAssertEquals(result[1], 1);982 TKAssertEquals(result[2], 2);983 TKAssertEquals(result[3], 3);984 validator = SKValidatingObject.initWithForm(input);985 var fallback = JSData.initWithLength(0);986 result = validator.base64DataForKey("missing", fallback);987 TKAssertExactEquals(result, fallback);988 TKAssertThrows(function(){989 var input = JSFormFieldMap();990 input.add("data", "not!base64");991 var validator = SKValidatingObject.initWithForm(input);992 var result = validator.base64DataForKey("data");993 });994 },995 testFormBase64URLDataForKey: function(){996 var input = {data: JSData.initWithArray([0,1,2,3]).base64URLStringRepresentation()};997 var validator = SKValidatingObject.initWithObject(input);998 var result = validator.base64URLDataForKey("data");999 TKAssert(result instanceof JSData);1000 TKAssertEquals(result.length, 4);1001 TKAssertEquals(result[0], 0);1002 TKAssertEquals(result[1], 1);1003 TKAssertEquals(result[2], 2);1004 TKAssertEquals(result[3], 3);1005 validator = SKValidatingObject.initWithObject(input);1006 var fallback = JSData.initWithLength(0);1007 result = validator.base64URLDataForKey("missing", fallback);1008 TKAssertExactEquals(result, fallback);1009 TKAssertThrows(function(){1010 var input = {data: "not!base64url"};1011 var validator = SKValidatingObject.initWithObject(input);1012 var result = validator.base64URLDataForKey("data");1013 });1014 },...
test_check.py
Source:test_check.py
...15class BaseTemplateTest(unittest.TestCase):16 """Common methods for testing template validators"""17 SAMPLE_FILE = "" # Path to a file that should pass all tests18 VALIDATOR = check.MarkdownValidator19 def _create_validator(self, markdown):20 """Create validator object from markdown string; useful for failures"""21 return self.VALIDATOR(markdown=markdown)22class TestAstHelpers(BaseTemplateTest):23 SAMPLE_FILE = os.path.join(MARKDOWN_DIR, 'index.md')24 VALIDATOR = check.MarkdownValidator25 def test_link_text_extracted(self):26 """Verify that link text and destination are extracted correctly"""27 validator = self._create_validator("""[This is a link](discussion.html)""")28 links = validator.ast.find_external_links(validator.ast.children[0])29 dest, link_text = validator.ast.get_link_info(links[0])30 self.assertEqual(dest, "discussion.html")31 self.assertEqual(link_text, "This is a link")32class TestIndexPage(BaseTemplateTest):33 """Test the ability to correctly identify and validate specific sections34 of a markdown file"""35 SAMPLE_FILE = os.path.join(MARKDOWN_DIR, "index.md")36 VALIDATOR = check.IndexPageValidator37 def test_sample_file_passes_validation(self):38 sample_validator = self.VALIDATOR(self.SAMPLE_FILE)39 res = sample_validator.validate()40 self.assertTrue(res)41 def test_headers_missing_hrs(self):42 validator = self._create_validator("""Blank row43layout: lesson44title: Lesson Title45Another section that isn't an HR46""")47 self.assertFalse(validator._validate_doc_headers())48 def test_headers_missing_a_line(self):49 """One of the required headers is missing"""50 validator = self._create_validator("""---51layout: lesson52---""")53 self.assertFalse(validator._validate_doc_headers())54 # TESTS INVOLVING DOCUMENT HEADER SECTION55 def test_headers_fail_with_other_content(self):56 validator = self._create_validator("""---57layout: lesson58title: Lesson Title59otherline: Nothing60---""")61 self.assertFalse(validator._validate_doc_headers())62 def test_fail_when_headers_not_yaml_dict(self):63 """Fail when the headers can't be parsed to a dict of YAML data"""64 validator = self._create_validator("""---65This will parse as a string, not a dictionary66---""")67 self.assertFalse(validator._validate_doc_headers())68 # TESTS INVOLVING SECTION TITLES/HEADINGS69 def test_index_has_valid_section_headings(self):70 """The provided index page"""71 validator = self._create_validator("""## Topics721. [Topic Title One](01-one.html)732. [Topic Title Two](02-two.html)74## Other Resources75* [Reference Guide](reference.html)76* [Next Steps](discussion.html)77* [Instructor's Guide](instructors.html)""")78 res = validator._validate_section_heading_order()79 self.assertTrue(res)80 def test_index_fail_when_section_heading_absent(self):81 validator = self._create_validator("""## Topics821. [Topic Title One](01-one.html)832. [Topic Title Two](02-two.html)84## Other Resources85* [Reference Guide](reference.html)86* [Next Steps](discussion.html)87* [Instructor's Guide](instructors.html)""")88 res = validator.ast.has_section_heading("Fake heading")89 self.assertFalse(res)90 def test_fail_when_section_heading_is_wrong_level(self):91 """All headings must be exactly level 2"""92 validator = self._create_validator("""---93layout: page94title: Lesson Title95---96Paragraph of introductory material.97> ## Prerequisites98>99> A short paragraph describing what learners need to know100> before tackling this lesson.101### Topics1021. [Topic Title 1](01-one.html)1032. [Topic Title 2](02-two.html)104## Other Resources105* [Reference Guide](reference.html)106* [Next Steps](discussion.html)107* [Instructor's Guide](instructors.html)""")108 self.assertFalse(validator._validate_section_heading_order())109 def test_fail_when_section_headings_in_wrong_order(self):110 validator = self._create_validator("""---111layout: lesson112title: Lesson Title113---114Paragraph of introductory material.115> ## Prerequisites116>117> A short paragraph describing what learners need to know118> before tackling this lesson.119## Other Resources120* [Reference Guide](reference.html)121* [Instructor's Guide](instructors.html)122## Topics123* [Topic Title 1](01-one.html)124* [Topic Title 2](02-two.html)""")125 self.assertFalse(validator._validate_section_heading_order())126 def test_pass_when_prereq_section_has_correct_heading_level(self):127 validator = self._create_validator("""---128layout: lesson129title: Lesson Title130---131Paragraph of introductory material.132> ## Prerequisites133>134> A short paragraph describing what learners need to know135> before tackling this lesson.136""")137 self.assertTrue(validator._validate_intro_section())138 def test_fail_when_prereq_section_has_incorrect_heading_level(self):139 validator = self._create_validator("""140> # Prerequisites {.prereq}141>142> A short paragraph describing what learners need to know143> before tackling this lesson.144""")145 self.assertFalse(validator._validate_callouts())146 # TESTS INVOLVING LINKS TO OTHER CONTENT147 def test_should_check_text_of_all_links_in_index(self):148 """Text of every local-html link in index.md should149 match dest page title"""150 validator = self._create_validator("""151## [This link is in a heading](reference.html)152[Topic Title One](01-one.html#anchor)""")153 links = validator.ast.find_external_links()154 check_text, dont_check_text = validator._partition_links()155 self.assertEqual(len(dont_check_text), 0)156 self.assertEqual(len(check_text), 2)157 def test_file_links_validate(self):158 """Verify that all links in a sample file validate.159 Involves checking for example files; may fail on "core" branch"""160 sample_validator = self.VALIDATOR(self.SAMPLE_FILE)161 res = sample_validator._validate_links()162 self.assertTrue(res)163 def test_html_link_to_extant_md_file_passes(self):164 """Verify that an HTML link with corresponding MD file will pass165 Involves checking for example files; may fail on "core" branch"""166 validator = self._create_validator("""[Topic Title One](01-one.html)""")167 self.assertTrue(validator._validate_links())168 def test_html_link_with_anchor_to_extant_md_passes(self):169 """Verify that link is identified correctly even if to page anchor170 For now this just tests that the regex handles #anchors.171 It doesn't validate that the named anchor exists in the md file172 Involves checking for example files; may fail on "core" branch173 """174 validator = self._create_validator("""[Topic Title One](01-one.html#anchor)""")175 self.assertTrue(validator._validate_links())176 def test_inpage_anchor_passes_validation(self):177 """Links that reference anchors within the page should be ignored"""178 # TODO: Revisit once anchor rules are available179 validator = self._create_validator("""Most databases also support Booleans and date/time values;180SQLite uses the integers 0 and 1 for the former, and represents the latter as discussed [earlier](#a:dates).""")181 self.assertTrue(validator._validate_links())182 def test_missing_markdown_file_fails_validation(self):183 """Fail validation when an html file is linked without corresponding184 markdown file"""185 validator = self._create_validator("""[Broken link](nonexistent.html)""")186 self.assertFalse(validator._validate_links())187 def test_website_link_ignored_by_validator(self):188 """Don't look for markdown if the file linked isn't local-189 remote website links are ignored"""190 validator = self._create_validator("""[Broken link](http://website.com/filename.html)""")191 self.assertTrue(validator._validate_links())192 def test_malformed_website_link_fails_validator(self):193 """If the link isn't prefixed by http(s):// or ftp://, fail.194 This is because there are a lot of edge cases in distinguishing195 between filenames and URLs: err on the side of certainty."""196 validator = self._create_validator("""[Broken link](www.website.com/filename.html)""")197 self.assertFalse(validator._validate_links())198 def test_finds_image_asset(self):199 """Image asset is found in the expected file location200 Involves checking for example files; may fail on "core" branch"""201 validator = self._create_validator(202 """![this is the image's title](fig/example.svg "this is the image's alt text")""")203 self.assertTrue(validator._validate_links())204 def test_image_asset_not_found(self):205 """Image asset can't be found if path is invalid"""206 validator = self._create_validator(207 """![this is the image's title](fig/exemple.svg "this is the image's alt text")""")208 self.assertFalse(validator._validate_links())209 def test_non_html_link_finds_csv(self):210 """Look for CSV file in appropriate folder211 Involves checking for example files; may fail on "core" branch212 """213 validator = self._create_validator(214 """Use [this CSV](data/data.csv) for the exercise.""")215 self.assertTrue(validator._validate_links())216 def test_non_html_links_are_path_sensitive(self):217 """Fails to find CSV file with wrong path."""218 validator = self._create_validator(219 """Use [this CSV](data.csv) for the exercise.""")220 self.assertFalse(validator._validate_links())221 ### Tests involving callout/blockquote sections222 def test_one_prereq_callout_passes(self):223 """index.md should have one, and only one, prerequisites box"""224 validator = self._create_validator("""> ## Prerequisites {.prereq}225>226> What learners need to know before tackling this lesson.227""")228 self.assertTrue(validator._validate_callouts())229 def test_two_prereq_callouts_fail(self):230 """More than one prereq callout box is not allowed"""231 validator = self._create_validator("""> ## Prerequisites {.prereq}232>233> What learners need to know before tackling this lesson.234A spacer paragraph235> ## Prerequisites {.prereq}236>237> A second prerequisites box should cause an error238""")239 self.assertFalse(validator._validate_callouts())240 def test_callout_without_style_fails(self):241 """A callout box will fail if it is missing the required style"""242 validator = self._create_validator("""> ## Prerequisites243>244> What learners need to know before tackling this lesson.245""")246 self.assertFalse(validator._validate_callouts())247 def test_callout_with_wrong_title_fails(self):248 """A callout box will fail if it has the wrong title"""249 validator = self._create_validator("""> ## Wrong title {.prereq}250>251> What learners need to know before tackling this lesson.252""")253 self.assertFalse(validator._validate_callouts())254 def test_unknown_callout_style_fails(self):255 """A callout whose style is unrecognized by template is invalid"""256 validator = self._create_validator("""> ## Any title {.callout}257>258> What learners need to know before tackling this lesson.259""")260 callout_node = validator.ast.get_callouts()[0]261 self.assertFalse(validator._validate_one_callout(callout_node))262 def test_block_ignored_sans_heading(self):263 """264 Blockquotes only count as callouts if they have a heading265 """266 validator = self._create_validator("""> Prerequisites {.prereq}267>268> What learners need to know before tackling this lesson.269""")270 callout_nodes = validator.ast.get_callouts()271 self.assertEqual(len(callout_nodes), 0)272 def test_callout_heading_must_be_l2(self):273 """Callouts will fail validation if the heading is not level 2"""274 validator = self._create_validator("""> ### Prerequisites {.prereq}275>276> What learners need to know before tackling this lesson.277""")278 self.assertFalse(validator._validate_callouts())279 def test_fail_if_fixme_present_all_caps(self):280 """Validation should fail if a line contains the word FIXME (exact)"""281 validator = self._create_validator("""Incomplete sentence (FIXME).""")282 self.assertFalse(validator._validate_no_fixme())283 def test_fail_if_fixme_present_mixed_case(self):284 """Validation should fail if a line contains the word FIXME285 (in any capitalization)"""286 validator = self._create_validator("""Incomplete sentence (FiXmE).""")287 self.assertFalse(validator._validate_no_fixme())288class TestTopicPage(BaseTemplateTest):289 """Verifies that the topic page validator works as expected"""290 SAMPLE_FILE = os.path.join(MARKDOWN_DIR, "01-one.md")291 VALIDATOR = check.TopicPageValidator292 def test_headers_fail_because_invalid_content(self):293 """The value provided as YAML does not match the expected datatype"""294 validator = self._create_validator("""---295layout: lesson296title: Lesson Title297subtitle: A page298minutes: not a number299---""")300 self.assertFalse(validator._validate_doc_headers())301 def test_topic_page_should_have_no_headings(self):302 """Requirement according to spec; may be relaxed in future"""303 validator = self._create_validator("""304## Heading that should not be present305Some text""")306 self.assertFalse(validator._validate_has_no_headings())307 def test_should_not_check_text_of_links_in_topic(self):308 """Never check that text of local-html links in topic309 matches dest title """310 validator = self._create_validator("""311## [This link is in a heading](reference.html)312[Topic Title One](01-one.html#anchor)""")313 links = validator.ast.find_external_links()314 check_text, dont_check_text = validator._partition_links()315 self.assertEqual(len(dont_check_text), 2)316 self.assertEqual(len(check_text), 0)317 def test_pass_when_optional_callouts_absent(self):318 """Optional block titles should be optional"""319 validator = self._create_validator("""> ## Learning Objectives {.objectives}320>321> * All topic pages must have this callout""")322 self.assertTrue(validator._validate_callouts())323 def test_callout_style_passes_regardless_of_title(self):324 """Verify that certain kinds of callout box can be recognized solely325 by style, regardless of the heading title"""326 validator = self._create_validator("""> ## Learning Objectives {.objectives}327>328> * All topic pages must have this callout329> ## Some random title {.callout}330>331> Some informative text""")332 self.assertTrue(validator._validate_callouts())333 def test_callout_style_allows_duplicates(self):334 """Multiple blockquoted sections with style 'callout' are allowed"""335 validator = self._create_validator("""> ## Learning Objectives {.objectives}336>337> * All topic pages must have this callout338> ## Callout box one {.callout}339>340> Some informative text341Spacer paragraph342> ## Callout box two {.callout}343>344> Further exposition""")345 self.assertTrue(validator._validate_callouts())346 def test_sample_file_passes_validation(self):347 sample_validator = self.VALIDATOR(self.SAMPLE_FILE)348 res = sample_validator.validate()349 self.assertTrue(res)350class TestReferencePage(BaseTemplateTest):351 """Verifies that the reference page validator works as expected"""352 SAMPLE_FILE = os.path.join(MARKDOWN_DIR, "reference.md")353 VALIDATOR = check.ReferencePageValidator354 def test_missing_glossary_definition(self):355 validator = self._create_validator("")356 self.assertFalse(validator._validate_glossary_entry(357 ["Key word"]))358 def test_missing_colon_at_glossary_definition(self):359 validator = self._create_validator("")360 self.assertFalse(validator._validate_glossary_entry(361 ["Key word", "Definition of term"]))362 def test_wrong_indentation_at_glossary_definition(self):363 validator = self._create_validator("")364 self.assertFalse(validator._validate_glossary_entry(365 ["Key word", ": Definition of term"]))366 def test_wrong_continuation_at_glossary_definition(self):367 validator = self._create_validator("")368 self.assertFalse(validator._validate_glossary_entry(369 ["Key word", ": Definition of term", "continuation"]))370 def test_valid_glossary_definition(self):371 validator = self._create_validator("")372 self.assertTrue(validator._validate_glossary_entry(373 ["Key word", ": Definition of term", " continuation"]))374 def test_only_definitions_can_appear_after_glossary_heading(self):375 validator = self._create_validator("""## Glossary376Key Word 1377: Definition of first term378Paragraph379Key Word 2380: Definition of second term381""")382 self.assertFalse(validator._validate_glossary())383 def test_glossary(self):384 validator = self._create_validator("""## Glossary385Key Word 1386: Definition of first term387Key Word 2388: Definition of second term389""")390 self.assertTrue(validator._validate_glossary())391 def test_callout_fails_when_none_specified(self):392 """The presence of a callout box should cause validation to fail393 when the template doesn't define any recognized callouts394 (No "unknown" blockquote sections are allowed)395 """396 validator = self._create_validator("""> ## Learning Objectives {.objectives}397>398> * Learning objective 1399> * Learning objective 2""")400 self.assertFalse(validator._validate_callouts())401 def test_sample_file_passes_validation(self):402 sample_validator = self.VALIDATOR(self.SAMPLE_FILE)403 res = sample_validator.validate()404 self.assertTrue(res)405class TestInstructorPage(BaseTemplateTest):406 """Verifies that the instructors page validator works as expected"""407 SAMPLE_FILE = os.path.join(MARKDOWN_DIR, "instructors.md")408 VALIDATOR = check.InstructorPageValidator409 def test_should_selectively_check_text_of_links_in_topic(self):410 """Only verify that text of local-html links in topic411 matches dest title if the link is in a heading"""412 validator = self._create_validator("""413## [Reference](reference.html)414[Topic Title One](01-one.html#anchor)""")415 check_text, dont_check_text = validator._partition_links()416 self.assertEqual(len(dont_check_text), 1)417 self.assertEqual(len(check_text), 1)418 def test_link_dest_bad_while_text_ignored(self):419 validator = self._create_validator("""420[ignored text](nonexistent.html)""")421 self.assertFalse(validator._validate_links())422 def test_link_dest_good_while_text_ignored(self):423 validator = self._create_validator("""424[ignored text](01-one.html)""")425 self.assertTrue(validator._validate_links())426 def test_sample_file_passes_validation(self):427 sample_validator = self.VALIDATOR(self.SAMPLE_FILE)428 res = sample_validator.validate()429 self.assertTrue(res)430class TestLicensePage(BaseTemplateTest):431 SAMPLE_FILE = os.path.join(MARKDOWN_DIR, "LICENSE.md")432 VALIDATOR = check.LicensePageValidator433 def test_sample_file_passes_validation(self):434 sample_validator = self.VALIDATOR(self.SAMPLE_FILE)435 res = sample_validator.validate()436 self.assertTrue(res)437 def test_modified_file_fails_validation(self):438 with open(self.SAMPLE_FILE, 'rU') as f:439 orig_text = f.read()440 mod_text = orig_text.replace("The", "the")441 validator = self._create_validator(mod_text)442 self.assertFalse(validator.validate())443class TestDiscussionPage(BaseTemplateTest):444 SAMPLE_FILE = os.path.join(MARKDOWN_DIR, "discussion.md")445 VALIDATOR = check.DiscussionPageValidator446 def test_sample_file_passes_validation(self):447 sample_validator = self.VALIDATOR(self.SAMPLE_FILE)448 res = sample_validator.validate()449 self.assertTrue(res)450if __name__ == "__main__":...
mns_tool.py
Source:mns_tool.py
1#coding=utf-82# Copyright (C) 2015, Alibaba Cloud Computing3#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:4#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.5#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.6import os7import sys8import string9import types10import logging11import logging.handlers12from mns_exception import *13METHODS = ["PUT", "POST", "GET", "DELETE"]14PERMISSION_ACTIONS = ["setqueueattributes", "getqueueattributes", "sendmessage", "receivemessage", "deletemessage", "peekmessage", "changevisibility"]15class MNSLogger:16 @staticmethod17 def get_logger(log_name=None, log_file=None, log_level=logging.INFO):18 if log_name is None:19 log_name = "mns_python_sdk"20 if log_file is None:21 log_file = os.path.join(os.path.split(os.path.realpath(__file__))[0], "mns_python_sdk.log")22 logger = logging.getLogger(log_name)23 if logger.handlers == []:24 fileHandler = logging.handlers.RotatingFileHandler(log_file, maxBytes=10*1024*1024)25 formatter = logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] [%(filename)s:%(lineno)d] [%(thread)d] %(message)s', '%Y-%m-%d %H:%M:%S')26 fileHandler.setFormatter(formatter)27 logger.addHandler(fileHandler)28 MNSLogger.validate_loglevel(log_level)29 logger.setLevel(log_level)30 return logger31 @staticmethod32 def validate_loglevel(log_level):33 log_levels = [logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]34 if log_level not in log_levels:35 raise MNSClientParameterException("LogLevelInvalid", "Bad value: '%s', expect levels: '%s'." % \36 (log_level, ','.join([str(item) for item in log_levels])))37class ValidatorBase:38 @staticmethod39 def validate(req):40 pass41 @staticmethod42 def type_validate(item, valid_type, param_name=None, req_id=None):43 if not (type(item) is valid_type):44 if param_name is None:45 raise MNSClientParameterException("TypeInvalid", "Bad type: '%s', '%s' expect type '%s'." % (type(item), item, valid_type), req_id)46 else:47 raise MNSClientParameterException("TypeInvalid", "Param '%s' in bad type: '%s', '%s' expect type '%s'." % (param_name, type(item), item, valid_type), req_id)48 @staticmethod49 def is_str(item, param_name=None, req_id=None):50 if not isinstance(item, basestring):51 if param_name is None:52 raise MNSClientParameterException("TypeInvalid", "Bad type: '%s', '%s' expect basestring." % (type(item), item), req_id)53 else:54 raise MNSClientParameterException("TypeInvalid", "Param '%s' in bad type: '%s', '%s' expect basestring." % (param_name, type(item), item), req_id)55 @staticmethod56 def marker_validate(req):57 ValidatorBase.is_str(req.marker, req_id=req.request_id)58 @staticmethod59 def retnumber_validate(req):60 ValidatorBase.type_validate(req.ret_number, types.IntType, req_id=req.request_id)61 if (req.ret_number != -1 and req.ret_number <= 0 ):62 raise MNSClientParameterException("HeaderInvalid", "Bad value: '%s', x-mns-number should larger than 0." % req.ret_number, req.request_id)63 @staticmethod64 def name_validate(name, nameType, req_id=None):65 #type66 ValidatorBase.is_str(name, req_id=req_id)67 #length68 if len(name) < 1:69 raise MNSClientParameterException("QueueNameInvalid", "Bad value: '%s', the length of %s should larger than 1." % (name, nameType), req_id)70 @staticmethod71 def list_condition_validate(req):72 if req.prefix != "":73 ValidatorBase.name_validate(req.prefix, "prefix")74 ValidatorBase.marker_validate(req)75 ValidatorBase.retnumber_validate(req)76class SetAccountAttributesValidator(ValidatorBase):77 @staticmethod78 def validate(req):79 #type80 if req.logging_bucket is not None:81 ValidatorBase.is_str(req.logging_bucket, req_id=req.request_id)82class QueueValidator(ValidatorBase):83 @staticmethod84 def queue_validate(req):85 #type86 ValidatorBase.type_validate(req.visibility_timeout, types.IntType, req_id=req.request_id)87 ValidatorBase.type_validate(req.maximum_message_size, types.IntType, req_id=req.request_id)88 ValidatorBase.type_validate(req.message_retention_period, types.IntType, req_id=req.request_id)89 ValidatorBase.type_validate(req.delay_seconds, types.IntType, req_id=req.request_id)90 ValidatorBase.type_validate(req.polling_wait_seconds, types.IntType, req_id=req.request_id)91 #value92 if req.visibility_timeout != -1 and req.visibility_timeout <= 0:93 raise MNSClientParameterException("QueueAttrInvalid", "Bad value: '%d', visibility timeout should larger than 0." % req.visibility_timeout, req.request_id)94 if req.maximum_message_size != -1 and req.maximum_message_size <= 0:95 raise MNSClientParameterException("QueueAttrInvalid", "Bad value: '%d', maximum message size should larger than 0." % req.maximum_message_size, req.request_id)96 if req.message_retention_period != -1 and req.message_retention_period <= 0:97 raise MNSClientParameterException("QueueAttrInvalid", "Bad value: '%d', message retention period should larger than 0." % req.message_retention_period, req.request_id)98 if req.delay_seconds != -1 and req.delay_seconds < 0:99 raise MNSClientParameterException("QueueAttrInvalid", "Bad value: '%d', delay seconds should larger than 0." % req.delay_seconds, req.request_id)100 if req.polling_wait_seconds != -1 and req.polling_wait_seconds < 0:101 raise MNSClientParameterException("QueueAttrInvalid", "Bad value: '%d', polling wait seconds should larger than 0." % req.polling_wait_seconds, req.request_id)102 if req.logging_enabled != None and str(req.logging_enabled).lower() not in ("true", "false"):103 raise MNSClientParameterException("QueueAttrInvalid", "Bad value: '%s', logging enabled should be True/False." % req.logging_enabled, req.request_id)104class MessageValidator(ValidatorBase):105 @staticmethod106 def sendmessage_attr_validate(req, req_id):107 #type108 ValidatorBase.is_str(req.message_body, None, req_id)109 ValidatorBase.type_validate(req.delay_seconds, types.IntType, None, req_id)110 ValidatorBase.type_validate(req.priority, types.IntType, None, req_id)111 #value112 if req.message_body == "":113 raise MNSClientParameterException("MessageBodyInvalid", "Bad value: '', message body should not be ''.", req_id)114 if req.delay_seconds != -1 and req.delay_seconds < 0:115 raise MNSClientParameterException("DelaySecondsInvalid", "Bad value: '%d', delay_seconds should larger than 0." % req.delay_seconds, req_id)116 if req.priority != -1 and req.priority < 0:117 raise MNSClientParameterException("PriorityInvalid", "Bad value: '%d', priority should larger than 0." % req.priority, req_id)118 @staticmethod119 def receiphandle_validate(receipt_handle, req_id):120 if (receipt_handle == ""):121 raise MNSClientParameterException("ReceiptHandleInvalid", "The receipt handle should not be null.", req_id)122 @staticmethod123 def waitseconds_validate(wait_seconds, req_id):124 if wait_seconds != -1 and wait_seconds < 0:125 raise MNSClientParameterException("WaitSecondsInvalid", "Bad value: '%d', wait_seconds should larger than 0." % wait_seconds, req_id)126 @staticmethod127 def batchsize_validate(batch_size, req_id):128 if batch_size != -1 and batch_size < 0:129 raise MNSClientParameterException("BatchSizeInvalid", "Bad value: '%d', batch_size should larger than 0." % batch_size, req_id)130 @staticmethod131 def publishmessage_attr_validate(req):132 #type133 ValidatorBase.is_str(req.message_body, "message_body", req_id=req.request_id)134 ValidatorBase.is_str(req.message_tag, "message_tag", req_id=req.request_id)135 if req.direct_mail is not None:136 ValidatorBase.is_str(req.direct_mail.account_name, "account_name of direct mail", req_id=req.request_id)137 ValidatorBase.is_str(req.direct_mail.subject, "subject of direct mail", req_id=req.request_id)138 #value139 if req.message_body == "":140 raise MNSClientParameterException("MessageBodyInvalid", "Bad value: '', message body should not be ''.", req.request_id)141 if len(req.message_tag) > 16:142 raise MNSClientParameterException("MessageTagInvalid", "The length of message tag should be between 1 and 16.", req.request_id)143class CreateQueueValidator(QueueValidator):144 @staticmethod145 def validate(req):146 QueueValidator.validate(req)147 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)148 QueueValidator.queue_validate(req)149class DeleteQueueValidator(QueueValidator):150 @staticmethod151 def validate(req):152 QueueValidator.validate(req)153 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)154class ListQueueValidator(QueueValidator):155 @staticmethod156 def validate(req):157 QueueValidator.validate(req)158 QueueValidator.list_condition_validate(req)159class SetQueueAttrValidator(QueueValidator):160 @staticmethod161 def validate(req):162 QueueValidator.validate(req)163 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)164 QueueValidator.queue_validate(req)165class GetQueueAttrValidator(QueueValidator):166 @staticmethod167 def validate(req):168 QueueValidator.validate(req)169 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)170class SendMessageValidator(MessageValidator):171 @staticmethod172 def validate(req):173 MessageValidator.validate(req)174 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)175 MessageValidator.sendmessage_attr_validate(req, req.request_id)176class BatchSendMessageValidator(MessageValidator):177 @staticmethod178 def validate(req):179 MessageValidator.validate(req)180 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)181 for entry in req.message_list:182 MessageValidator.sendmessage_attr_validate(entry, req.request_id)183class ReceiveMessageValidator(MessageValidator):184 @staticmethod185 def validate(req):186 MessageValidator.validate(req)187 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)188 MessageValidator.waitseconds_validate(req.wait_seconds, req.request_id)189class BatchReceiveMessageValidator(MessageValidator):190 @staticmethod191 def validate(req):192 MessageValidator.validate(req)193 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)194 MessageValidator.batchsize_validate(req.batch_size, req.request_id)195 MessageValidator.waitseconds_validate(req.wait_seconds, req.request_id)196class DeleteMessageValidator(MessageValidator):197 @staticmethod198 def validate(req):199 MessageValidator.validate(req)200 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)201 MessageValidator.receiphandle_validate(req.receipt_handle, req.request_id)202class BatchDeleteMessageValidator(MessageValidator):203 @staticmethod204 def validate(req):205 MessageValidator.validate(req)206 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)207 for receipt_handle in req.receipt_handle_list:208 MessageValidator.receiphandle_validate(receipt_handle, req.request_id)209class PeekMessageValidator(MessageValidator):210 @staticmethod211 def validate(req):212 MessageValidator.validate(req)213 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)214class BatchPeekMessageValidator(MessageValidator):215 @staticmethod216 def validate(req):217 MessageValidator.validate(req)218 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)219 MessageValidator.batchsize_validate(req.batch_size, req.request_id)220class ChangeMsgVisValidator(MessageValidator):221 @staticmethod222 def validate(req):223 MessageValidator.validate(req)224 ValidatorBase.name_validate(req.queue_name, "queue_name", req.request_id)225 MessageValidator.receiphandle_validate(req.receipt_handle, req.request_id)226 if (req.visibility_timeout < 0 or req.visibility_timeout > 43200 ):227 raise MNSClientParameterException("VisibilityTimeoutInvalid", "Bad value: '%d', visibility timeout should between 0 and 43200." % req.visibility_timeout, req.request_id)228class TopicValidator(ValidatorBase):229 @staticmethod230 def topic_validate(req):231 #type232 ValidatorBase.type_validate(req.maximum_message_size, types.IntType, "maximum_message_size", req_id=req.request_id)233 #value234 if req.maximum_message_size != -1 and req.maximum_message_size <= 0:235 raise MNSClientParameterException("TopicAttrInvalid", "Bad value: '%s', maximum message size should larger than 0." % req.maximum_message_size, req.request_id)236 if req.logging_enabled != None and str(req.logging_enabled).lower() not in ("true", "false"):237 raise MNSClientParameterException("TopicAttrInvalid", "Bad value: '%s', logging enabled should be True/False." % req.logging_enabled, req.request_id)238class CreateTopicValidator(TopicValidator):239 @staticmethod240 def validate(req):241 TopicValidator.validate(req)242 ValidatorBase.name_validate(req.topic_name, "topic_name", req.request_id)243 TopicValidator.topic_validate(req)244class DeleteTopicValidator(TopicValidator):245 @staticmethod246 def validate(req):247 TopicValidator.validate(req)248 ValidatorBase.name_validate(req.topic_name, "topic_name", req.request_id)249class ListTopicValidator(TopicValidator):250 @staticmethod251 def validate(req):252 TopicValidator.validate(req)253 TopicValidator.list_condition_validate(req)254class SetTopicAttrValidator(TopicValidator):255 @staticmethod256 def validate(req):257 TopicValidator.validate(req)258 ValidatorBase.name_validate(req.topic_name, "topic_name", req.request_id)259 TopicValidator.topic_validate(req)260class GetTopicAttrValidator(TopicValidator):261 @staticmethod262 def validate(req):263 TopicValidator.validate(req)264 ValidatorBase.name_validate(req.topic_name, "topic_name", req.request_id)265class PublishMessageValidator(MessageValidator):266 @staticmethod267 def validate(req):268 MessageValidator.validate(req)269 ValidatorBase.name_validate(req.topic_name, "topic_name", req.request_id)270 MessageValidator.publishmessage_attr_validate(req)271class SubscriptionValidator(TopicValidator):272 @staticmethod273 def subscription_validate(req):274 TopicValidator.is_str(req.endpoint, "endpoint", req_id=req.request_id)275 TopicValidator.is_str(req.notify_strategy, "notify_strategy", req_id=req.request_id)276 TopicValidator.is_str(req.filter_tag, "filter_tag", req_id=req.request_id)277 TopicValidator.is_str(req.notify_content_format, "notify_content_format", req_id=req.request_id)278 @staticmethod279 def filter_tag_validate(filter_tag, req_id):280 if len(filter_tag) > 16:281 raise MNSClientParameterException("FilterTagInvalid", "Bad value: '%s', The length of filter tag should be between 1 and 16." % (filter_tag))282class SubscribeValidator(SubscriptionValidator):283 @staticmethod284 def validate(req):285 SubscriptionValidator.validate(req)286 ValidatorBase.name_validate(req.topic_name, "topic_name", req.request_id)287 ValidatorBase.name_validate(req.subscription_name, "subscription_name", req.request_id)288 SubscriptionValidator.subscription_validate(req)289 SubscriptionValidator.filter_tag_validate(req.filter_tag, req.request_id)290class UnsubscribeValidator(SubscriptionValidator):291 @staticmethod292 def validate(req):293 SubscriptionValidator.validate(req)294 ValidatorBase.name_validate(req.topic_name, "topic_name", req.request_id)295 ValidatorBase.name_validate(req.subscription_name, "subscription_name", req.request_id)296class ListSubscriptionByTopicValidator(SubscriptionValidator):297 @staticmethod298 def validate(req):299 SubscriptionValidator.validate(req)300 SubscriptionValidator.list_condition_validate(req)301class SetSubscriptionAttrValidator(SubscriptionValidator):302 @staticmethod303 def validate(req):304 SubscriptionValidator.validate(req)305 ValidatorBase.name_validate(req.topic_name, "topic_name", req.request_id)306 ValidatorBase.name_validate(req.subscription_name, "subscription_name", req.request_id)307 SubscriptionValidator.subscription_validate(req)308class GetSubscriptionAttrValidator(SubscriptionValidator):309 @staticmethod310 def validate(req):311 SubscriptionValidator.validate(req)312 ValidatorBase.name_validate(req.topic_name, "topic_name", req.request_id)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!