How to use requireBoolean method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

Preconditions.test.js

Source:Preconditions.test.js Github

copy

Full Screen

1import Preconditions from "./Preconditions.js";2const FUNCTION = function() {3};4const ARRAY = [5 1, 2, 36]7function testThrows(title, f, value, label, message) {8 test(title, () => {9 expect(10 () => f(value, label)11 ).toThrow(message);12 });13}14function testNotThrows(title, f, value) {15 test(title, () => {16 expect(17 () => f(value, "Label123")18 ).not19 .toThrow();20 });21}22// requireNonNull.......................................................................................................23testThrows("requireNonNull undefined", Preconditions.requireNonNull, undefined, "Label123", "Missing Label123");24testThrows("requireNonNull null", Preconditions.requireNonNull, null, "Label123", "Missing Label123");25testNotThrows("requireNonNull empty string", Preconditions.requireNonNull, "");26testNotThrows("requireNonNull false", Preconditions.requireNonNull, false);27testNotThrows("requireNonNull 0", Preconditions.requireNonNull, 0);28testNotThrows("requireNonNull array", Preconditions.requireNonNull, ARRAY);29testNotThrows("requireNonNull object", Preconditions.requireNonNull, {});30// requireArray.......................................................................................................31testThrows("requireArray undefined", Preconditions.requireArray, undefined, "Label123", "Missing Label123");32testThrows("requireArray null", Preconditions.requireArray, null, "Label123", "Missing Label123");33testThrows("requireArray false", Preconditions.requireArray, false, "Label123", "Expected array Label123 got false");34testThrows("requireArray 0", Preconditions.requireArray, 0, "Label123", "Expected array Label123 got 0");35testThrows("requireArray empty string", Preconditions.requireArray, "", "Label123", "Expected array Label123 got ");36testThrows("requireArray string", Preconditions.requireArray, "ABC123", "Label123", "Expected array Label123 got ABC123");37testThrows("requireArray function", Preconditions.requireArray, FUNCTION, "Label123", "Expected array Label123 got function () {}");38testThrows("requireArray object", Preconditions.requireArray, {}, "Label123", "Expected array Label123 got [object Object]");39testNotThrows("requireArray array", Preconditions.requireArray, ARRAY);40// requireBoolean.......................................................................................................41testThrows("requireBoolean undefined", Preconditions.requireBoolean, undefined, "Label123", "Missing Label123");42testThrows("requireBoolean null", Preconditions.requireBoolean, null, "Label123", "Missing Label123");43testNotThrows("requireBoolean false", Preconditions.requireBoolean, false);44testNotThrows("requireBoolean true", Preconditions.requireBoolean, true);45testThrows("requireBoolean 0", Preconditions.requireBoolean, 0, "Label123", "Expected boolean Label123 got 0");46testThrows("requireBoolean empty string", Preconditions.requireBoolean, "", "Label123", "Expected boolean Label123 got ");47testThrows("requireBoolean string", Preconditions.requireBoolean, "ABC123", "Label123", "Expected boolean Label123 got ABC123");48testThrows("requireBoolean function", Preconditions.requireBoolean, FUNCTION, "Label123", "Expected boolean Label123 got function () {}");49testThrows("requireBoolean object", Preconditions.requireBoolean, {}, "Label123", "Expected boolean Label123 got [object Object]");50testThrows("requireBoolean array", Preconditions.requireBoolean, [], "Label123", "Expected boolean Label123 got ");51// requireFunction.......................................................................................................52testThrows("requireFunction undefined", Preconditions.requireFunction, undefined, "Label123", "Missing Label123");53testThrows("requireFunction null", Preconditions.requireFunction, null, "Label123", "Missing Label123");54testThrows("requireFunction false", Preconditions.requireFunction, false, "Label123", "Expected function Label123 got false");55testThrows("requireFunction 0", Preconditions.requireFunction, 0, "Label123", "Expected function Label123 got 0");56testThrows("requireFunction empty string", Preconditions.requireFunction, "", "Label123", "Expected function Label123 got ");57testThrows("requireFunction string", Preconditions.requireFunction, "ABC123", "Label123", "Expected function Label123 got ABC123");58testThrows("requireFunction array", Preconditions.requireFunction, ARRAY, "Label123", "Expected function Label123 got 1,2,3");59testThrows("requireFunction object", Preconditions.requireFunction, {}, "Label123", "Expected function Label123 got [object Object]");60testNotThrows("requireFunction function", Preconditions.requireFunction, FUNCTION);61// requireNumber.......................................................................................................62function testRequireNumberThrows(title, value, lower, upper, message) {63 test(title, () => {64 expect(65 () => Preconditions.requireNumber(value, "Label123", lower, upper)66 ).toThrow(message);67 });68}69function testRequireNumberNotThrows(title, value, lower, upper) {70 test(title, () => {71 expect(72 () => Preconditions.requireNumber(value, "Label123", lower, upper)73 ).not74 .toThrow();75 });76}77testRequireNumberThrows("requireNumber undefined", undefined, null, null, "Missing Label123");78testRequireNumberThrows("requireNumber null", null, null, null, "Missing Label123");79testRequireNumberThrows("requireNumber false", false, null, null, "Expected number Label123 got false");80testRequireNumberThrows("requireNumber empty string", "", null, null, "Expected number Label123 got ");81testRequireNumberThrows("requireNumber string", "ABC123", null, null, "Expected number Label123 got ABC123");82testRequireNumberThrows("requireNumber function", FUNCTION, null, null, "Expected number Label123 got function () {}");83testRequireNumberThrows("requireNumber array", ARRAY, null, null, "Expected number Label123 got 1,2,3");84testRequireNumberThrows("requireNumber object", {}, null, null, "Expected number Label123 got [object Object]");85testRequireNumberThrows("requireNumber number < lower", 1, 2, null, "Expected Label123 1 >= 2");86testRequireNumberThrows("requireNumber number > upper", 2, null, 2, "Expected Label123 2 < 2");87testRequireNumberThrows("requireNumber number > upper #2", 3, null, 2, "Expected Label123 3 < 2");88testRequireNumberNotThrows("requireNumber number 0", 0);89testRequireNumberNotThrows("requireNumber number 1", 1);90testRequireNumberNotThrows("requireNumber number 1 lower=1", 1, 1);91testRequireNumberNotThrows("requireNumber number 2 lower=1", 2, 1);92testRequireNumberNotThrows("requireNumber number 1 upper=2", 1, null, 2);93testRequireNumberNotThrows("requireNumber number 2 upper=3", 2, null, 3);94testRequireNumberNotThrows("requireNumber number 2 lower1, upper=3", 2, 1, 3);95testRequireNumberNotThrows("requireNumber number 2 lower2, upper=3", 2, 2, 3);96// requirePositiveNumber.......................................................................................................97testThrows("requirePositiveNumber undefined", Preconditions.requirePositiveNumber, undefined, "Label123", "Missing Label123");98testThrows("requirePositiveNumber null", Preconditions.requirePositiveNumber, null, "Label123", "Missing Label123");99testThrows("requirePositiveNumber false", Preconditions.requirePositiveNumber, false, "Label123", "Expected number Label123 got false");100testThrows("requirePositiveNumber empty string", Preconditions.requirePositiveNumber, "", "Label123", "Expected number Label123 got ");101testThrows("requirePositiveNumber string", Preconditions.requirePositiveNumber, "ABC123", "Label123", "Expected number Label123 got ABC123");102testThrows("requirePositiveNumber function", Preconditions.requirePositiveNumber, FUNCTION, "Label123", "Expected number Label123 got function () {}");103testThrows("requirePositiveNumber array", Preconditions.requirePositiveNumber, ARRAY, "Label123", "Expected number Label123 got 1,2,3");104testThrows("requirePositiveNumber object", Preconditions.requirePositiveNumber, {}, "Label123", "Expected number Label123 got [object Object]");105testThrows("requirePositiveNumber number < 0", Preconditions.requirePositiveNumber, -1, "Label123", "Expected number Label123 >= 0 got -1");106testNotThrows("requirePositiveNumber number 0", Preconditions.requirePositiveNumber, 0);107testNotThrows("requirePositiveNumber number 1", Preconditions.requirePositiveNumber, 1);108// requireObject.......................................................................................................109testThrows("requireObject undefined", Preconditions.requireObject, undefined, "Label123", "Missing Label123");110testThrows("requireObject null", Preconditions.requireObject, null, "Label123", "Missing Label123");111testThrows("requireObject false", Preconditions.requireObject, false, "Label123", "Expected object Label123 got false");112testThrows("requireObject 0", Preconditions.requireObject, 0, "Label123", "Expected object Label123 got 0");113testThrows("requireObject empty string", Preconditions.requireObject, "", "Label123", "Expected object Label123 got ");114testThrows("requireObject string", Preconditions.requireObject, "ABC123", "Label123", "Expected object Label123 got ABC123");115testThrows("requireObject array", Preconditions.requireObject, ARRAY, "Label123", "Expected object Label123 got 1,2,3");116testThrows("requireObject function", Preconditions.requireObject, FUNCTION, "Label123", "Expected object Label123 got function () {}");117testNotThrows("requireObject object", Preconditions.requireObject, {});118// requireText.......................................................................................................119testThrows("requireText undefined", Preconditions.requireText, undefined, "Label123", "Missing Label123");120testThrows("requireText null", Preconditions.requireText, null, "Label123", "Missing Label123");121testThrows("requireText false", Preconditions.requireText, false, "Label123", "Expected string Label123 got false");122testThrows("requireText 0", Preconditions.requireText, 0, "Label123", "Expected string Label123 got 0");123testThrows("requireText array", Preconditions.requireText, ARRAY, "Label123", "Expected string Label123 got 1,2,3");124testThrows("requireText function", Preconditions.requireText, FUNCTION, "Label123", "Expected string Label123 got function () {}");125testThrows("requireText object", Preconditions.requireText, {}, "Label123", "Expected string Label123 got [object Object]");126testNotThrows("requireText empty string", Preconditions.requireText, "");127testNotThrows("requireText non empty string", Preconditions.requireText, "abc123");128// requireNonEmptyText.......................................................................................................129testThrows("requireNonEmptyText undefined", Preconditions.requireNonEmptyText, undefined, "Label123", "Missing Label123");130testThrows("requireNonEmptyText null", Preconditions.requireNonEmptyText, null, "Label123", "Missing Label123");131testThrows("requireNonEmptyText false", Preconditions.requireNonEmptyText, false, "Label123", "Expected string Label123 got false");132testThrows("requireNonEmptyText 0", Preconditions.requireNonEmptyText, 0, "Label123", "Expected string Label123 got 0");133testThrows("requireNonEmptyText array", Preconditions.requireNonEmptyText, ARRAY, "Label123", "Expected string Label123 got 1,2,3");134testThrows("requireNonEmptyText function", Preconditions.requireNonEmptyText, FUNCTION, "Label123", "Expected string Label123 got function () {}");135testThrows("requireNonEmptyText object", Preconditions.requireNonEmptyText, {}, "Label123", "Expected string Label123 got [object Object]");136testThrows("requireNonEmptyText empty string", Preconditions.requireNonEmptyText, "", "Label123", "Missing Label123");137testNotThrows("requireNonEmptyText non empty string", Preconditions.requireNonEmptyText, "abc123");138// optionalText.......................................................................................................139testNotThrows("optionalText undefined", Preconditions.optionalText, undefined, "Label123", "Missing Label123");140testNotThrows("optionalText null", Preconditions.optionalText, null, "Label123", "Missing Label123");141testThrows("optionalText false", Preconditions.optionalText, false, "Label123", "Expected string Label123 got false");142testThrows("optionalText 0", Preconditions.optionalText, 0, "Label123", "Expected string Label123 got 0");143testThrows("optionalText array", Preconditions.optionalText, ARRAY, "Label123", "Expected string Label123 got 1,2,3");144testThrows("optionalText function", Preconditions.optionalText, FUNCTION, "Label123", "Expected string Label123 got function () {}");145testThrows("optionalText object", Preconditions.optionalText, {}, "Label123", "Expected string Label123 got [object Object]");146testNotThrows("optionalText empty string", Preconditions.optionalText, "");147testNotThrows("optionalText non empty string", Preconditions.optionalText, "abc123");148// requireInstance......................................................................................................149class Test1 {150}151class Test2 extends Test1 {152}153class Test3 {154}155class Test4 {156 toString() {157 return "Test4!";158 }159}160function testRequireInstanceThrows(title, value, message) {161 test(title, () => {162 expect(163 () => Preconditions.requireInstance(value, Test1, "Label123")164 ).toThrow(message);165 });166}167function testRequireInstanceNotThrows(title, value) {168 test(title, () => {169 expect(170 () => Preconditions.requireInstance(value, Test1, "Label123")171 ).not172 .toThrow();173 });174}175testRequireInstanceThrows("requireInstance undefined", undefined, "Missing Label123");176testRequireInstanceThrows("requireInstance null", null, "Missing Label123");177testRequireInstanceThrows("requireInstance false", false, "Expected Test1 Label123 got false");178testRequireInstanceThrows("requireInstance instanceof false", new Test3(), "Expected Test1 Label123 got " + new Test3());179testRequireInstanceThrows("requireInstance instanceof false", new Test4(), "Expected Test1 Label123 got Test4!");180testRequireInstanceNotThrows("requireInstance instanceof class", new Test1());181testRequireInstanceNotThrows("requireInstance instanceof subclass", new Test2());182// optionalInstance......................................................................................................183function testOptionalInstanceThrows(title, value, message) {184 test(title, () => {185 expect(186 () => Preconditions.optionalInstance(value, Test1, "Label123")187 ).toThrow(message);188 });189}190function testOptionalInstanceNotThrows(title, value) {191 test(title, () => {192 expect(193 () => Preconditions.optionalInstance(value, Test1, "Label123")194 ).not195 .toThrow();196 });197}198testOptionalInstanceNotThrows("optionalInstance undefined", undefined);199testOptionalInstanceNotThrows("optionalInstance null", null);200testOptionalInstanceThrows("optionalInstance false", false, "Expected Test1 or nothing Label123 got false");201testOptionalInstanceThrows("optionalInstance instanceof false", new Test3(), "Expected Test1 or nothing Label123 got " + new Test3());202testOptionalInstanceThrows("optionalInstance instanceof false", new Test4(), "Expected Test1 or nothing Label123 got Test4!");203testOptionalInstanceNotThrows("optionalInstance instanceof class", new Test1());204testOptionalInstanceNotThrows("optionalInstance instanceof subclass", new Test2());205// optionalFunction......................................................................................................206function testOptionalFunctionThrows(title, value, message) {207 test(title, () => {208 expect(209 () => Preconditions.optionalFunction(value, "Label123")210 ).toThrow(message);211 });212}213function testOptionalFunctionNotThrows(title, value) {214 test(title, () => {215 expect(216 () => Preconditions.optionalFunction(value, "Label123")217 ).not218 .toThrow();219 });220}221testOptionalFunctionNotThrows("optionalFunction undefined", undefined);222testOptionalFunctionNotThrows("optionalFunction null", null);223testOptionalFunctionThrows("optionalFunction array", ARRAY, "Expected function Label123 or nothing got 1,2,3");224testOptionalFunctionThrows("optionalFunction false", false, "Expected function Label123 or nothing got false");225testOptionalFunctionThrows("optionalFunction class", new Test1(), "Expected function Label123 or nothing got [object Object]");226testOptionalFunctionNotThrows("optionalFunction function", FUNCTION);227testOptionalFunctionThrows("optionalFunction number", 123, "Expected function Label123 or nothing got 123");228testOptionalFunctionThrows("optionalFunction object", {}, "Expected function Label123 or nothing got ");...

