Best JavaScript code snippet using pact-foundation-pact
validateConfig.js
Source:validateConfig.js
1'use strict';2var equal = require('ajv/lib/compile/equal');3var validate = (function() {4 var pattern0 = new RegExp('^[0-9]+$');5 var refVal = [];6 var refVal1 = (function() {7 var pattern0 = new RegExp('^[0-9]+$');8 return function validate(data, dataPath, parentData, parentDataProperty, rootData) {9 'use strict';10 var vErrors = null;11 var errors = 0;12 if (rootData === undefined) rootData = data;13 if ((data && typeof data === "object" && !Array.isArray(data))) {14 var errs__0 = errors;15 var valid1 = true;16 for (var key0 in data) {17 var isAdditional0 = !(false || validate.schema.properties.hasOwnProperty(key0));18 if (isAdditional0) {19 valid1 = false;20 var err = {21 keyword: 'additionalProperties',22 dataPath: (dataPath || '') + "",23 schemaPath: '#/additionalProperties',24 params: {25 additionalProperty: '' + key0 + ''26 },27 message: 'should NOT have additional properties'28 };29 if (vErrors === null) vErrors = [err];30 else vErrors.push(err);31 errors++;32 }33 }34 if (data.topBody !== undefined) {35 var errs_1 = errors;36 if (!refVal2(data.topBody, (dataPath || '') + '.topBody', data, 'topBody', rootData)) {37 if (vErrors === null) vErrors = refVal2.errors;38 else vErrors = vErrors.concat(refVal2.errors);39 errors = vErrors.length;40 }41 var valid1 = errors === errs_1;42 }43 if (data.topJoin !== undefined) {44 var errs_1 = errors;45 if (!refVal[2](data.topJoin, (dataPath || '') + '.topJoin', data, 'topJoin', rootData)) {46 if (vErrors === null) vErrors = refVal[2].errors;47 else vErrors = vErrors.concat(refVal[2].errors);48 errors = vErrors.length;49 }50 var valid1 = errors === errs_1;51 }52 if (data.topLeft !== undefined) {53 var errs_1 = errors;54 if (!refVal[2](data.topLeft, (dataPath || '') + '.topLeft', data, 'topLeft', rootData)) {55 if (vErrors === null) vErrors = refVal[2].errors;56 else vErrors = vErrors.concat(refVal[2].errors);57 errors = vErrors.length;58 }59 var valid1 = errors === errs_1;60 }61 if (data.topRight !== undefined) {62 var errs_1 = errors;63 if (!refVal[2](data.topRight, (dataPath || '') + '.topRight', data, 'topRight', rootData)) {64 if (vErrors === null) vErrors = refVal[2].errors;65 else vErrors = vErrors.concat(refVal[2].errors);66 errors = vErrors.length;67 }68 var valid1 = errors === errs_1;69 }70 if (data.bottomBody !== undefined) {71 var errs_1 = errors;72 if (!refVal[2](data.bottomBody, (dataPath || '') + '.bottomBody', data, 'bottomBody', rootData)) {73 if (vErrors === null) vErrors = refVal[2].errors;74 else vErrors = vErrors.concat(refVal[2].errors);75 errors = vErrors.length;76 }77 var valid1 = errors === errs_1;78 }79 if (data.bottomJoin !== undefined) {80 var errs_1 = errors;81 if (!refVal[2](data.bottomJoin, (dataPath || '') + '.bottomJoin', data, 'bottomJoin', rootData)) {82 if (vErrors === null) vErrors = refVal[2].errors;83 else vErrors = vErrors.concat(refVal[2].errors);84 errors = vErrors.length;85 }86 var valid1 = errors === errs_1;87 }88 if (data.bottomLeft !== undefined) {89 var errs_1 = errors;90 if (!refVal[2](data.bottomLeft, (dataPath || '') + '.bottomLeft', data, 'bottomLeft', rootData)) {91 if (vErrors === null) vErrors = refVal[2].errors;92 else vErrors = vErrors.concat(refVal[2].errors);93 errors = vErrors.length;94 }95 var valid1 = errors === errs_1;96 }97 if (data.bottomRight !== undefined) {98 var errs_1 = errors;99 if (!refVal[2](data.bottomRight, (dataPath || '') + '.bottomRight', data, 'bottomRight', rootData)) {100 if (vErrors === null) vErrors = refVal[2].errors;101 else vErrors = vErrors.concat(refVal[2].errors);102 errors = vErrors.length;103 }104 var valid1 = errors === errs_1;105 }106 if (data.bodyLeft !== undefined) {107 var errs_1 = errors;108 if (!refVal[2](data.bodyLeft, (dataPath || '') + '.bodyLeft', data, 'bodyLeft', rootData)) {109 if (vErrors === null) vErrors = refVal[2].errors;110 else vErrors = vErrors.concat(refVal[2].errors);111 errors = vErrors.length;112 }113 var valid1 = errors === errs_1;114 }115 if (data.bodyRight !== undefined) {116 var errs_1 = errors;117 if (!refVal[2](data.bodyRight, (dataPath || '') + '.bodyRight', data, 'bodyRight', rootData)) {118 if (vErrors === null) vErrors = refVal[2].errors;119 else vErrors = vErrors.concat(refVal[2].errors);120 errors = vErrors.length;121 }122 var valid1 = errors === errs_1;123 }124 if (data.bodyJoin !== undefined) {125 var errs_1 = errors;126 if (!refVal[2](data.bodyJoin, (dataPath || '') + '.bodyJoin', data, 'bodyJoin', rootData)) {127 if (vErrors === null) vErrors = refVal[2].errors;128 else vErrors = vErrors.concat(refVal[2].errors);129 errors = vErrors.length;130 }131 var valid1 = errors === errs_1;132 }133 if (data.joinBody !== undefined) {134 var errs_1 = errors;135 if (!refVal[2](data.joinBody, (dataPath || '') + '.joinBody', data, 'joinBody', rootData)) {136 if (vErrors === null) vErrors = refVal[2].errors;137 else vErrors = vErrors.concat(refVal[2].errors);138 errors = vErrors.length;139 }140 var valid1 = errors === errs_1;141 }142 if (data.joinLeft !== undefined) {143 var errs_1 = errors;144 if (!refVal[2](data.joinLeft, (dataPath || '') + '.joinLeft', data, 'joinLeft', rootData)) {145 if (vErrors === null) vErrors = refVal[2].errors;146 else vErrors = vErrors.concat(refVal[2].errors);147 errors = vErrors.length;148 }149 var valid1 = errors === errs_1;150 }151 if (data.joinRight !== undefined) {152 var errs_1 = errors;153 if (!refVal[2](data.joinRight, (dataPath || '') + '.joinRight', data, 'joinRight', rootData)) {154 if (vErrors === null) vErrors = refVal[2].errors;155 else vErrors = vErrors.concat(refVal[2].errors);156 errors = vErrors.length;157 }158 var valid1 = errors === errs_1;159 }160 if (data.joinJoin !== undefined) {161 var errs_1 = errors;162 if (!refVal[2](data.joinJoin, (dataPath || '') + '.joinJoin', data, 'joinJoin', rootData)) {163 if (vErrors === null) vErrors = refVal[2].errors;164 else vErrors = vErrors.concat(refVal[2].errors);165 errors = vErrors.length;166 }167 var valid1 = errors === errs_1;168 }169 } else {170 var err = {171 keyword: 'type',172 dataPath: (dataPath || '') + "",173 schemaPath: '#/type',174 params: {175 type: 'object'176 },177 message: 'should be object'178 };179 if (vErrors === null) vErrors = [err];180 else vErrors.push(err);181 errors++;182 }183 validate.errors = vErrors;184 return errors === 0;185 };186 })();187 refVal1.schema = {188 "type": "object",189 "properties": {190 "topBody": {191 "$ref": "#/definitions/border"192 },193 "topJoin": {194 "$ref": "#/definitions/border"195 },196 "topLeft": {197 "$ref": "#/definitions/border"198 },199 "topRight": {200 "$ref": "#/definitions/border"201 },202 "bottomBody": {203 "$ref": "#/definitions/border"204 },205 "bottomJoin": {206 "$ref": "#/definitions/border"207 },208 "bottomLeft": {209 "$ref": "#/definitions/border"210 },211 "bottomRight": {212 "$ref": "#/definitions/border"213 },214 "bodyLeft": {215 "$ref": "#/definitions/border"216 },217 "bodyRight": {218 "$ref": "#/definitions/border"219 },220 "bodyJoin": {221 "$ref": "#/definitions/border"222 },223 "joinBody": {224 "$ref": "#/definitions/border"225 },226 "joinLeft": {227 "$ref": "#/definitions/border"228 },229 "joinRight": {230 "$ref": "#/definitions/border"231 },232 "joinJoin": {233 "$ref": "#/definitions/border"234 }235 },236 "additionalProperties": false237 };238 refVal1.errors = null;239 refVal[1] = refVal1;240 var refVal2 = (function() {241 var pattern0 = new RegExp('^[0-9]+$');242 return function validate(data, dataPath, parentData, parentDataProperty, rootData) {243 'use strict';244 var vErrors = null;245 var errors = 0;246 if (typeof data !== "string") {247 var err = {248 keyword: 'type',249 dataPath: (dataPath || '') + "",250 schemaPath: '#/type',251 params: {252 type: 'string'253 },254 message: 'should be string'255 };256 if (vErrors === null) vErrors = [err];257 else vErrors.push(err);258 errors++;259 }260 validate.errors = vErrors;261 return errors === 0;262 };263 })();264 refVal2.schema = {265 "type": "string"266 };267 refVal2.errors = null;268 refVal[2] = refVal2;269 var refVal3 = (function() {270 var pattern0 = new RegExp('^[0-9]+$');271 return function validate(data, dataPath, parentData, parentDataProperty, rootData) {272 'use strict';273 var vErrors = null;274 var errors = 0;275 if (rootData === undefined) rootData = data;276 if ((data && typeof data === "object" && !Array.isArray(data))) {277 var errs__0 = errors;278 var valid1 = true;279 for (var key0 in data) {280 var isAdditional0 = !(false || pattern0.test(key0));281 if (isAdditional0) {282 valid1 = false;283 var err = {284 keyword: 'additionalProperties',285 dataPath: (dataPath || '') + "",286 schemaPath: '#/additionalProperties',287 params: {288 additionalProperty: '' + key0 + ''289 },290 message: 'should NOT have additional properties'291 };292 if (vErrors === null) vErrors = [err];293 else vErrors.push(err);294 errors++;295 }296 }297 for (var key0 in data) {298 if (pattern0.test(key0)) {299 var errs_1 = errors;300 if (!refVal4(data[key0], (dataPath || '') + '[\'' + key0 + '\']', data, key0, rootData)) {301 if (vErrors === null) vErrors = refVal4.errors;302 else vErrors = vErrors.concat(refVal4.errors);303 errors = vErrors.length;304 }305 var valid1 = errors === errs_1;306 }307 }308 } else {309 var err = {310 keyword: 'type',311 dataPath: (dataPath || '') + "",312 schemaPath: '#/type',313 params: {314 type: 'object'315 },316 message: 'should be object'317 };318 if (vErrors === null) vErrors = [err];319 else vErrors.push(err);320 errors++;321 }322 validate.errors = vErrors;323 return errors === 0;324 };325 })();326 refVal3.schema = {327 "type": "object",328 "patternProperties": {329 "^[0-9]+$": {330 "$ref": "#/definitions/column"331 }332 },333 "additionalProperties": false334 };335 refVal3.errors = null;336 refVal[3] = refVal3;337 var refVal4 = (function() {338 var pattern0 = new RegExp('^[0-9]+$');339 return function validate(data, dataPath, parentData, parentDataProperty, rootData) {340 'use strict';341 var vErrors = null;342 var errors = 0;343 if ((data && typeof data === "object" && !Array.isArray(data))) {344 var errs__0 = errors;345 var valid1 = true;346 for (var key0 in data) {347 var isAdditional0 = !(false || key0 == 'alignment' || key0 == 'width' || key0 == 'wrapWord' || key0 == 'truncate' || key0 == 'paddingLeft' || key0 == 'paddingRight');348 if (isAdditional0) {349 valid1 = false;350 var err = {351 keyword: 'additionalProperties',352 dataPath: (dataPath || '') + "",353 schemaPath: '#/additionalProperties',354 params: {355 additionalProperty: '' + key0 + ''356 },357 message: 'should NOT have additional properties'358 };359 if (vErrors === null) vErrors = [err];360 else vErrors.push(err);361 errors++;362 }363 }364 var data1 = data.alignment;365 if (data1 !== undefined) {366 var errs_1 = errors;367 if (typeof data1 !== "string") {368 var err = {369 keyword: 'type',370 dataPath: (dataPath || '') + '.alignment',371 schemaPath: '#/properties/alignment/type',372 params: {373 type: 'string'374 },375 message: 'should be string'376 };377 if (vErrors === null) vErrors = [err];378 else vErrors.push(err);379 errors++;380 }381 var schema1 = validate.schema.properties.alignment.enum;382 var valid1;383 valid1 = false;384 for (var i1 = 0; i1 < schema1.length; i1++)385 if (equal(data1, schema1[i1])) {386 valid1 = true;387 break;388 } if (!valid1) {389 var err = {390 keyword: 'enum',391 dataPath: (dataPath || '') + '.alignment',392 schemaPath: '#/properties/alignment/enum',393 params: {394 allowedValues: schema1395 },396 message: 'should be equal to one of the allowed values'397 };398 if (vErrors === null) vErrors = [err];399 else vErrors.push(err);400 errors++;401 }402 var valid1 = errors === errs_1;403 }404 if (data.width !== undefined) {405 var errs_1 = errors;406 if (typeof data.width !== "number") {407 var err = {408 keyword: 'type',409 dataPath: (dataPath || '') + '.width',410 schemaPath: '#/properties/width/type',411 params: {412 type: 'number'413 },414 message: 'should be number'415 };416 if (vErrors === null) vErrors = [err];417 else vErrors.push(err);418 errors++;419 }420 var valid1 = errors === errs_1;421 }422 if (data.wrapWord !== undefined) {423 var errs_1 = errors;424 if (typeof data.wrapWord !== "boolean") {425 var err = {426 keyword: 'type',427 dataPath: (dataPath || '') + '.wrapWord',428 schemaPath: '#/properties/wrapWord/type',429 params: {430 type: 'boolean'431 },432 message: 'should be boolean'433 };434 if (vErrors === null) vErrors = [err];435 else vErrors.push(err);436 errors++;437 }438 var valid1 = errors === errs_1;439 }440 if (data.truncate !== undefined) {441 var errs_1 = errors;442 if (typeof data.truncate !== "number") {443 var err = {444 keyword: 'type',445 dataPath: (dataPath || '') + '.truncate',446 schemaPath: '#/properties/truncate/type',447 params: {448 type: 'number'449 },450 message: 'should be number'451 };452 if (vErrors === null) vErrors = [err];453 else vErrors.push(err);454 errors++;455 }456 var valid1 = errors === errs_1;457 }458 if (data.paddingLeft !== undefined) {459 var errs_1 = errors;460 if (typeof data.paddingLeft !== "number") {461 var err = {462 keyword: 'type',463 dataPath: (dataPath || '') + '.paddingLeft',464 schemaPath: '#/properties/paddingLeft/type',465 params: {466 type: 'number'467 },468 message: 'should be number'469 };470 if (vErrors === null) vErrors = [err];471 else vErrors.push(err);472 errors++;473 }474 var valid1 = errors === errs_1;475 }476 if (data.paddingRight !== undefined) {477 var errs_1 = errors;478 if (typeof data.paddingRight !== "number") {479 var err = {480 keyword: 'type',481 dataPath: (dataPath || '') + '.paddingRight',482 schemaPath: '#/properties/paddingRight/type',483 params: {484 type: 'number'485 },486 message: 'should be number'487 };488 if (vErrors === null) vErrors = [err];489 else vErrors.push(err);490 errors++;491 }492 var valid1 = errors === errs_1;493 }494 } else {495 var err = {496 keyword: 'type',497 dataPath: (dataPath || '') + "",498 schemaPath: '#/type',499 params: {500 type: 'object'501 },502 message: 'should be object'503 };504 if (vErrors === null) vErrors = [err];505 else vErrors.push(err);506 errors++;507 }508 validate.errors = vErrors;509 return errors === 0;510 };511 })();512 refVal4.schema = {513 "type": "object",514 "properties": {515 "alignment": {516 "type": "string",517 "enum": ["left", "right", "center"]518 },519 "width": {520 "type": "number"521 },522 "wrapWord": {523 "type": "boolean"524 },525 "truncate": {526 "type": "number"527 },528 "paddingLeft": {529 "type": "number"530 },531 "paddingRight": {532 "type": "number"533 }534 },535 "additionalProperties": false536 };537 refVal4.errors = null;538 refVal[4] = refVal4;539 return function validate(data, dataPath, parentData, parentDataProperty, rootData) {540 'use strict'; /*# sourceURL=config.json */541 var vErrors = null;542 var errors = 0;543 if (rootData === undefined) rootData = data;544 if ((data && typeof data === "object" && !Array.isArray(data))) {545 var errs__0 = errors;546 var valid1 = true;547 for (var key0 in data) {548 var isAdditional0 = !(false || key0 == 'border' || key0 == 'columns' || key0 == 'columnDefault' || key0 == 'drawHorizontalLine');549 if (isAdditional0) {550 valid1 = false;551 var err = {552 keyword: 'additionalProperties',553 dataPath: (dataPath || '') + "",554 schemaPath: '#/additionalProperties',555 params: {556 additionalProperty: '' + key0 + ''557 },558 message: 'should NOT have additional properties'559 };560 if (vErrors === null) vErrors = [err];561 else vErrors.push(err);562 errors++;563 }564 }565 if (data.border !== undefined) {566 var errs_1 = errors;567 if (!refVal1(data.border, (dataPath || '') + '.border', data, 'border', rootData)) {568 if (vErrors === null) vErrors = refVal1.errors;569 else vErrors = vErrors.concat(refVal1.errors);570 errors = vErrors.length;571 }572 var valid1 = errors === errs_1;573 }574 if (data.columns !== undefined) {575 var errs_1 = errors;576 if (!refVal3(data.columns, (dataPath || '') + '.columns', data, 'columns', rootData)) {577 if (vErrors === null) vErrors = refVal3.errors;578 else vErrors = vErrors.concat(refVal3.errors);579 errors = vErrors.length;580 }581 var valid1 = errors === errs_1;582 }583 if (data.columnDefault !== undefined) {584 var errs_1 = errors;585 if (!refVal[4](data.columnDefault, (dataPath || '') + '.columnDefault', data, 'columnDefault', rootData)) {586 if (vErrors === null) vErrors = refVal[4].errors;587 else vErrors = vErrors.concat(refVal[4].errors);588 errors = vErrors.length;589 }590 var valid1 = errors === errs_1;591 }592 if (data.drawHorizontalLine !== undefined) {593 var errs_1 = errors;594 var errs__1 = errors;595 var valid1;596 valid1 = typeof data.drawHorizontalLine == "function";597 if (!valid1) {598 if (errs__1 == errors) {599 var err = {600 keyword: 'typeof',601 dataPath: (dataPath || '') + '.drawHorizontalLine',602 schemaPath: '#/properties/drawHorizontalLine/typeof',603 params: {604 keyword: 'typeof'605 },606 message: 'should pass "typeof" keyword validation'607 };608 if (vErrors === null) vErrors = [err];609 else vErrors.push(err);610 errors++;611 } else {612 for (var i1 = errs__1; i1 < errors; i1++) {613 var ruleErr1 = vErrors[i1];614 if (ruleErr1.dataPath === undefined) ruleErr1.dataPath = (dataPath || '') + '.drawHorizontalLine';615 if (ruleErr1.schemaPath === undefined) {616 ruleErr1.schemaPath = "#/properties/drawHorizontalLine/typeof";617 }618 }619 }620 }621 var valid1 = errors === errs_1;622 }623 } else {624 var err = {625 keyword: 'type',626 dataPath: (dataPath || '') + "",627 schemaPath: '#/type',628 params: {629 type: 'object'630 },631 message: 'should be object'632 };633 if (vErrors === null) vErrors = [err];634 else vErrors.push(err);635 errors++;636 }637 validate.errors = vErrors;638 return errors === 0;639 };640})();641validate.schema = {642 "$id": "config.json",643 "$schema": "http://json-schema.org/draft-07/schema#",644 "type": "object",645 "properties": {646 "border": {647 "$ref": "#/definitions/borders"648 },649 "columns": {650 "$ref": "#/definitions/columns"651 },652 "columnDefault": {653 "$ref": "#/definitions/column"654 },655 "drawHorizontalLine": {656 "typeof": "function"657 }658 },659 "additionalProperties": false,660 "definitions": {661 "columns": {662 "type": "object",663 "patternProperties": {664 "^[0-9]+$": {665 "$ref": "#/definitions/column"666 }667 },668 "additionalProperties": false669 },670 "column": {671 "type": "object",672 "properties": {673 "alignment": {674 "type": "string",675 "enum": ["left", "right", "center"]676 },677 "width": {678 "type": "number"679 },680 "wrapWord": {681 "type": "boolean"682 },683 "truncate": {684 "type": "number"685 },686 "paddingLeft": {687 "type": "number"688 },689 "paddingRight": {690 "type": "number"691 }692 },693 "additionalProperties": false694 },695 "borders": {696 "type": "object",697 "properties": {698 "topBody": {699 "$ref": "#/definitions/border"700 },701 "topJoin": {702 "$ref": "#/definitions/border"703 },704 "topLeft": {705 "$ref": "#/definitions/border"706 },707 "topRight": {708 "$ref": "#/definitions/border"709 },710 "bottomBody": {711 "$ref": "#/definitions/border"712 },713 "bottomJoin": {714 "$ref": "#/definitions/border"715 },716 "bottomLeft": {717 "$ref": "#/definitions/border"718 },719 "bottomRight": {720 "$ref": "#/definitions/border"721 },722 "bodyLeft": {723 "$ref": "#/definitions/border"724 },725 "bodyRight": {726 "$ref": "#/definitions/border"727 },728 "bodyJoin": {729 "$ref": "#/definitions/border"730 },731 "joinBody": {732 "$ref": "#/definitions/border"733 },734 "joinLeft": {735 "$ref": "#/definitions/border"736 },737 "joinRight": {738 "$ref": "#/definitions/border"739 },740 "joinJoin": {741 "$ref": "#/definitions/border"742 }743 },744 "additionalProperties": false745 },746 "border": {747 "type": "string"748 }749 }750};751validate.errors = null;...
test_mixins.py
Source:test_mixins.py
...201 serializer = MainSerializer(data=data)202 assert(not serializer.is_valid(raise_exception=False))203 assert(serializer.errors['field_errors'] == {})204 assert(serializer.errors['non_field_errors'] == [{'code': 'parent-non-field-error'}, ])205 def test_nested_serializer_with_drf_and_custom_errors(self):206 data = {207 'int_field': 1,208 'custom_field': 'something',209 'list_field': [],210 'nested_field': {211 'custom_field': 'raise_multiple_field_errors',212 'list_field': [1, 2, 'a']213 },214 'nested_field_unformatted': {215 'custom_field': 'raise_multiple_field_errors',216 'list_field': [1, 2, 'a']217 },218 'nested_list_field': [],219 'nested_list_field_unformatted': []...
test_tidy.py
Source:test_tidy.py
1# Copyright 2013 The Servo Project Developers. See the COPYRIGHT2# file at the top-level directory of this distribution.3#4# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or5# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license6# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your7# option. This file may not be copied, modified, or distributed8# except according to those terms.9import os10import unittest11from servo_tidy import tidy12base_path = 'servo_tidy_tests/' if os.path.exists('servo_tidy_tests/') else 'python/tidy/servo_tidy_tests/'13def iterFile(name):14 return iter([os.path.join(base_path, name)])15class CheckTidiness(unittest.TestCase):16 def assertNoMoreErrors(self, errors):17 with self.assertRaises(StopIteration):18 errors.next()19 def test_tidy_config(self):20 errors = tidy.check_config_file(os.path.join(base_path, 'servo-tidy.toml'), print_text=False)21 self.assertEqual("invalid config key 'key-outside'", errors.next()[2])22 self.assertEqual("invalid config key 'wrong-key'", errors.next()[2])23 self.assertEqual('invalid config table [wrong]', errors.next()[2])24 self.assertEqual("ignored file './fake/file.html' doesn't exist", errors.next()[2])25 self.assertEqual("ignored directory './fake/dir' doesn't exist", errors.next()[2])26 self.assertNoMoreErrors(errors)27 def test_directory_checks(self):28 dirs = {29 os.path.join(base_path, "dir_check/webidl_plus"): ['webidl', 'test'],30 os.path.join(base_path, "dir_check/only_webidl"): ['webidl']31 }32 errors = tidy.check_directory_files(dirs)33 error_dir = os.path.join(base_path, "dir_check/webidl_plus")34 self.assertEqual("Unexpected extension found for test.rs. We only expect files with webidl, test extensions in {0}".format(error_dir), errors.next()[2])35 self.assertEqual("Unexpected extension found for test2.rs. We only expect files with webidl, test extensions in {0}".format(error_dir), errors.next()[2])36 self.assertNoMoreErrors(errors)37 def test_spaces_correctnes(self):38 errors = tidy.collect_errors_for_files(iterFile('wrong_space.rs'), [], [tidy.check_by_line], print_text=False)39 self.assertEqual('trailing whitespace', errors.next()[2])40 self.assertEqual('no newline at EOF', errors.next()[2])41 self.assertEqual('tab on line', errors.next()[2])42 self.assertEqual('CR on line', errors.next()[2])43 self.assertEqual('no newline at EOF', errors.next()[2])44 self.assertNoMoreErrors(errors)45 def test_empty_file(self):46 errors = tidy.collect_errors_for_files(iterFile('empty_file.rs'), [], [tidy.check_by_line], print_text=False)47 self.assertEqual('file is empty', errors.next()[2])48 self.assertNoMoreErrors(errors)49 def test_long_line(self):50 errors = tidy.collect_errors_for_files(iterFile('long_line.rs'), [], [tidy.check_by_line], print_text=False)51 self.assertEqual('Line is longer than 120 characters', errors.next()[2])52 self.assertNoMoreErrors(errors)53 def test_whatwg_link(self):54 errors = tidy.collect_errors_for_files(iterFile('whatwg_link.rs'), [], [tidy.check_by_line], print_text=False)55 self.assertTrue('link to WHATWG may break in the future, use this format instead:' in errors.next()[2])56 self.assertTrue('links to WHATWG single-page url, change to multi page:' in errors.next()[2])57 self.assertNoMoreErrors(errors)58 def test_license(self):59 errors = tidy.collect_errors_for_files(iterFile('incorrect_license.rs'), [], [tidy.check_license], print_text=False)60 self.assertEqual('incorrect license', errors.next()[2])61 self.assertNoMoreErrors(errors)62 def test_shebang_license(self):63 errors = tidy.collect_errors_for_files(iterFile('shebang_license.py'), [], [tidy.check_license], print_text=False)64 self.assertEqual('missing blank line after shebang', errors.next()[2])65 self.assertNoMoreErrors(errors)66 def test_shell(self):67 errors = tidy.collect_errors_for_files(iterFile('shell_tidy.sh'), [], [tidy.check_shell], print_text=False)68 self.assertEqual('script does not have shebang "#!/usr/bin/env bash"', errors.next()[2])69 self.assertEqual('script is missing options "set -o errexit", "set -o pipefail"', errors.next()[2])70 self.assertEqual('script should not use backticks for command substitution', errors.next()[2])71 self.assertEqual('variable substitutions should use the full \"${VAR}\" form', errors.next()[2])72 self.assertEqual('script should use `[[` instead of `[` for conditional testing', errors.next()[2])73 self.assertEqual('script should use `[[` instead of `[` for conditional testing', errors.next()[2])74 self.assertNoMoreErrors(errors)75 def test_apache2_incomplete(self):76 errors = tidy.collect_errors_for_files(iterFile('apache2_license.rs'), [], [tidy.check_license])77 self.assertEqual('incorrect license', errors.next()[2])78 def test_rust(self):79 errors = tidy.collect_errors_for_files(iterFile('rust_tidy.rs'), [], [tidy.check_rust], print_text=False)80 self.assertEqual('extra space after use', errors.next()[2])81 self.assertEqual('extra space after {', errors.next()[2])82 self.assertEqual('extra space before }', errors.next()[2])83 self.assertEqual('use statement spans multiple lines', errors.next()[2])84 self.assertEqual('missing space before }', errors.next()[2])85 self.assertTrue('use statement is not in alphabetical order' in errors.next()[2])86 self.assertEqual('use statement contains braces for single import', errors.next()[2])87 self.assertTrue('use statement is not in alphabetical order' in errors.next()[2])88 self.assertEqual('encountered whitespace following a use statement', errors.next()[2])89 self.assertTrue('mod declaration is not in alphabetical order' in errors.next()[2])90 self.assertEqual('mod declaration spans multiple lines', errors.next()[2])91 self.assertTrue('extern crate declaration is not in alphabetical order' in errors.next()[2])92 self.assertEqual('found an empty line following a {', errors.next()[2])93 self.assertEqual('missing space before ->', errors.next()[2])94 self.assertEqual('missing space after ->', errors.next()[2])95 self.assertEqual('missing space after :', errors.next()[2])96 self.assertEqual('missing space before {', errors.next()[2])97 self.assertEqual('missing space before =', errors.next()[2])98 self.assertEqual('missing space after =', errors.next()[2])99 self.assertEqual('missing space before -', errors.next()[2])100 self.assertEqual('missing space before *', errors.next()[2])101 self.assertEqual('missing space after =>', errors.next()[2])102 self.assertEqual('missing space after :', errors.next()[2])103 self.assertEqual('missing space after :', errors.next()[2])104 self.assertEqual('extra space before :', errors.next()[2])105 self.assertEqual('extra space before :', errors.next()[2])106 self.assertEqual('use &[T] instead of &Vec<T>', errors.next()[2])107 self.assertEqual('use &str instead of &String', errors.next()[2])108 self.assertEqual('use &T instead of &Root<T>', errors.next()[2])109 self.assertEqual('encountered function signature with -> ()', errors.next()[2])110 self.assertEqual('operators should go at the end of the first line', errors.next()[2])111 self.assertEqual('else braces should be on the same line', errors.next()[2])112 self.assertEqual('extra space after (', errors.next()[2])113 self.assertEqual('extra space after (', errors.next()[2])114 self.assertEqual('extra space after (', errors.next()[2])115 self.assertEqual('extra space after test_fun', errors.next()[2])116 self.assertEqual('no = in the beginning of line', errors.next()[2])117 self.assertEqual('space before { is not a multiple of 4', errors.next()[2])118 self.assertEqual('space before } is not a multiple of 4', errors.next()[2])119 self.assertEqual('extra space after if', errors.next()[2])120 self.assertNoMoreErrors(errors)121 feature_errors = tidy.collect_errors_for_files(iterFile('lib.rs'), [], [tidy.check_rust], print_text=False)122 self.assertTrue('feature attribute is not in alphabetical order' in feature_errors.next()[2])123 self.assertTrue('feature attribute is not in alphabetical order' in feature_errors.next()[2])124 self.assertTrue('feature attribute is not in alphabetical order' in feature_errors.next()[2])125 self.assertTrue('feature attribute is not in alphabetical order' in feature_errors.next()[2])126 self.assertNoMoreErrors(feature_errors)127 ban_errors = tidy.collect_errors_for_files(iterFile('ban.rs'), [], [tidy.check_rust], print_text=False)128 self.assertEqual('Banned type Cell<JSVal> detected. Use MutJS<JSVal> instead', ban_errors.next()[2])129 self.assertNoMoreErrors(ban_errors)130 ban_errors = tidy.collect_errors_for_files(iterFile('ban-domrefcell.rs'), [], [tidy.check_rust], print_text=False)131 self.assertEqual('Banned type DOMRefCell<JS<T>> detected. Use MutJS<JS<T>> instead', ban_errors.next()[2])132 self.assertNoMoreErrors(ban_errors)133 def test_spec_link(self):134 tidy.SPEC_BASE_PATH = base_path135 errors = tidy.collect_errors_for_files(iterFile('speclink.rs'), [], [tidy.check_spec], print_text=False)136 self.assertEqual('method declared in webidl is missing a comment with a specification link', errors.next()[2])137 self.assertEqual('method declared in webidl is missing a comment with a specification link', errors.next()[2])138 self.assertNoMoreErrors(errors)139 def test_script_thread(self):140 errors = tidy.collect_errors_for_files(iterFile('script_thread.rs'), [], [tidy.check_rust], print_text=False)141 self.assertEqual('use a separate variable for the match expression', errors.next()[2])142 self.assertEqual('use a separate variable for the match expression', errors.next()[2])143 self.assertNoMoreErrors(errors)144 def test_webidl(self):145 errors = tidy.collect_errors_for_files(iterFile('spec.webidl'), [tidy.check_webidl_spec], [], print_text=False)146 self.assertEqual('No specification link found.', errors.next()[2])147 self.assertNoMoreErrors(errors)148 def test_toml(self):149 errors = tidy.collect_errors_for_files(iterFile('Cargo.toml'), [tidy.check_toml], [], print_text=False)150 self.assertEqual('found asterisk instead of minimum version number', errors.next()[2])151 self.assertEqual('.toml file should contain a valid license.', errors.next()[2])152 self.assertNoMoreErrors(errors)153 def test_modeline(self):154 errors = tidy.collect_errors_for_files(iterFile('modeline.txt'), [], [tidy.check_modeline], print_text=False)155 self.assertEqual('vi modeline present', errors.next()[2])156 self.assertEqual('vi modeline present', errors.next()[2])157 self.assertEqual('vi modeline present', errors.next()[2])158 self.assertEqual('emacs file variables present', errors.next()[2])159 self.assertEqual('emacs file variables present', errors.next()[2])160 self.assertNoMoreErrors(errors)161 def test_malformed_json(self):162 errors = tidy.collect_errors_for_files(iterFile('malformed_json.json'), [tidy.check_json], [], print_text=False)163 self.assertEqual('Invalid control character at: line 3 column 40 (char 61)', errors.next()[2])164 self.assertNoMoreErrors(errors)165 def test_json_with_duplicate_key(self):166 errors = tidy.collect_errors_for_files(iterFile('duplicate_key.json'), [tidy.check_json], [], print_text=False)167 self.assertEqual('Duplicated Key (the_duplicated_key)', errors.next()[2])168 self.assertNoMoreErrors(errors)169 def test_json_with_unordered_keys(self):170 tidy.config["check-ordered-json-keys"].append('python/tidy/servo_tidy_tests/unordered_key.json')171 errors = tidy.collect_errors_for_files(iterFile('unordered_key.json'), [tidy.check_json], [], print_text=False)172 self.assertEqual('Unordered key (found b before a)', errors.next()[2])173 self.assertNoMoreErrors(errors)174 def test_yaml_with_duplicate_key(self):175 errors = tidy.collect_errors_for_files(iterFile('duplicate_keys_buildbot_steps.yml'), [tidy.check_yaml], [], print_text=False)176 self.assertEqual('Duplicated Key (duplicate_yaml_key)', errors.next()[2])177 self.assertNoMoreErrors(errors)178 def test_non_list_mapped_buildbot_steps(self):179 errors = tidy.collect_errors_for_files(iterFile('non_list_mapping_buildbot_steps.yml'), [tidy.check_yaml], [], print_text=False)180 self.assertEqual("Key 'non-list-key' maps to type 'str', but list expected", errors.next()[2])181 self.assertNoMoreErrors(errors)182 def test_non_string_list_mapping_buildbot_steps(self):183 errors = tidy.collect_errors_for_files(iterFile('non_string_list_buildbot_steps.yml'), [tidy.check_yaml], [], print_text=False)184 self.assertEqual("List mapped to 'mapping_key' contains non-string element", errors.next()[2])185 self.assertNoMoreErrors(errors)186 def test_lock(self):187 errors = tidy.collect_errors_for_files(iterFile('duplicated_package.lock'), [tidy.check_lock], [], print_text=False)188 msg = """duplicate versions for package `test`189\t\x1b[93mThe following packages depend on version 0.4.9 from 'crates.io':\x1b[0m190\t\ttest2191\t\x1b[93mThe following packages depend on version 0.5.1 from 'crates.io':\x1b[0m"""192 self.assertEqual(msg, errors.next()[2])193 msg2 = """duplicate versions for package `test3`194\t\x1b[93mThe following packages depend on version 0.5.1 from 'crates.io':\x1b[0m195\t\ttest4196\t\x1b[93mThe following packages depend on version 0.5.1 from 'https://github.com/user/test3':\x1b[0m197\t\ttest5"""198 self.assertEqual(msg2, errors.next()[2])199 self.assertNoMoreErrors(errors)200 def test_lint_runner(self):201 test_path = base_path + 'lints/'202 runner = tidy.LintRunner(only_changed_files=False, progress=False)203 runner.path = test_path + 'some-fictional-file'204 self.assertEqual([(runner.path, 0, "file does not exist")], list(runner.check()))205 runner.path = test_path + 'not_script'206 self.assertEqual([(runner.path, 0, "lint should be a python script")],207 list(runner.check()))208 runner.path = test_path + 'not_inherited.py'209 self.assertEqual([(runner.path, 1, "class 'Lint' should inherit from 'LintRunner'")],210 list(runner.check()))211 runner.path = test_path + 'no_lint.py'212 self.assertEqual([(runner.path, 1, "script should contain a class named 'Lint'")],213 list(runner.check()))214 runner.path = test_path + 'no_run.py'215 self.assertEqual([(runner.path, 0, "class 'Lint' should implement 'run' method")],216 list(runner.check()))217 runner.path = test_path + 'invalid_error_tuple.py'218 self.assertEqual([(runner.path, 1, "errors should be a tuple of (path, line, reason)")],219 list(runner.check()))220 runner.path = test_path + 'proper_file.py'221 self.assertEqual([('path', 0, "foobar")], list(runner.check()))222 def test_file_list(self):223 base_path='./python/tidy/servo_tidy_tests/test_ignored'224 file_list = tidy.FileList(base_path, only_changed_files=False, exclude_dirs=[])225 lst = list(file_list)226 self.assertEqual([os.path.join(base_path, 'whee', 'test.rs'), os.path.join(base_path, 'whee', 'foo', 'bar.rs')], lst)227 file_list = tidy.FileList(base_path, only_changed_files=False,228 exclude_dirs=[os.path.join(base_path, 'whee', 'foo')])229 lst = list(file_list)230 self.assertEqual([os.path.join(base_path, 'whee', 'test.rs')], lst)231def do_tests():232 suite = unittest.TestLoader().loadTestsFromTestCase(CheckTidiness)...
errors_test.py
Source:errors_test.py
1# Copyright 2015 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for tensorflow.python.framework.errors."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19import gc20import pickle21import warnings22from tensorflow.core.lib.core import error_codes_pb223from tensorflow.python import _pywrap_file_io24from tensorflow.python.framework import c_api_util25from tensorflow.python.framework import errors26from tensorflow.python.framework import errors_impl27from tensorflow.python.platform import test28from tensorflow.python.util import compat29class ErrorsTest(test.TestCase):30 def _CountReferences(self, typeof):31 """Count number of references to objects of type |typeof|."""32 objs = gc.get_objects()33 ref_count = 034 for o in objs:35 try:36 if isinstance(o, typeof):37 ref_count += 138 # Certain versions of python keeps a weakref to deleted objects.39 except ReferenceError:40 pass41 return ref_count42 def testUniqueClassForEachErrorCode(self):43 for error_code, exc_type in [44 (errors.CANCELLED, errors_impl.CancelledError),45 (errors.UNKNOWN, errors_impl.UnknownError),46 (errors.INVALID_ARGUMENT, errors_impl.InvalidArgumentError),47 (errors.DEADLINE_EXCEEDED, errors_impl.DeadlineExceededError),48 (errors.NOT_FOUND, errors_impl.NotFoundError),49 (errors.ALREADY_EXISTS, errors_impl.AlreadyExistsError),50 (errors.PERMISSION_DENIED, errors_impl.PermissionDeniedError),51 (errors.UNAUTHENTICATED, errors_impl.UnauthenticatedError),52 (errors.RESOURCE_EXHAUSTED, errors_impl.ResourceExhaustedError),53 (errors.FAILED_PRECONDITION, errors_impl.FailedPreconditionError),54 (errors.ABORTED, errors_impl.AbortedError),55 (errors.OUT_OF_RANGE, errors_impl.OutOfRangeError),56 (errors.UNIMPLEMENTED, errors_impl.UnimplementedError),57 (errors.INTERNAL, errors_impl.InternalError),58 (errors.UNAVAILABLE, errors_impl.UnavailableError),59 (errors.DATA_LOSS, errors_impl.DataLossError),60 ]:61 # pylint: disable=protected-access62 self.assertTrue(63 isinstance(64 errors_impl._make_specific_exception(None, None, None,65 error_code), exc_type))66 # error_code_from_exception_type and exception_type_from_error_code should67 # be consistent with operation result.68 self.assertEqual(error_code,69 errors_impl.error_code_from_exception_type(exc_type))70 # pylint: enable=protected-access71 def testKnownErrorClassForEachErrorCodeInProto(self):72 for error_code in error_codes_pb2.Code.values():73 # pylint: disable=line-too-long74 if error_code in (75 error_codes_pb2.OK, error_codes_pb2.76 DO_NOT_USE_RESERVED_FOR_FUTURE_EXPANSION_USE_DEFAULT_IN_SWITCH_INSTEAD_77 ):78 continue79 # pylint: enable=line-too-long80 with warnings.catch_warnings(record=True) as w:81 # pylint: disable=protected-access82 exc = errors_impl._make_specific_exception(None, None, None, error_code)83 # pylint: enable=protected-access84 self.assertEqual(0, len(w)) # No warning is raised.85 self.assertTrue(isinstance(exc, errors_impl.OpError))86 self.assertTrue(errors_impl.OpError in exc.__class__.__bases__)87 def testUnknownErrorCodeCausesWarning(self):88 with warnings.catch_warnings(record=True) as w:89 # pylint: disable=protected-access90 exc = errors_impl._make_specific_exception(None, None, None, 37)91 # pylint: enable=protected-access92 self.assertEqual(1, len(w))93 self.assertTrue("Unknown error code: 37" in str(w[0].message))94 self.assertTrue(isinstance(exc, errors_impl.OpError))95 with warnings.catch_warnings(record=True) as w:96 # pylint: disable=protected-access97 exc = errors_impl.error_code_from_exception_type("Unknown")98 # pylint: enable=protected-access99 self.assertEqual(1, len(w))100 self.assertTrue("Unknown class exception" in str(w[0].message))101 self.assertTrue(isinstance(exc, errors_impl.OpError))102 def testStatusDoesNotLeak(self):103 try:104 _pywrap_file_io.DeleteFile(compat.as_bytes("/DOES_NOT_EXIST/"))105 except:106 pass107 gc.collect()108 self.assertEqual(0, self._CountReferences(c_api_util.ScopedTFStatus))109 def testPickleable(self):110 for error_code in [111 errors.CANCELLED,112 errors.UNKNOWN,113 errors.INVALID_ARGUMENT,114 errors.DEADLINE_EXCEEDED,115 errors.NOT_FOUND,116 errors.ALREADY_EXISTS,117 errors.PERMISSION_DENIED,118 errors.UNAUTHENTICATED,119 errors.RESOURCE_EXHAUSTED,120 errors.FAILED_PRECONDITION,121 errors.ABORTED,122 errors.OUT_OF_RANGE,123 errors.UNIMPLEMENTED,124 errors.INTERNAL,125 errors.UNAVAILABLE,126 errors.DATA_LOSS,127 ]:128 # pylint: disable=protected-access129 exc = errors_impl._make_specific_exception(None, None, None, error_code)130 # pylint: enable=protected-access131 unpickled = pickle.loads(pickle.dumps(exc))132 self.assertEqual(exc.node_def, unpickled.node_def)133 self.assertEqual(exc.op, unpickled.op)134 self.assertEqual(exc.message, unpickled.message)135 self.assertEqual(exc.error_code, unpickled.error_code)136if __name__ == "__main__":...
errors.py
Source:errors.py
1from utils import calc_angle_error, calc_dipole_error2import numpy as np3class Errors():4 def make_full_error_lists(self, results):5 for i in results.values():6 angle_error = calc_angle_error(i["tddft_dipole"], i["xtb_dipole"])7 self.chromophores.append(i)8 self.Na_Ncs.append(i["Na_Nc"])9 self.tddft_energies.append(i["tddft_energy"])10 self.xtb_energies.append(i["xtb_energy"])11 self.tddft_dipoles.append(i["tddft_dipole"])12 self.xtb_dipoles.append(i["xtb_dipole"])13 self.tddft_dipole_mags.append(np.linalg.norm(i["tddft_dipole"]))14 self.xtb_dipole_mags.append(np.linalg.norm(i["xtb_dipole"]))15 self.energy_errors.append(i["xtb_energy"] - i["tddft_energy"])16 self.dipole_errors.append(calc_dipole_error(i["xtb_dipole"], i["tddft_dipole"]))17 self.tddft_angle_errors.append(calc_angle_error(i["Na_Nc"], i["tddft_dipole"]))18 self.xtb_angle_errors.append(calc_angle_error(i["Na_Nc"], i["xtb_dipole"]))19 self.tddft_energies = np.array(self.tddft_energies)20 self.xtb_energies = np.array(self.xtb_energies)21 self.energy_errors = np.array(self.energy_errors)22 self.dipole_errors = np.array(self.dipole_errors)23 self.tddft_angle_errors = np.array(self.tddft_angle_errors)24 self.xtb_angle_errors = np.array(self.xtb_angle_errors)25 self.tddft_energies *= 27.2114 #hartree to eV26 self.xtb_energies *= 27.2114 #hartree to eV27 self.energy_errors *= 27.2114 #hartree to eV28 def clean_by_Z_value(self, full_errors, mean, stddev):29 Z_value = lambda x : (x - mean)/stddev30 self.z_values = [Z_value(x) for x in full_errors.energy_errors]31 for enum, z in enumerate(self.z_values):32 if abs(z) < 2:33 self.chromophores.append(full_errors.chromophores[enum])34 self.Na_Ncs.append(full_errors.Na_Ncs[enum])35 self.tddft_energies.append(full_errors.tddft_energies[enum])36 self.xtb_energies.append(full_errors.xtb_energies[enum])37 self.tddft_dipoles.append(full_errors.tddft_dipoles[enum])38 self.xtb_dipoles.append(full_errors.xtb_dipoles[enum])39 self.tddft_dipole_mags.append(full_errors.tddft_dipole_mags[enum])40 self.xtb_dipole_mags.append(full_errors.xtb_dipole_mags[enum])41 self.tddft_angle_errors.append(full_errors.tddft_angle_errors[enum])42 self.xtb_angle_errors.append(full_errors.xtb_angle_errors[enum])43 self.energy_errors.append(full_errors.energy_errors[enum])44 self.dipole_errors.append(full_errors.dipole_errors[enum])45 self.tddft_energies = np.array(self.tddft_energies)46 self.xtb_energies = np.array(self.xtb_energies)47 self.tddft_dipole_mags = np.array(self.tddft_dipole_mags)48 self.xtb_dipole_mags = np.array(self.xtb_dipole_mags)49 self.energy_errors = np.array(self.energy_errors)50 self.dipole_errors = np.array(self.dipole_errors)51 self.tddft_angle_errors = np.array(self.tddft_angle_errors)52 self.xtb_angle_errors = np.array(self.xtb_angle_errors)53 def __init__(self, results=None, full_errors=None, mean=None, stddev=None, with_outliers=True):54 self.chromophores = []55 self.Na_Ncs = []56 self.tddft_energies = []57 self.xtb_energies = []58 self.tddft_dipoles = []59 self.xtb_dipoles = []60 self.tddft_dipole_mags = []61 self.xtb_dipole_mags = []62 self.energy_errors = []63 self.z_values = []64 self.dipole_errors = []65 self.tddft_angle_errors = []66 self.xtb_angle_errors = []67 if with_outliers:68 self.make_full_error_lists(results)69 else:70 assert(full_errors is not None and mean is not None and stddev is not None)71 self.clean_by_Z_value(full_errors, mean, stddev)72 assert(len(self.tddft_energies) == len(self.chromophores))73 assert(len(self.tddft_energies) == len(self.Na_Ncs))74 assert(len(self.tddft_energies) == len(self.xtb_energies))75 assert(len(self.tddft_energies) == len(self.tddft_dipoles))76 assert(len(self.tddft_energies) == len(self.xtb_dipoles))77 assert(len(self.tddft_energies) == len(self.energy_errors))78 assert(len(self.tddft_energies) == len(self.dipole_errors))79 assert(len(self.tddft_energies) == len(self.tddft_angle_errors))...
findbook.py
Source:findbook.py
1import os2import time3from findbooks import *4def checkCollection(barcodes, checker, hits, errors, len_title="short"):5 for barcode in barcodes:6 try:7 item = Item(barcode)8 item.get_marc_fields(len_title="long")9 c_return_item, c_hits = checker.check(item)10 if c_hits:11 msg = "Barcode: %s found at URL: %s\n" % (barcode, ", ".join(c_hits))12 print(msg)13 if barcode not in hits.keys():14 hits[barcode] = c_hits15 else:16 hits[barcode] += c_hits17 except Exception as e:18 error = "Barcode: %s experienced an error. %s\n" % (barcode, e)19 print(error)20 if barcode not in errors.keys():21 errors[barcode] = [error]22 else:23 errors[barcode].append(error)24 return hits, errors25def report(hits, errors, path=None):26 if not path:27 path = os.getcwd()28 hits_path = os.path.join(path, "hits-" + time.strftime("%Y%m%d%H%M%S", time.localtime())) + ".txt"29 errors_path = os.path.join(path, "errors-" + time.strftime("%Y%m%d%H%M%S", time.localtime())) + ".txt"30 with open(hits_path, 'a') as fout:31 for key in hits.keys():32 msg = "Barcode: %s found at URLs: %s\n" % (key, ", ".join(hits[key]))33 fout.write(msg)34 print("Hits written to: %s" % hits_path)35 with open(errors_path, 'a') as fout:36 for key in errors.keys():37 msg = "Barcode: %s experienced the following errors: %s\n" % (key, ", ".join(errors[key]))38 fout.write(msg)39 print("Errors written to: %s" % errors_path)40def checkAll(barcodes, hits, errors):41 ################################################################42 ### HATHI43 ################################################################44 h = HathiChecker()45 hits, errors = checkCollection(barcodes, h, hits, errors, len_title="long")46 ################################################################47 ### INTERNET ARCHIVE48 ################################################################49 i = IaChecker()50 hits, errors = checkCollection(barcodes, i, hits, errors, len_title="long")51 ################################################################52 ### JSTOR53 ################################################################54 #j = JstorChecker()55 #hits, errors = checkCollection(barcodes, j, hits, errors, len_title="short")56 ################################################################57 ### GOOGLE BOOKS58 ################################################################59 with open('google-api-key.txt', 'r') as fin:60 key = fin.read()61 g = GoogleChecker(key)62 hits, errors = checkCollection(barcodes, g, hits, errors, len_title="long")63 return hits, errors64def main():65 hits = dict()66 errors = dict()67 barcodes = []68 with open('not_online_1.txt', 'r') as fin:69 for line in fin:70 barcodes.append(line.strip())71 hits, errors = checkAll(barcodes, hits, errors)72 time.sleep(86400)#24 hrs73 barcodes = []74 with open('not_online_2.txt', 'r') as fin:75 for line in fin:76 barcodes.append(line.strip())77 hits, errors = checkAll(barcodes, hits, errors)78 report(hits, errors)...
error_tools.py
Source:error_tools.py
...66 )67# Stops linter complaining about invalid class name68convert_os_errors = _ConvertOSErrors69@contextmanager70def unwrap_errors(path_replace):71 """72 A context manager to re-write the paths in resource exceptions to be73 in the same context as the wrapped filesystem.74 The only parameter may be the path from the parent, if only one path75 is to be unwrapped. Or it may be a dictionary that maps wrapped76 paths on to unwrapped paths.77 """78 try:79 yield80 except errors.ResourceError as e:81 if hasattr(e, 'path'):82 if isinstance(path_replace, dict):83 e.path = path_replace.get(e.path, e.path)84 else:...
analysis2.py
Source:analysis2.py
1# This is a main class for one execution.2import os3import numpy as np4import pandas as pd5from currency import Strategy36from currency.Strategy3 import strategy, read_file7from multiprocessing import Pool, Queue8symbol_i = 'AUDNZD'9volume_i = 56363 # TODO depends on symbol e.g. EUR AUD relationship10entry_time_i = '04:10:00'11exit_time_i = '03:50:00'12# ticks_to_target_i = 6513ticks_to_stop_i = 100014save_i = True15# print(os.cpu_count())16# direction = 'long'17# entry_reason_time = 'ZEIT'18# tick = 0.0000119read_file(entry_time_i)20def daily_trades(name, trades_results):21 errors_return, trades_return = strategy(symbol_i, volume_i, entry_time_i, exit_time_i, name,22 ticks_to_stop_i, save_i)23 # errors_results.put(errors_return)24 trades_results.put(trades_return)25# for ticks_to_target in range(15, 400, 5):26# daily_trades(ticks_to_target)27target_range = range(15, 400, 5)28if __name__ == '__main__':29 analyse_errors = pd.DataFrame()30 analyse_trades = pd.DataFrame()31 pool = Pool(7)32 # myErrors= Queue()33 myTrades = Queue()34 pool.map(daily_trades, target_range, myTrades)35 for i in target_range:36 # errors_return = myErrors.get()37 trades_return = myTrades.get()38 # analyse_errors = analyse_errors.append(errors_return.iloc[0], ignore_index=True)39 # analyse_errors = analyse_errors.append(errors_return.iloc[1], ignore_index=True)40 # if len(errors_return.index) > 2:41 # analyse_errors = analyse_errors.append(errors_return.iloc[2], ignore_index=True)42 analyse_trades = analyse_trades.append(trades_return.iloc[0], ignore_index=True)43# print('_____________________________________________________________________________________________________')44# with Pool(6) as p:45# print('main line')46# p.map(process_a_day, date_list)47# # print(errors_return)48# # print(trades_return)49# # print(errors_return.iloc[0])50# # print(trades_return.iloc[0])51# analyse_errors = analyse_errors.append(errors_return.iloc[0], ignore_index=True)52# analyse_errors = analyse_errors.append(errors_return.iloc[1], ignore_index=True)53# if len(errors_return.index) > 2:54# analyse_errors = analyse_errors.append(errors_return.iloc[2], ignore_index=True)55# analyse_trades = analyse_trades.append(trades_return.iloc[0], ignore_index=True)56 pool.close()57 pool.join()58 print(analyse_errors)59 print(analyse_trades)60 path = 'C:/trading_data/'61 analyse_trades.to_excel(path + 'trades_summary.xlsx')...
Using AI Code Generation
1const { Pact } = require('@pact-foundation/pact-node');2console.log(Pact.Errors.PactBinaryNotFound);3console.log(Pact.Errors.PactBrokerFetchError);4console.log(Pact.Errors.PactBrokerPublishError);5console.log(Pact.Errors.PactBrokerVerificationError);6console.log(Pact.Errors.PactBrokerValidationError);7console.log(Pact.Errors.PactProcessError);8console.log(Pact.Errors.PactServerError);9console.log(Pact.Errors.PactTestError);10console.log(Pact.Errors.PactTestSetupError);11console.log(Pact.Errors.PactTestTimeoutError);12console.log(Pact.Errors.PactTestExecutionError);13console.log(Pact.Errors.PactTestVerificationError);14console.log(Pact.Errors.PactTestInteractionError);15console.log(Pact.Errors.PactTestInteractionNonExistentError);16console.log(Pact.Errors.PactTestInteractionProviderStateError);17console.log(Pact.Errors.PactTestInteractionProviderStateNonExistentError);18console.log(Pact.Errors.PactTestInteractionProviderStateMismatchError);19console.log(Pact.Errors.PactTestInteractionProviderStateSetupError);20console.log(Pact.Errors.PactTestInteractionProviderStateTeardownError);21console.log(Pact.Errors.PactTestInteractionProviderStateTimeoutError);
Using AI Code Generation
1var errors = require('pact-foundation-pact').errors;2var error = errors.createError('some error message');3var error = errors.createError('some error message', 500);4var error = errors.createError('some error message', 500, {extra: 'extra information'});5var error = errors.createError('some error message', 500, {extra: 'extra information'}, 'some error stack');6var error = errors.createError('some error message', 500, {extra: 'extra information'}, 'some error stack', 'some error name');7var error = errors.createError('some error message', 500, {extra: 'extra information'}, 'some error stack', 'some error name', {some: 'extra information'});
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!!