Best JavaScript code snippet using appium-base-driver
utils.js
Source: utils.js
1const path = require('path');2const fs = require('fs');3const settings = require('./settings');4// å建æ件5function createFolderIfNotExists(outputFilePath) {6 const parent = path.dirname(outputFilePath);7 if (!fs.existsSync(parent)) {8 createFolderIfNotExists(parent);9 fs.mkdirSync(parent);10 }11}12// è·åæ件å表13function getJSFileList(root) {14 let res = [];15 let files = fs.readdirSync(root);16 files.forEach(file => {17 const pathname = path.join(root, file);18 const stat = fs.lstatSync(pathname);19 if (!stat.isDirectory() && /\.(js|jsx|ts|tsx|vue)$/.test(pathname)) {20 res.push(pathname);21 } else if (stat.isDirectory()) {22 res = res.concat(getJSFileList(pathname));23 }24 });25 return res;26}27// æ¯å¦ä¸ºä¸æ28module.exports.isChineaseText = function (value) {29 return value && /[\u4e00-\u9fa5ï¼ï¼ï¼ã]/.test(value);30}31const isEmpty = function (id) {32 return (id === null || id === undefined);33}34const isJSEmpty = (source) => {35 return isEmpty(source) || source.trim() === '';36};37module.exports.isEmpty = isEmpty;38module.exports.getJSFileList = getJSFileList;39// åæ件40module.exports.writeSync = function (outputFilePath, content) {41 createFolderIfNotExists(outputFilePath);42 fs.writeFileSync(outputFilePath, content);43}44module.exports.getUniqueId = (original, value, zhLocaleData, duplicateKeys) => {45 const id = original.replace(/\-\d+$/, '');46 let validId = id;47 while ((validId in zhLocaleData) && (zhLocaleData[validId] !== value)) {48 if (!duplicateKeys[id]) {49 duplicateKeys[id] = 1;50 } else {51 duplicateKeys[id] += 1;52 }53 validId = `${id}-${duplicateKeys[id]}`;54 }55 zhLocaleData[validId] = value;56 return validId;57}58module.exports.getUniqueImportId = (id, all) => {59 const revert = Object.keys(all).reduce((revert, key) => {60 if (revert[all[key]]) {61 return revert;62 }63 revert[all[key]] = key;64 return revert;65 }, {});66 if (revert[id]) {67 return revert[id];68 }69 const duplicateKeys = {};70 let validId = id;71 while (validId in all) {72 if (!duplicateKeys[id]) {73 duplicateKeys[id] = 1;74 } else {75 duplicateKeys[id] += 1;76 }77 validId = `${id}${duplicateKeys[id]}`;78 }79 return validId;80}81const getProcessFiles = (folders, excludes) => {82 if (!excludes) {83 excludes = [];84 }85 return folders.reduce((files, folder) => {86 const jsFiles = getJSFileList(path.resolve(process.cwd(), folder));87 jsFiles.forEach(file => {88 const isExcludes = excludes.some(exclude => {89 const relativePath = path.relative(exclude, file);90 return !/^\.\./.test(relativePath);91 });92 if (!isExcludes) {93 files = files.concat(file);94 }95 });96 return files;97 }, []);98};99module.exports.getProcessFiles = getProcessFiles;100const jsonCompatiable = (filepath) => {101 try {102 const fileContent = fs.readFileSync(filepath, 'UTF8');103 const value = eval(`${fileContent.replace(settings.Header, 'false? null: ')}`);104 if (Object.prototype.toString.call(value) === '[object Object]') {105 return value;106 }107 return {};108 } catch (e) {109 return {};110 }111}112module.exports.jsonCompatiable = jsonCompatiable;113module.exports.loadLocales = function (languages, baseFolder, isTs) {114 const resources = {};115 if (!languages || !languages.length) {116 return resources;117 }118 languages.forEach(language => {119 resources[language] = jsonCompatiable(path.resolve(baseFolder, `${language}.${isTs ? 'ts' : 'js'}`));120 if (!resources[language]) {121 resources[language] = {};122 }123 });124 return resources;125}126module.exports.asyncForEach = async function (array, callback) {127 for (let index = 0; index < array.length; index++) {128 await callback(array[index], index, array);129 }130}131// const removeComment = (source) => {132// return source.replace(/<!--[^(<!--)]*-->/g, '');133// };134const placeholder = '____VUE_PLACEHOLDER____';135// sourceå¯è½å·²æ´æ°ï¼æ¯å¦template136const getVueScriptContent = (source) => {137 if (isJSEmpty(source)) {138 return {};139 }140 const matchs = source.match(/(<script[^>]*>)((.*\n)*)(<\/script>)/);141 if (matchs) {142 const scripts = matchs[2];143 return {144 scripts,145 placeholder,146 wrapper: source.replace(scripts, placeholder),147 };148 }149 return {150 scripts: '',151 placeholder: '',152 wrapper: source,153 };154};155const extractChinease = (val) => {156 if (isEmpty(val)) {157 return val;158 }159 return val.match(/\s*([^>{"`'}<]*[\u4e00-\u9fa5]+[^<{"`'}>]*)\s*/g);160}161module.exports.getVueScriptContent = getVueScriptContent;162module.exports.extractChinease = extractChinease;...
validation.js
Source: validation.js
1export const validateEntryStatus = entries => {2 const domainRangeKeys = {};3 const rangeDomainKeys = {};4 const domainKeys = {};5 const rangeKeys = {};6 const duplicates = {};7 const cycles = {};8 const domains = {};9 const ranges = {};10 for (let i = 0; i < entries.length; i++) {11 //identify duplicates12 if (domainRangeKeys[entries[i].drKey]) {13 domainRangeKeys[entries[i].drKey].push(i);14 for (let j = 0; j < domainRangeKeys[entries[i].drKey].length; j++) {15 duplicates[domainRangeKeys[entries[i].drKey][j]] = true;16 }17 } else {18 domainRangeKeys[entries[i].drKey] = [i];19 }20 //populate ids for cycles identification21 if (rangeDomainKeys[entries[i].rdKey]) {22 rangeDomainKeys[entries[i].rdKey].push(i);23 } else {24 rangeDomainKeys[entries[i].rdKey] = [i];25 }26 //identify duplicate domains27 if (domainKeys[entries[i].domain]) {28 domainKeys[entries[i].domain].push(i);29 for (let j = 0; j < domainKeys[entries[i].domain].length; j++) {30 domains[domainKeys[entries[i].domain][j]] = true;31 }32 } else {33 domainKeys[entries[i].domain] = [i];34 }35 //populate ids for chains identification36 if (rangeKeys[entries[i].range]) {37 rangeKeys[entries[i].range].push(i);38 } else {39 rangeKeys[entries[i].range] = [i];40 }41 //pupulate initial status42 entries[i].status = "Valid";43 }44 //identify cycles45 const drKeys = Object.keys(domainRangeKeys);46 for (let i = 0; i < drKeys.length; i++) {47 let rdKey = rangeDomainKeys[drKeys[i]];48 if (rdKey) {49 for (let j = 0; j < rdKey.length; j++) {50 cycles[rdKey[j]] = true;51 }52 }53 }54 //identify chains55 const rKeys = Object.keys(rangeKeys);56 for (let i = 0; i < rKeys.length; i++) {57 let dKey = domainKeys[rKeys[i]];58 if (dKey) {59 for (let j = 0; j < dKey.length; j++) {60 ranges[dKey[j]] = true;61 }62 }63 }64 const dKeys = Object.keys(domainKeys);65 for (let i = 0; i < dKeys.length; i++) {66 let rKey = rangeKeys[dKeys[i]];67 if (rKey) {68 for (let j = 0; j < rKey.length; j++) {69 ranges[rKey[j]] = true;70 }71 }72 }73 //update status for all errors74 const domainsKeys = Object.keys(domains);75 const duplicateKeys = Object.keys(duplicates);76 const rangesKeys = Object.keys(ranges);77 const cycleKeys = Object.keys(cycles);78 for (let i = 0; i < domainsKeys.length; i++) {79 if (entries[domainsKeys[i]].status === "Valid") {80 entries[domainsKeys[i]].status = "Forks";81 } else {82 entries[domainsKeys[i]].status += " Forks";83 }84 }85 for (let i = 0; i < duplicateKeys.length; i++) {86 if (entries[duplicateKeys[i]].status === "Valid") {87 entries[duplicateKeys[i]].status = "Duplicate";88 } else if (entries[duplicateKeys[i]].status.includes("Forks")) {89 entries[duplicateKeys[i]].status = entries[duplicateKeys[i]].status.replace("Forks", "Duplicate");90 } else {91 entries[duplicateKeys[i]].status += " Duplicate";92 }93 }94 for (let i = 0; i < rangesKeys.length; i++) {95 if (entries[rangesKeys[i]].status === "Valid") {96 entries[rangesKeys[i]].status = "Chain";97 } else {98 entries[rangesKeys[i]].status += " Chain";99 }100 }101 for (let i = 0; i < cycleKeys.length; i++) {102 if (entries[cycleKeys[i]].status === "Valid") {103 entries[cycleKeys[i]].status = "Cycle";104 } else if (entries[cycleKeys[i]].status.includes("Chain")) {105 entries[cycleKeys[i]].status = entries[cycleKeys[i]].status.replace("Chain", "Cycle");106 } else {107 entries[cycleKeys[i]].status += " Cycle";108 }109 }110 return entries;111};112export const calculateValidationErrors = (entries) => {113 const errors = {};114 for (let i = 0; i < entries.length; i++) {115 errors[entries[i].status] = errors[entries[i].status] ? errors[entries[i].status] + 1 : 1;116 }117 return errors;...
helpers-specs.js
Source: helpers-specs.js
...15 });16 });17 describe('#duplicateKeys', function () {18 it('should translate key in an object', function () {19 duplicateKeys({'foo': 'hello world'}, 'foo', 'bar').should.eql({'foo': 'hello world', 'bar': 'hello world'});20 });21 it('should translate key in an object within an object', function () {22 duplicateKeys({'key': {'foo': 'hello world'}}, 'foo', 'bar').should.eql({'key': {'foo': 'hello world', 'bar': 'hello world'}});23 });24 it('should translate key in an object with an array', function () {25 duplicateKeys([26 {'key': {'foo': 'hello world'}},27 {'foo': 'HELLO WORLD'}28 ], 'foo', 'bar').should.eql([29 {'key': {'foo': 'hello world', 'bar': 'hello world'}},30 {'foo': 'HELLO WORLD', 'bar': 'HELLO WORLD'}31 ]);32 });33 it('should duplicate both keys', function () {34 duplicateKeys({35 'keyOne': {36 'foo': 'hello world',37 },38 'keyTwo': {39 'bar': 'HELLO WORLD',40 },41 }, 'foo', 'bar').should.eql({42 'keyOne': {43 'foo': 'hello world',44 'bar': 'hello world',45 },46 'keyTwo': {47 'bar': 'HELLO WORLD',48 'foo': 'HELLO WORLD',49 }50 });51 });52 it('should not do anything to primitives', function () {53 [0, 1, -1, true, false, null, undefined, '', 'Hello World'].forEach((item) => {54 should.equal(duplicateKeys(item), item);55 });56 });57 it('should rename keys on big complex objects', function () {58 const input = [59 {'foo': 'bar'},60 {61 hello: {62 world: {63 'foo': 'BAR',64 }65 },66 foo: 'bahr'67 },68 'foo',69 null,70 071 ];72 const expectedOutput = [73 {'foo': 'bar', 'FOO': 'bar'},74 {75 hello: {76 world: {77 'foo': 'BAR',78 'FOO': 'BAR',79 }80 },81 foo: 'bahr',82 FOO: 'bahr'83 },84 'foo',85 null,86 087 ];88 duplicateKeys(input, 'foo', 'FOO').should.deep.equal(expectedOutput);89 });90 });...
dirty-json.js
Source: dirty-json.js
1// < begin copyright > 2// Copyright Ryan Marcus 20183// 4// This program is free software: you can redistribute it and/or modify5// it under the terms of the GNU Affero General Public License as6// published by the Free Software Foundation, either version 3 of the7// License, or (at your option) any later version.8// 9// This program is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU Affero General Public License for more details.13// 14// You should have received a copy of the GNU Affero General Public License15// along with this program. If not, see <https://www.gnu.org/licenses/>.16// 17// < end copyright > 18 19"use strict";20let parser = require('./parser');21module.exports.parse = parse;22function parse(text, config) {23 let fallback = true;24 let duplicateKeys = false;25 if (config) {26 if (("fallback" in config) && config[fallback] === false) {27 fallback = false;28 }29 duplicateKeys = "duplicateKeys" in config && config["duplicateKeys"] === true;30 }31 try {32 return parser.parse(text, duplicateKeys);33 } catch (e) {34 // our parser threw an error! see if the JSON was valid...35 /* istanbul ignore next */36 if (fallback === false) {37 throw e;38 }39 40 try {41 let json = JSON.parse(text);42 // if we didn't throw, it was valid JSON!43 /* istanbul ignore next */44 console.warn("dirty-json got valid JSON that failed with the custom parser. We're returning the valid JSON, but please file a bug report here: https://github.com/RyanMarcus/dirty-json/issues -- the JSON that caused the failure was: " + text);45 /* istanbul ignore next */46 return json;47 } catch (json_error) {48 throw e;49 }50 }...
extract-i18n.js
Source: extract-i18n.js
...39 })40}41const defaultAction = (languageFiles) => {42 missingKeys(languageFiles)43 duplicateKeys(languageFiles)44}45program46 .version('0.0.1')47 .argument('<languageFiles>')48 .action(defaultAction)49program.command('missing-keys <languageFiles>')50 .action(missingKeys)51program.command('duplicate-keys <languageFiles>')52 .action(duplicateKeys)...
index.js
Source: index.js
1import getUser from "../../../../lib/auth/getUser";2import connectToDb from "../../../../lib/db/db";3import userModel from "../../../../lib/db/models/user";4async function updateUserDetails(userId, changes) {5 await connectToDb();6 try {7 await userModel.findByIdAndUpdate(userId, {8 $set: changes,9 });10 return {11 errorOccurred: false,12 httpCode: 200,13 message: "User details updated successfully.",14 changes: changes,15 };16 } catch (error) {17 if (error.code === 11000) {18 const duplicateKeys = [];19 for (var key in error.keyPattern) {20 duplicateKeys.push(key);21 }22 return {23 errorOccurred: true,24 httpCode: 400,25 message: "Duplicate keys.",26 duplicateKeys: duplicateKeys,27 };28 }29 return {30 errorOccurred: true,31 httpCode: 500,32 error: error,33 message: "Something went wrong.",34 };35 }36}37export default async function handler(req, res) {38 const user = getUser(req);39 if (!user) {40 return res.status(401).send({41 message: "Sign in to continue.",42 });43 }44 const changes = {};45 if (req.body.username) {46 changes.username = req.body.username;47 }48 if (req.body.name) {49 changes.name = req.body.name;50 }51 if (req.body.contactNumber) {52 changes.contactNumber = req.body.contactNumber;53 }54 if (req.body.privateProfile !== undefined) {55 changes.privateProfile = req.body.privateProfile;56 }57 const result = await updateUserDetails(user._id, changes);58 const status = result.httpCode;59 delete result.httpCode;60 return res.status(status).json({61 ...result,62 });...
DeduplicateValues.js
Source: DeduplicateValues.js
1/*2 * Copyright (C) 2020 Graylog, Inc.3 *4 * This program is free software: you can redistribute it and/or modify5 * it under the terms of the Server Side Public License, version 1,6 * as published by MongoDB, Inc.7 *8 * This program is distributed in the hope that it will be useful,9 * but WITHOUT ANY WARRANTY; without even the implied warranty of10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11 * Server Side Public License for more details.12 *13 * You should have received a copy of the Server Side Public License14 * along with this program. If not, see15 * <http://www.mongodb.com/licensing/server-side-public-license>.16 */17export default (rows, rowFieldNames) => {18 const duplicateKeys = {};19 return rows.map((item) => {20 const reducedItem = { ...item };21 const entries = Object.entries(reducedItem);22 entries.forEach(([key, value], entryIdx) => {23 if (!rowFieldNames.includes(key)) {24 return;25 }26 if (duplicateKeys[key] === value) {27 delete reducedItem[key];28 } else {29 entries.slice(entryIdx + 1)30 .forEach((entry) => delete duplicateKeys[entry[0]]);31 duplicateKeys[key] = value;32 }33 });34 return reducedItem;35 });...
generateSlug.js
Source: generateSlug.js
1"use strict";2var __importDefault = (this && this.__importDefault) || function (mod) {3 return (mod && mod.__esModule) ? mod : { "default": mod };4};5Object.defineProperty(exports, "__esModule", { value: true });6exports.createSlug = void 0;7const camelcase_keys_1 = __importDefault(require("camelcase-keys"));8const slugify_1 = __importDefault(require("slugify"));9const createSlug = (string, existingSlugs = {}, convertToCamelCase = false) => {10 const stringToLower = string.toLowerCase();11 const slugged = (0, slugify_1.default)(stringToLower, { remove: /[*+~.,()/'"!:@]/g });12 const convertedSlug = convertToCamelCase ? Object.keys((0, camelcase_keys_1.default)({ [slugged]: string }))[0] : slugged;13 const duplicateKeys = Object.keys(existingSlugs).filter((slug) => slug === convertedSlug);14 return duplicateKeys.length ? `${convertedSlug}${duplicateKeys.length + 1}` : convertedSlug;15};...
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var appium = require('appium-base-driver');3driver.getSession().then(function(session) {4 var caps = session.getCapabilities();5 var dupKeys = appium.helpers.duplicateKeys(caps);6 console.log(dupKeys);7 driver.quit();8});9var webdriver = require('selenium-webdriver');10var appium = require('appium-base-driver');11driver.getSession().then(function(session) {12 var caps = session.getCapabilities();13 var dupKeys = appium.helpers.duplicateKeys(caps);14 if (dupKeys.length > 0) {15 console.log('Duplicate keys found: ' + dupKeys);16 } else {17 console.log('No duplicate keys found');18 }19 driver.quit();20});
Using AI Code Generation
1const { BaseDriver } = require('appium-base-driver');2const { util } = require('appium-support');3let caps = {4};5let driver = new BaseDriver();6driver.createSession(caps);7let duplicateKeys = driver.duplicateKeys;8console.log(`Duplicate Keys: ${util.unwrapElement(duplicateKeys)}`);
Using AI Code Generation
1const { BaseDriver } = require('appium-base-driver');2const { desiredCapConstraints } = require('appium-base-driver');3let caps = {4};5const { BaseDriver } = require('appium-base-driver');6const { desiredCapConstraints } = require('appium-base-driver');7let caps = {8};9const { BaseDriver } = require('appium-base-driver');10const { desiredCapConstraints } = require('appium-base-driver');11let caps = {
Using AI Code Generation
1describe('Test', function() {2 it('should pass', function() {3 driver.duplicateKeys(3);4 });5});6describe('Test', function() {7 it('should pass', function() {8 driver.duplicateKeys(3);9 });10});11describe('Test', function() {12 it('should pass', function() {13 driver.duplicateKeys(3);14 });15});16describe('Test', function() {17 it('should pass', function() {18 driver.duplicateKeys(3);19 });20});21describe('Test', function() {22 it('should pass', function() {23 driver.duplicateKeys(3);24 });25});26describe('Test', function() {27 it('should pass', function() {28 driver.duplicateKeys(3);29 });30});31describe('Test', function() {32 it('should pass', function() {33 driver.duplicateKeys(3);34 });35});36describe('Test', function() {37 it('should pass', function() {38 driver.duplicateKeys(3);39 });40});41describe('Test', function() {42 it('should pass', function() {43 driver.duplicateKeys(3);44 });45});46describe('Test', function() {47 it('should pass', function() {48 driver.duplicateKeys(3);49 });50});51describe('Test', function() {52 it('should pass', function() {53 driver.duplicateKeys(3);54 });55});
Using AI Code Generation
1const BaseDriver = require('appium-base-driver');2const driver = new BaseDriver();3driver.duplicateKeys(2, 'a');4const BaseDriver = require('appium-base-driver');5const driver = new BaseDriver();6driver.duplicateKeys(2, 'a');7const BaseDriver = require('appium-base-driver');8const driver = new BaseDriver();9driver.duplicateKeys(2, 'a');10const BaseDriver = require('appium-base-driver');11const driver = new BaseDriver();12driver.duplicateKeys(2, 'a');13const BaseDriver = require('appium-base-driver');14const driver = new BaseDriver();15driver.duplicateKeys(2, 'a');16const BaseDriver = require('appium-base-driver');17const driver = new BaseDriver();18driver.duplicateKeys(2, 'a');19const BaseDriver = require('appium-base-driver');20const driver = new BaseDriver();21driver.duplicateKeys(2, 'a');22const BaseDriver = require('appium-base-driver');23const driver = new BaseDriver();24driver.duplicateKeys(2, 'a');25const BaseDriver = require('appium-base-driver');26const driver = new BaseDriver();27driver.duplicateKeys(2, 'a');28const BaseDriver = require('appium-base-driver');
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
Software testing is fueling the IT sector forward by scaling up the test process and continuous product delivery. Currently, this profession is in huge demand, as it needs certified testers with expertise in automation testing. When it comes to outsourcing software testing jobs, whether it’s an IT company or an individual customer, they all look for accredited professionals. That’s why having an software testing certification has become the need of the hour for the folks interested in the test automation field. A well-known certificate issued by an authorized institute kind vouches that the certificate holder is skilled in a specific technology.
Ruby is a programming language which is well suitable for web automation. Ruby makes an excellent choice because of its clean syntax, focus on built-in library integrations, and an active community. Another benefit of Ruby is that it also allows other programming languages like Java, Python, etc. to be used in order to automate applications written in any other frameworks. Therefore you can use Selenium Ruby to automate any sort of application in your system and test the results in any type of testing environment
I still remember the day when our delivery manager announced that from the next phase, the project is going to be Agile. After attending some training and doing some online research, I realized that as a traditional tester, moving from Waterfall to agile testing team is one of the best learning experience to boost my career. Testing in Agile, there were certain challenges, my roles and responsibilities increased a lot, workplace demanded for a pace which was never seen before. Apart from helping me to learn automation tools as well as improving my domain and business knowledge, it helped me get close to the team and participate actively in product creation. Here I will be sharing everything I learned as a traditional tester moving from Waterfall to Agile.
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Mobile App Testing Tutorial.
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!!