Full Screen

Full Screen

iosCSSLocatorConverter.js

Source:iosCSSLocatorConverter.js Github

copy

Full Screen

...54 *55 * @param {CssNameValueObject} css A CSS object that has 'name' and 'value'56 * @returns {string} Either 'true' or 'false'. If value is empty, return 'true'57 */58function requireBoolean(css) {59 const val = css.value?.toLowerCase() || 'true'; // an omitted boolean attribute means 'true' (e.g.: input[checked] means checked is true)60 switch (val) {61 case '0':62 case 'false':63 return '0';64 case '1':65 case 'true':66 return '1';67 default:68 throw new TypeError(`'${css.name}' must be true, false or empty. Found '${css.value}'`);69 }70}71/**72 * Get the canonical form of a CSS attribute name73 *74 * Converts to lowercase and if an attribute name is an alias for something else, return75 * what it is an alias for76 *77 * @param {Object} css CSS object78 * @returns {string} The canonical attribute name79 */80function requireAttributeName(css) {81 const attrName = css.name.toLowerCase();82 // Check if it's supported and if it is, return it83 if (ALL_ATTRS.includes(attrName)) {84 return attrName.toLowerCase();85 }86 // If attrName is an alias for something else, return that87 for (const [officialAttr, aliasAttrs] of ATTRIBUTE_ALIASES) {88 if (aliasAttrs.includes(attrName)) {89 return officialAttr;90 }91 }92 throw new Error(`'${attrName}' is not a valid attribute. ` + `Supported attributes are '${ALL_ATTRS.join(', ')}'`);93}94/**95 * @typedef {Object} CssAttr96 * @property {?string} valueType Type of attribute (must be string or empty)97 * @property {?string} value Value of the attribute98 * @property {?string} operator The operator between value and value type (=, *=, , ^=, $=)99 */100/**101 * Convert a CSS attribute into a UiSelector method call102 *103 * @param {CssAttr} cssAttr CSS attribute object104 * @returns {string} CSS attribute parsed as UiSelector105 */106function parseAttr(cssAttr) {107 if (cssAttr.valueType && cssAttr.valueType !== 'string') {108 throw new TypeError(109 `'${cssAttr.name}=${cssAttr.value}' is an invalid attribute. ` +110 `Only 'string' and empty attribute types are supported. Found '${cssAttr.valueType}'`111 );112 }113 const attrName = toCamelCase(requireAttributeName(cssAttr));114 // Validate that it's a supported attribute115 if (!STR_ATTRS.includes(attrName) && !BOOLEAN_ATTRS.includes(attrName)) {116 throw new Error(117 `'${attrName}' is not supported. Supported attributes are ` + `'${[...STR_ATTRS, ...BOOLEAN_ATTRS].join(', ')}'`118 );119 }120 // Parse index if it's an index attribute121 if (attrName === 'index') {122 return { index: cssAttr.value };123 }124 if (BOOLEAN_ATTRS.includes(attrName)) {125 return `${attrName} == ${requireBoolean(cssAttr)}`;126 }127 let value = cssAttr.value || '';128 if (value === '') {129 return `[${attrName} LIKE ${value}]`;130 }131 switch (cssAttr.operator) {132 case '=':133 return `${attrName} == "${value}"`;134 case '*=':135 return `${attrName} MATCHES "${_.escapeRegExp(value)}"`;136 case '^=':137 return `${attrName} BEGINSWITH "${value}"`;138 case '$=':139 return `${attrName} ENDSWITH "${value}"`;140 case '~=':141 return `${attrName} CONTAINS "${value}"`;142 default:143 // Unreachable, but adding error in case a new CSS attribute is added.144 throw new Error(145 `Unsupported CSS attribute operator '${cssAttr.operator}'. ` + ` '=', '*=', '^=', '$=' and '~=' are supported.`146 );147 }148}149/**150 * @typedef {Object} CssPseudo151 * @property {?string} valueType The type of CSS pseudo selector (https://www.npmjs.com/package/css-selector-parser for reference)152 * @property {?string} name The name of the pseudo selector153 * @property {?string} value The value of the pseudo selector154 */155/**156 * Convert a CSS pseudo class to a UiSelector157 *158 * @param {CssPseudo} cssPseudo CSS Pseudo class159 * @returns {string} Pseudo selector parsed as UiSelector160 */161function parsePseudo(cssPseudo) {162 if (cssPseudo.valueType && cssPseudo.valueType !== 'string') {163 throw new Error(164 `'${cssPseudo.name}=${cssPseudo.value}'. ` +165 `Unsupported css pseudo class value type: '${cssPseudo.valueType}'. Only 'string' type or empty is supported.`166 );167 }168 const pseudoName = requireAttributeName(cssPseudo);169 if (BOOLEAN_ATTRS.includes(pseudoName)) {170 return `${toCamelCase(pseudoName)} == ${requireBoolean(cssPseudo)}`;171 }172 if (pseudoName === 'index') {173 return { index: cssPseudo.value };174 }175}176/**177 * @typedef {Object} CssRule178 * @property {?string} nestingOperator The nesting operator (aka: combinator https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors)179 * @property {?string} tagName The tag name (aka: type selector https://developer.mozilla.org/en-US/docs/Web/CSS/Type_selectors)180 * @property {?string[]} classNames An array of CSS class names181 * @property {?CssAttr[]} attrs An array of CSS attributes182 * @property {?CssPseudo[]} attrs An array of CSS pseudos183 * @property {?string} id CSS identifier184 * @property {?CssRule} rule A descendant of this CSS rule...

Full Screen

Full Screen

process-config.js

Source:process-config.js Github

copy

Full Screen

...57 this.requireString('errorOutput', '{stdout}\n{stderr}', true);58 this.requireString('startMessage', '', true);59 this.requireString('successMessage', 'Executed : {fullCommand}', true);60 this.requireString('errorMessage', 'Executed : {fullCommand}\nReturned with code {exitStatus}\n{stderr}', true);61 this.requireBoolean('promptToSave', true);62 this.requireBoolean('stream', false);63 this.requireBoolean('autoShowOutput', true);64 this.requireBoolean('autoHideOutput', false);65 this.requireBoolean('scrollLockEnabled', false);66 this.requireInteger('outputBufferSize', 80000, true);67 this.requireInteger('maxCompleted', null, true);68 this.requireString('startScript', null, true);69 this.requireString('successScript', null, true);70 this.requireString('errorScript', null, true);71 this.requireBoolean('scriptOnStart', false);72 this.requireBoolean('scriptOnSuccess', false);73 this.requireBoolean('scriptOnError', false);74 this.checkArguments();75 this.checkInputDialogs();76 this.checkPatterns();77 this.checkMenus();78 this.checkNotifications();79 }80 isValid() {81 if (this.namespace.trim().length === 0) {82 return false;83 }84 if (this.action.trim().length === 0) {85 return false;86 }87 if (this.command.trim().length === 0) {88 return false;89 }90 return true;91 }92 requireString(name, defaultValue, allowNull) {93 const value = this[name];94 if (allowNull) {95 if (_.isNull(value)) {96 return;97 }98 if (_.isUndefined(value)) {99 this[name] = null;100 return;101 }102 }103 if (!_.isString(value)) {104 return this[name] = defaultValue;105 }106 }107 requireBoolean(name, defaultValue) {108 const value = this[name];109 if (!_.isBoolean(value)) {110 return this[name] = defaultValue;111 }112 }113 requireInteger(name, defaultValue, allowNull) {114 const value = this[name];115 if (allowNull) {116 if (_.isNull(value)) {117 return;118 }119 if (_.isUndefined(value)) {120 this[name] = null;121 return;...

Full Screen

Full Screen

validations_spec.js

Source:validations_spec.js Github

copy

Full Screen

2describe("Validations",() => {3 describe("requireBoolean", () => {4 it("should work correctly", () => {5 const testBool = (val) => {6 [err, valid] = v.requireBoolean(val);7 return valid;8 }9 expect(testBool(true)).toBe(true);10 expect(testBool(false)).toBe(true);11 expect(testBool(1)).toBe(false);12 expect(testBool({})).toBe(false);13 expect(testBool([])).toBe(false);14 expect(testBool("str")).toBe(false);15 expect(testBool(null)).toBe(false);16 expect(testBool(undefined)).toBe(true);17 });18 });19 describe("requireInteger", () => {20 it("should work correctly", () => {...

Full Screen

Full Screen

define.js

Source:define.js Github

copy

Full Screen

1// Dependencies2const uuid = require('node-uuid');3const _ = require('underscore');4const t = require('./types');5const v = require('./validations');6const PREFIX = "LOCAL_ORM";7const define = ({name: schemaName, schema: schema}) => {8 let table_key = (table_name) => `${PREFIX}_${schemaName}_${table_name}`;9 const loadTable = (table_name) => {10 let s = window.localStorage[table_key(table_name)];11 return s ? JSON.parse(s) : [];12 }13 const commitTable = (table_name, entities) => {14 return window.localStorage[table_key(table_name)] = JSON.stringify(entities);15 }16 return _.reduce(Object.keys(schema), (memo, tableName) => {17 const tableConfig = schema[tableName];18 const fields = Object.keys(tableConfig);19 const fetchAll = () => loadTable(tableName);20 const setDefaultValues = (oldEntity) => {21 let entity = _.clone(oldEntity);22 fields.forEach( (k) => {23 if (!entity[k] && !_.isUndefined(tableConfig[k].defaultVal)) {24 let dv = tableConfig[k].defaultVal;25 entity[k] = _.isFunction(dv) ? dv() : dv26 };27 });28 return entity;29 };30 const addTypeValidation = (validations, type) => {31 let out = _.clone(validations);32 if (type === t.string) {33 out.unshift(v.requireString);34 } else if (type === t.integer) {35 out.unshift(v.requireInteger);36 } else if (type === t.boolean) {37 out.unshift(v.requireBoolean);38 } else {39 throw "Unsupported type";40 }41 return out;42 };43 // Exposed44 const validate = (oldEnt) => {45 let ent = setDefaultValues(oldEnt);46 const errors = _.reduce(fields, (memo, field) => {47 let validations = tableConfig[field]['validations'] || [];48 validations = addTypeValidation(validations, tableConfig[field]['type']);49 let fieldErrors = validations.map((validator) => {50 let [err, valid] = validator(ent[field]);51 return err;52 });53 fieldErrors = _.filter(fieldErrors, (x) => x !== null);54 if (fieldErrors.length > 0 ) {55 memo[field] = fieldErrors;56 }57 return memo;58 }, {});59 const valid = _.reduce(60 _.pairs(errors),61 (memo, val) => { return memo && (val[1].length === 0) }62 , true63 );64 return [errors, valid];65 }66 const create = (ent) => {67 const [err, valid] = validate(ent);68 if (valid) {69 ent.id = uuid.v1();70 let entities = fetchAll();71 entities.push(ent);72 commitTable(tableName, entities);73 return [null, ent];74 } else {75 return [err, null]76 }77 };78 const update = (ent) => {79 const [err, valid] = validate(ent);80 if (valid) {81 let entities = fetchAll();82 const ind = _.findIndex(entities, { id: ent.id });83 if (ind > -1) {84 entities[ind] = ent;85 commitTable(tableName, entities);86 return [null, ent];87 } else {88 return ['Not Found', null];89 }90 } else {91 return [err, null];92 }93 };94 const build = (opts = {}) => {95 let ent = setDefaultValues(opts);96 return ent;97 };98 const save = (oldEnt) => {99 let ent = setDefaultValues(oldEnt);100 if (ent.id) {101 return update(ent);102 } else {103 return create(ent);104 }105 };106 const find = (id) => {107 const ent = _.find(fetchAll(), {id: id});108 if (ent) {109 return ent;110 } else {111 throw `Entity with id ${id} does not exist`;112 }113 };114 const destroy = (id) => {115 let ent = find(id);116 let entities = fetchAll();117 let e = _.find(entities, { id: ent.id });118 let updatedEntities = _.without(entities, e);119 commitTable(tableName, updatedEntities);120 return true;121 };122 const all = (filterWith) => {123 return fetchAll();124 };125 const where = (filterWith) => {126 let allFields = _.union(fields, ['id']);127 if (_.isObject(filterWith)) {128 let keys = Object.keys(filterWith);129 _.each(keys, (key) => {130 if(allFields.indexOf(key) < 0) {131 throw `Key ${key} doesn't exists`;132 }133 });134 };135 if (!filterWith) {136 return fetchAll();137 } else {138 return _.filter(fetchAll(), filterWith);139 }140 };141 memo[tableName] = { save, find, destroy, all, where, validate, build };142 return memo;143 }, {});144};...

Full Screen

Full Screen

validation.js

Source:validation.js Github

copy

Full Screen

1import Joi from "joi";2import mongoose from "mongoose";3const type = {4 userName: Joi.string()5 .required()6 .trim(),7 name: Joi.string().trim(),8 otp: Joi.string().required().min(4).message("otp must contain atleast 4 digit"),9 password: Joi.string()10 .required()11 .pattern(12 new RegExp(13 "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=.*[@#$%^&+=])"14 )15 )16 .message(17 "Password must cantain 8-20 Characters ,at least 1 in LowerCase,at least 1 With UpperCase and atleast 1 Special Character"18 ),19 confirmPassword: Joi.any().valid(Joi.ref('password'))20 .required()21 .label('Confirm password')22 .messages({ 'any.only': '{{#label}} does not match with password' }),23 email: Joi.string()24 .required()25 .email({ minDomainSegments: 2 })26 .message("Please enter a valid email address")27 .normalize(),28 contactNumber: Joi.string().regex(/^[0-9]{10}$/).messages({ 'string.pattern.base': `Phone number must have 10 digits.` }).required(),29 Id: Joi.string()30 .required()31 .custom((value, helper) => {32 if (mongoose.Types.ObjectId.isValid(value)) { return true }33 else { return helper.message("Need a valid Id") }34 }),35 requireString: Joi.string().required(),36 notRequireString: Joi.string(),37 requireBoolean: Joi.boolean().required(),38 notRequireBoolean: Joi.boolean(),39 requireObject: Joi.object().required()40}41export const schemas = {42 blogOtpRequest: Joi.object().keys({43 userName: type.userName,44 email: type.email,45 password: type.password,46 confirmPassword: type.confirmPassword47 }),48 blogUserSignin: Joi.object().keys({49 email: type.email,50 password: type.password51 }),52 blogResendOtp: Joi.object().keys({53 userId: type.Id54 }),55 blogConfirmOtp: Joi.object().keys({56 userId: type.Id,57 otp: type.otp58 }),59 blogEditUserDetails: Joi.object().keys({60 name: type.name,61 email: type.email,62 contact: type.contactNumber63 }),64 blogforgetPasswordOtpRequest: Joi.object().keys({65 email: type.email66 }),67 blogforgetPasswordConfirmOtp: Joi.object().keys({68 userId: type.Id,69 otpId: type.Id,70 otp: type.otp,71 password: type.password,72 confirmPassword: type.confirmPassword73 }),74 blogforgetPasswordResendOtp: Joi.object().keys({75 userId: type.Id,76 otpId: type.Id77 }),78 blogEditName: Joi.object().keys({79 name: type.requireString80 }),81 blogEditEmailOtprequest: Joi.object().keys({82 email: type.email83 }),84 blogEditEmailConfirmOtp: Joi.object().keys({85 otpId: type.Id,86 otp: type.otp87 }),88 blogEditContactNumber: Joi.object().keys({89 contactNumber: type.contactNumber90 }),91 blogquestionreply: Joi.object().keys({92 reply: type.requireString,93 questionId: type.Id94 }),95 blogeditreply: Joi.object().keys({96 reply: type.requireString,97 replyId: type.Id98 }),99 blogaskquestion: Joi.object().keys({100 subject: type.requireString,101 question: type.requireString102 }),103 blogeditquestion: Joi.object().keys({104 subject: type.requireString,105 question: type.requireString,106 questionId: type.Id107 }),108 blogQuestionId: Joi.object().keys({109 questionId: type.Id110 }),111 blogReplyId: Joi.object().keys({112 replyId: type.Id113 }),114 blogUserName: Joi.object().keys({115 userName: type.userName116 }),117 blogSendRequestToPlay: Joi.object().keys({118 userName: type.userName,119 }),120 blogSendResponse: Joi.object().keys({121 userName: type.userName,122 accept: type.notRequireBoolean,123 request: type.notRequireBoolean,124 drawRequest: type.notRequireBoolean,125 pauseRequest: type.notRequireBoolean126 }),127 blogCreatedBoard: Joi.object().keys({128 player_1: type.userName,129 player_2: type.userName130 }),131 blogBoardData: Joi.object().keys({132 piece: type.requireObject,133 position: type.requireString,134 apponent: type.userName,135 }),136 blogSendingMail: Joi.object().keys({137 name: type.requireString,138 email: type.email,139 comment: type.requireString140 })...

Full Screen

Full Screen

Preconditions.js

Source:Preconditions.js Github

copy

Full Screen

...42 }43 /**44 * Throws an exception if the value is not a boolean.45 */46 static requireBoolean(value, label) {47 Preconditions.requireNonNull(value, label);48 if(typeof value !== "boolean"){49 reportError("Expected boolean " + label + " got " + value);50 }51 return value;52 }53 /**54 * Throws an exception if the value is not a number55 */56 static requireNumber(value, label, lower, upper) {57 Preconditions.requireNonNull(value, label);58 if(typeof value !== "number"){59 reportError("Expected number " + label + " got " + value);60 }...

Full Screen

Full Screen

validations.js

Source:validations.js Github

copy

Full Screen

1// Validation is a function that takes a single value,2// and returns an array of errors and a boolean validity.3const _ = require('underscore');4const wrap = (fn, err) => {5 return (val) => {6 if (_.isUndefined(val) || fn(val)) {7 return [null, true];8 } else {9 return [err, false];10 }11 };12};13const requireBoolean = wrap(_.isBoolean, "should be a boolean");14const requireString = wrap(_.isString, "should be a string");15const isInt = (value) => {16 return typeof value === "number" &&17 isFinite(value) &&18 Math.floor(value) === value;19};20const requireInteger = wrap(isInt, "should be an integer");21const present = (val) => {22 if (_.isUndefined(val) || _.isNull(val)) {23 return [ "should be present", false];24 } else {25 return [null, true];26 }27};28const maxLength = (max) => {29 return (val) => {30 if (_.isUndefined(val)) {31 return [null, true];32 }33 if (val.length) {34 if (val.length > max) {35 return ["max length exceeded", false];36 } else {37 return [null, true];38 }39 } else {40 return ["can't limit a max length: length is undefined", false];41 }42 };43};44const minLength = (min) => {45 return (val) => {46 if (_.isUndefined(val)) {47 return [null, true];48 }49 if (val && val.length) {50 if (val.length < min) {51 return ["min length exceeded", false];52 } else {53 return [null, true];54 }55 } else {56 return ["can't limit a min length: length is undefined", false];57 };58 };59};60const min = (min) => {61 return (val) => {62 if (val < min) {63 return [`should be more or equal to ${min}`, false]64 } else {65 return [null, true];66 };67 };68};69const max = (max) => {70 return (val) => {71 if (val > max) {72 return [`should be less or equal to ${max}`, false]73 } else {74 return [null, true];75 };76 };77};78const oneOf = (...args) => {79 return (val) => {80 if ((args || []).indexOf(val) > -1) {81 return [null, true];82 } else {83 return [`should be one of [${args}]`, false]84 };85 };86};87// Composite or88// Usage:89// let outerRange = or(minLength(10), maxLength(2));90const or = (v1, v2) => {91 return (val) => {92 let [err1, valid1] = v1(val);93 if (valid1) {94 return [null, true];95 }96 let [err2, valid2] = v2(val);97 if (valid2) {98 return [null, true];99 }100 return [`${err1}, ${err2}`, false];101 };102};103// Checks a value over a list of validations104const check = (val, validations) => {105 return _.reduce(validations, (memo, validation) => {106 const [err, valid] = validation(val);107 if (!valid) {108 memo[0].push(err);109 memo[1] = false;110 }111 return memo;112 }, [ [], true ]);113};114module.exports = {115 requireBoolean,116 requireInteger,117 requireString,118 present,119 min,120 max,121 maxLength,122 minLength,123 oneOf,124 or,125 check...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const assert = require('assert');3const opts = {4 capabilities: {5 }6};7async function main() {8 let client = await wdio.remote(opts);9 let element = await client.$('~Buttons');10 await element.click();11 let button = await client.$('~Rounded');12 await button.click();13 let element1 = await client.$('~Back');14 await element1.click();15 let element2 = await client.$('~Controls');16 await element2.click();17 let element3 = await client.$('~Segmented Controls');18 await element3.click();19 let element4 = await client.$('~Segment 2');20 await element4.click();21 let element5 = await client.$('~Segment 3');22 await element5.click();23 let element6 = await client.$('~Back');24 await element6.click();25 let element7 = await client.$('~Text Fields');26 await element7.click();27 let element8 = await client.$('~Rounded');28 await element8.click();29 let element9 = await client.$('~Back');30 await element9.click();31 let element10 = await client.$('~Search Bars');32 await element10.click();33 let element11 = await client.$('~Search Bar');34 await element11.click();35 let element12 = await client.$('~Back');36 await element12.click();37 let element13 = await client.$('~Sliders');38 await element13.click();39 let element14 = await client.$('~Slider');40 await element14.click();41 let element15 = await client.$('~Back');42 await element15.click();43 let element16 = await client.$('~Switches');44 await element16.click();45 let element17 = await client.$('~Switch');46 await element17.click();47 let element18 = await client.$('~Back');48 await element18.click();49 let element19 = await client.$('~Images');50 await element19.click();51 let element20 = await client.$('~Back');52 await element20.click();53 let element21 = await client.$('~Web View');

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4const expect = chai.expect;5chai.use(chaiAsPromised);6const HOST = 'localhost';7const PORT = 4723;8const caps = {9};10const driver = wd.promiseChainRemote(HOST, PORT);11driver.init(caps).then(() => {12 return driver.elementByAccessibilityId('IntegerA')13 .then(element => element.type('1'))14 .then(() => driver.elementByAccessibilityId('IntegerB'))15 .then(element => element.type('2'))16 .then(() => driver.elementByAccessibilityId('ComputeSumButton'))17 .then(element => element.click())18 .then(() => driver.elementByAccessibilityId('Answer'))19 .then(element => element.getAttribute('value'))20 .then(value => expect(value).to.equal('3'))21 .then(() => driver.elementByAccessibilityId('Show Alert'))22 .then(element => element.click())23 .then(() => driver.elementByAccessibilityId('OK'))24 .then(element => element.click())25 .then(() => driver.elementByAccessibilityId('Show Other Alert'))26 .then(element => element.click())27 .then(() => driver.elementByAccessibilityId('OK'))28 .then(element => element.click())29 .then(() => driver.elementByAccessibilityId('Show UIAAlert'))30 .then(element => element.click())31 .then(() => driver.elementByAccessibilityId('OK'))32 .then(element => element.click())33 .then(() => driver.elementByAccessibilityId('Show Other UIAAlert'))34 .then(element => element.click())35 .then(() => driver.elementByAccessibilityId('OK'))36 .then(element => element.click())37 .then(() => driver.elementByAccessibilityId('Show UIAActionSheet'))38 .then(element => element.click())39 .then(() => driver.elementByAccessibilityId('OK'))40 .then(element => element.click())41 .then(() => driver.elementByAccessibilityId

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const path = require('path');3const { AppiumDriver } = require('appium-base-driver');4const { XCUITestDriver } = require('appium-xcuitest-driver');5async function main() {6 const xdriver = new XCUITestDriver(new AppiumDriver());7 await driver.init({8 });9 await driver.requireBoolean('shouldUseCompactResponses', false);10}11main();12const { XCUITestDriver } = require('appium-xcuitest-driver');13const xdriver = new XCUITestDriver(new AppiumDriver());14const { XCUITestDriver } = require('appium-xcuitest-driver');15const xdriver = new XCUITestDriver(new AppiumDriver());16const { XCUITestDriver } = require('appium-xcuitest-driver');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { assert } = require('chai');2const wd = require('wd');3const { exec } = require('teen_process');4const { retryInterval } = require('asyncbox');5const { startServer } = require('appium');6const { XCUITEST_CAPS } = require('./desired');7const PORT = 4723;8describe('XCUITestDriver', function () {9 this.timeout(300000);10 let driver;11 before(async function () {12 const args = {13 defaultCapabilities: {14 },15 };16 const server = await startServer(args);17 driver = wd.promiseChainRemote('localhost', PORT);18 await driver.init(XCUITEST_CAPS);19 });20 after(async function () {21 await driver.quit();22 });23 it('should require boolean', async function () {24 const isRequireBoolean = await driver.requireBoolean();25 assert.equal(isRequireBoolean, true);26 });27});28const XCUITEST_CAPS = {

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2driver.init({3})4driver.elementByAccessibilityId('Search').then((element) => {5 driver.requireBoolean(element, 'enabled').then((enabled) => {6 console.log('Element is enabled: ' + enabled)7 })8})9driver.quit()

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Xcuitest Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful