Best JavaScript code snippet using stryker-parent
statement-mutant-placer.spec.ts
Source:statement-mutant-placer.spec.ts
1import { expect } from 'chai';2import { types } from '@babel/core';3import generate from '@babel/generator';4import { normalizeWhitespaces } from '@stryker-mutator/util';5import { statementMutantPlacer } from '../../../src/mutant-placers/statement-mutant-placer';6import { findNodePath, parseJS } from '../../helpers/syntax-test-helpers';7import { Mutant } from '../../../src/mutant';8import { createMutant } from '../../helpers/factories';9describe('statementMutantPlacer', () => {10 it('should have the correct name', () => {11 expect(statementMutantPlacer.name).eq('statementMutantPlacer');12 });13 describe(statementMutantPlacer.canPlace.name, () => {14 it('should be false for anything but a statement', () => {15 [16 findNodePath(parseJS('foo + bar'), (p) => p.isBinaryExpression()),17 findNodePath(parseJS('foo = bar'), (p) => p.isAssignmentExpression()),18 findNodePath(parseJS('foo.bar()'), (p) => p.isCallExpression()),19 ].forEach((node) => {20 expect(statementMutantPlacer.canPlace(node)).false;21 });22 });23 it('should be able to place a mutant in a statement', () => {24 // Arrange25 const ast = parseJS('const foo = a + b');26 const statement = findNodePath(ast, (p) => p.isVariableDeclaration());27 // Act28 const actual = statementMutantPlacer.canPlace(statement);29 // Assert30 expect(actual).true;31 });32 });33 describe(statementMutantPlacer.place.name, () => {34 function arrangeSingleMutant() {35 const ast = parseJS('const foo = a + b');36 const statement = findNodePath<types.VariableDeclaration>(ast, (p) => p.isVariableDeclaration());37 const nodeToMutate = findNodePath<types.BinaryExpression>(ast, (p) => p.isBinaryExpression());38 const mutant = new Mutant('1', 'file.js', nodeToMutate.node, {39 replacement: types.binaryExpression('>>>', types.identifier('bar'), types.identifier('baz')),40 mutatorName: 'fooMutator',41 });42 const appliedMutants = new Map([[mutant, mutant.applied(statement.node)]]);43 return { statement, appliedMutants, ast };44 }45 it('should be able to place a mutant in a statement', () => {46 // Arrange47 const { statement, appliedMutants, ast } = arrangeSingleMutant();48 // Act49 statementMutantPlacer.place(statement, appliedMutants);50 const actualCode = normalizeWhitespaces(generate(ast).code);51 // Assert52 expect(actualCode).contains(normalizeWhitespaces('if (stryMutAct_9fa48("1")) { const foo = bar >>> baz; } else '));53 });54 it('should keep block statements in tact', () => {55 // Arrange56 const ast = parseJS('function add(a, b) { return a + b; }');57 const statement = findNodePath<types.BlockStatement>(ast, (p) => p.isBlockStatement());58 const originalNodePath = findNodePath<types.BinaryExpression>(ast, (p) => p.isBinaryExpression());59 const mutant = createMutant({60 original: originalNodePath.node,61 replacement: types.binaryExpression('>>>', types.identifier('a'), types.identifier('b')),62 });63 const appliedMutants = new Map([[mutant, mutant.applied(statement.node)]]);64 // Act65 statementMutantPlacer.place(statement, appliedMutants);66 const actualCode = normalizeWhitespaces(generate(ast).code);67 // Assert68 expect(actualCode).matches(/function\s*add\s*\(a,\s*b\)\s*{.*}/);69 });70 it('should place the original code as alternative (inside `else`)', () => {71 const { ast, appliedMutants, statement } = arrangeSingleMutant();72 statementMutantPlacer.place(statement, appliedMutants);73 const actualCode = normalizeWhitespaces(generate(ast).code);74 expect(actualCode).matches(/else\s*{.*const foo = a \+ b;\s*\}/);75 });76 it('should add mutant coverage syntax', () => {77 const { ast, appliedMutants, statement } = arrangeSingleMutant();78 statementMutantPlacer.place(statement, appliedMutants);79 const actualCode = normalizeWhitespaces(generate(ast).code);80 expect(actualCode).matches(/else\s*{\s*stryCov_9fa48\("1"\)/);81 });82 it('should be able to place multiple mutants', () => {83 // Arrange84 const ast = parseJS('const foo = a + b');85 const statement = findNodePath<types.VariableDeclaration>(ast, (p) => p.isVariableDeclaration());86 const binaryExpression = findNodePath<types.BinaryExpression>(ast, (p) => p.isBinaryExpression());87 const fooIdentifier = findNodePath<types.Identifier>(ast, (p) => p.isIdentifier());88 const mutants = [89 new Mutant('52', 'file.js', binaryExpression.node, {90 replacement: types.binaryExpression('>>>', types.identifier('bar'), types.identifier('baz')),91 mutatorName: 'fooMutator',92 }),93 new Mutant('659', 'file.js', fooIdentifier.node, {94 replacement: types.identifier('bar'),95 mutatorName: 'fooMutator',96 }),97 ];98 const appliedMutants = new Map<Mutant, types.Statement>();99 appliedMutants.set(mutants[0], mutants[0].applied(statement.node));100 appliedMutants.set(mutants[1], mutants[1].applied(statement.node));101 // Act102 statementMutantPlacer.place(statement, appliedMutants);103 const actualCode = normalizeWhitespaces(generate(ast).code);104 // Assert105 expect(actualCode).contains(106 normalizeWhitespaces(`if (stryMutAct_9fa48("659")) {107 const bar = a + b;108 } else if (stryMutAct_9fa48("52")) {109 const foo = bar >>> baz;110 } else {111 stryCov_9fa48("52", "659")`)112 );113 });114 });...
gprun2.js
Source:gprun2.js
1'use strict'2const logger = require('../logger/logger')(module)3const nconf = require('../config/conf.js').nconf4const fs = require('fs')5const toString = require('stream-to-string')6const readline = require('readline')7const request = require('request-promise-native')8nconf.defaults({9"datasourceurl":"http://localhost:8080",10"minDepth": 2,11"maxDepth": 6,12"functionSet":{13 "+":{14 "arity":215 },16 "-":{17 "arity":218 },19 "*":{20 "arity":221 },22 "/":{23 "arity":224 },25 "if<=":{26 "arity":427 }28 29 },30 "variables":["distancediff","weightdiff","goingdiff"],31 "dependantvariable":"speeddiff",32 "proportions":{33 "functions": 0.5,34 "constants": 0.25,35 "variables": 0.2536 },37 "constants": {38 "nconstants" : 1000,39 "min": -10.0,40 "max": 10.041 },42 "constantsSet":[],43 "populationsize": 100,44 "datafileurl":"../data/test-100.json",45 "maxSpeedIncrease":0.40340390203403914,46 "maxSpeedDecrease":-0.2880974917179366,47 "epochs": 100,48 'nelite': 5,49 "crossoverrate":0.9,50 "tournamentsize": 5,51 "pointmutationrate":0.05,52})53const GPnode = require('../GPNode/GPnode.js').GPnode54const gpa = require('./gpalgorithm')55const batchsize = nconf.get("batchsize")56const dependantvariable = nconf.get("dependantvariable")57const epochs = nconf.get("epochs")58const populationsize = nconf.get('populationsize')59const nelite = nconf.get('nelite')60const crossoverRate = nconf.get('crossoverrate')61const tournamentSize = nconf.get('tournamentsize')62nconf.set('constantsSet',gpa.generateConstants(nconf.get('constants').nconstants))63const getDataBatch = async(batchSize) => {64 let url = nconf.get("datasourceurl")+"/data"65 if (typeof batchSize != 'undefined'){66 url = nconf.get("datasourceurl")+"/data?n=" + batchSize67 }68 const promise = new Promise((resolve,reject) => {69 request(url)70 .then(data => {71 //console.log("obs: " + JSON.stringify(data))72 resolve(data)73 })74 })75 //const data = await getBatch(batchSize)76 let data = await promise77 // console.log(data)78 return JSON.parse(data)79}80const learnStep = (epoch) => {81 console.log("#Epoch: " + epoch)82 console.log(JSON.stringify(population[0].stats.fitness))83 console.log("#" + population[0].rule.toStrArr())84 //prepare the population for the next generation85 let newPopulation = new Array(populationsize)86 //copy elite members87 for(let i=0; i<nelite; i++){88 newPopulation[i]=population[i]89 }90 //replace poulation members91 for(let i = nelite; i<populationsize; i++){92 if(Math.random() < crossoverRate){ //crossover this member of the population93 let parent1 = gpa.getTournamentWinner(gpa.getTournament(population,tournamentSize))94 let parent2 = gpa.getTournamentWinner(gpa.getTournament(population,tournamentSize))95 let index1 = parent1.rule.selectIndex()96 let index2 = parent2.rule.selectIndex()97 let offspring = GPnode.crossover(parent1.rule, parent2.rule, index1, index2)98 let newPopulationMember = {99 rule:offspring,100 stats:{101 cumulativeError:0,102 nobservations:0,103 fitness:Number.MAX_VALUE104 }105 }106 newPopulation[i] = newPopulationMember107 }108 else{ //mutate109 let tournamentWinner = gpa.getTournamentWinner(gpa.getTournament(population,tournamentSize))110 let crossoverMutateIndex = tournamentWinner.rule.selectIndex()111 let cmDepth = nconf.get('minDepth') +Math.floor(Math.random() * (nconf.get('maxDepth')-nconf.get('minDepth')))112 let mutated = GPnode.subtreeMutate(tournamentWinner.rule, crossoverMutateIndex,cmDepth)113 let mutatedArray = mutated.toArray()114 for(let j=0;j<mutatedArray.length;j++){115 let nodeToMutate=mutatedArray[j]116 let rnd=Math.random()117 //console.log("rnd: "+ rnd)118 if(rnd > nconf.get('pointmutationrate')){119 //logger.info(i + 'point mutate it');120 GPnode.pointMutate(nodeToMutate) //mutates in situ121 }122 else{123 //logger.info(i + 'do not point mutate it');124 }125 }126 let newPopMember={127 rule:mutated,128 stats:{129 cumulativeError:0,130 nobservations:0,131 fitness:Number.MAX_VALUE132 }133 }134 newPopulation[i]=newPopMember;135 }136 }137 population = newPopulation138 getDataBatch(batchsize)139 .then(databatch => {140 population = gpa.evaluatePopulation(population, databatch, true, dependantvariable)141 population = gpa.sortPopulation(population)142 if(epoch < epochs){143 learnStep(epoch + 1)144 }145 else{ //print out final result146 console.log("#Epoch: " + epoch)147 console.log(JSON.stringify(population[0].stats.fitness))148 console.log("#" + population[0].rule.toStrArr())149 }150 })151 152}153let population = gpa.generatePopulation(nconf.get('populationsize'))154getDataBatch(batchsize)155.then(databatch => {156 population = gpa.evaluatePopulation(population, databatch, true, dependantvariable)157 population = gpa.sortPopulation(population)158 learnStep(0)...
db.js
Source:db.js
1import forEach from 'lodash/forEach';2import invariant from 'invariant';3import iterateField from '../helpers/iterate-field';4import mergeWith from 'lodash/mergeWith';5/* eslint-disable consistent-return */6function mergeCustomizer (objVal, srcVal) {7 if (objVal && objVal.constructor === Array) {8 return srcVal;9 }10}11/* eslint-enable consistent-return */12// The store is responsible for holding and managing data13export default class DB {14 constructor () {15 // Local database16 // composed of data nodes, e.g.17 // {18 // 56d0583eb0dc646f07b05cf2: {...},19 // 568fc7d152e76bc604a74520: {...}20 // }21 this.db = {};22 }23 mergeChanges (changes) {24 mergeWith(this.db, changes, mergeCustomizer);25 }26 removeNode (id) {27 this.db[id] && delete this.db[id];28 }29 // XXX UNDOCUMENTED && UNTESTED30 performUserMutate ({nodeId, type, field}, nodes) {31 invariant(nodeId, 'Relate: mutate does not have a nodeId defined');32 invariant(type, 'Relate: mutate does not have a type defined');33 invariant(field, 'Relate: mutate does not have a field defined');34 let result = [];35 const nodeToMutate = this.db[nodeId];36 if (nodeToMutate) {37 iterateField(field, nodeToMutate, (dataField, parent, lastField) => {38 // add nodes to data field39 const nodeToMutateNodes = dataField.get();40 const nodesArr = nodes.constructor === Array ? nodes : [nodes];41 parent[lastField] = [...nodeToMutateNodes, ...nodesArr];42 result = [nodeId];43 });44 }45 return result;46 }47 getData (data, fragment) {48 const result = {};49 forEach(fragment, (frag, propertyName) => {50 let dataValue = data[propertyName];51 if (dataValue === undefined) dataValue = null;52 if (typeof frag === 'object' && dataValue) {53 const isList = dataValue && dataValue.constructor === Array;54 const isId = typeof dataValue !== 'object' && this.db[dataValue];55 if (isList) {56 const list = [];57 forEach(dataValue, (piece) => {58 const isPieceId = typeof piece !== 'object' && this.db[piece];59 list.push(this.getData(isPieceId ? this.db[piece] : piece, frag));60 });61 result[propertyName] = list;62 } else if (isId) {63 result[propertyName] = this.getData(this.db[dataValue], frag);64 } else {65 result[propertyName] = this.getData(dataValue, frag);66 }67 } else {68 result[propertyName] = dataValue;69 }70 });71 return result;72 }73 getNode (id) {74 return this.db[id];75 }...
Using AI Code Generation
1const nodeToMutate = require('stryker-parent').nodeToMutate;2const myNode = nodeToMutate();3const nodeToMutate = require('stryker-child').nodeToMutate;4const myNode = nodeToMutate();5module.exports = function(config) {6 config.set({7 });8};9module.exports = function(config) {10 config.set({11 });12};13module.exports = function(config) {14 config.set({15 });16};
Using AI Code Generation
1const path = require('path');2const { NodeMutator } = require('stryker-parent');3class MyMutator extends NodeMutator {4 constructor(name) {5 super(name);6 }7 mutate(node) {8 if (node.type === 'Literal' && typeof node.value === 'string') {9 return [this.nodeToMutate(node)];10 }11 }12}13module.exports = MyMutator;14module.exports = function(config) {15 config.set({16 mutator: {17 path.resolve(__dirname, 'test.js')18 }19 });20};
Using AI Code Generation
1var stryker = require('stryker-parent');2var nodeToMutate = stryker.nodeToMutate;3var fs = require('fs');4var codeToMutate = fs.readFileSync('test.js', 'utf8');5var node = nodeToMutate(codeToMutate, 1, 2);6console.log(node);7var foo = function () {8 return 1;9};10var bar = function () {11 return 2;12};13module.exports = {14};15If I want to mutate the line return 1; , how do I get the AST node of that line? I tried the following code:16var stryker = require('stryker-parent');17var nodeToMutate = stryker.nodeToMutate;18var fs = require('fs');19var codeToMutate = fs.readFileSync('test.js', 'utf8');20var node = nodeToMutate(codeToMutate, 1, 2);21console.log(node);22Node {23 loc: Location { start: [Object], end: [Object] },24 body: [ Node { type: 'VariableDeclaration', start: 0, end: 2, loc: [Object], range: [Object], declarations: [Array], kind: 'var' } ],25 sourceType: 'script' }26I would expect to get the node of the line return 1; . How can I achieve this?27var stryker = require('stryker-parent');28var nodeToMutate = stryker.nodeToMutate;29var fs = require('fs');30var codeToMutate = fs.readFileSync('test.js', 'utf8');
Using AI Code Generation
1const strykerParent = require('stryker-parent');2const nodeToMutate = strykerParent.nodeToMutate;3const node = nodeToMutate();4const strykerParent = require('stryker-parent');5const nodeToMutate = strykerParent.nodeToMutate;6const node = nodeToMutate();7const strykerParent = require('stryker-parent');8const nodeToMutate = strykerParent.nodeToMutate;9const node = nodeToMutate();10const strykerParent = require('stryker-parent');11const nodeToMutate = strykerParent.nodeToMutate;12const node = nodeToMutate();13const strykerParent = require('stryker-parent');14const nodeToMutate = strykerParent.nodeToMutate;15const node = nodeToMutate();16const strykerParent = require('stryker-parent');17const nodeToMutate = strykerParent.nodeToMutate;18const node = nodeToMutate();19const strykerParent = require('stryker-parent');20const nodeToMutate = strykerParent.nodeToMutate;21const node = nodeToMutate();22const strykerParent = require('stryker-parent');23const nodeToMutate = strykerParent.nodeToMutate;24const node = nodeToMutate();
Using AI Code Generation
1var strykerParent = require('stryker-parent');2var nodeToMutate = strykerParent.nodeToMutate;3var node = nodeToMutate('test.js', 1, 1);4console.log(node.type);5var node = nodeToMutate('test.js', 1, 10);6console.log(node.type);7var node = nodeToMutate('test.js', 1, 10);8console.log(node.type);9var node = nodeToMutate('test.js', 2, 2);10console.log(node.type);11var node = nodeToMutate('test.js', 3, 1);12console.log(node.type);13var node = nodeToMutate('test.js', 3, 10);14console.log(node.type);15var node = nodeToMutate('test.js', 3, 20);16console.log(node.type);17var node = nodeToMutate('test.js', 4, 2);18console.log(node.type);19var node = nodeToMutate('test.js', 4, 11);20console.log(node.type);21var node = nodeToMutate('test.js', 4, 20);22console.log(node.type);23var node = nodeToMutate('test.js', 5, 1);24console.log(node.type);25var node = nodeToMutate('test.js', 5, 10);26console.log(node.type);27var node = nodeToMutate('test.js', 5, 19);28console.log(node.type);29var node = nodeToMutate('test.js', 5, 28);30console.log(node.type);31var node = nodeToMutate('test.js', 5, 37);32console.log(node.type);33var node = nodeToMutate('test.js', 6, 1);34console.log(node.type);35var node = nodeToMutate('test.js', 6, 10);36console.log(node.type);
Using AI Code Generation
1var nodeToMutate = require('stryker-parent').nodeToMutate;2var mutate = nodeToMutate('test.js');3mutate('a + b', function (mutated) {4 console.log(mutated);5});6var nodeToMutate = require('stryker-parent').nodeToMutate;7var mutate = nodeToMutate('test.js');8mutate('a + b', function (mutated) {9 console.log(mutated);10});11var nodeToMutate = require('stryker-parent').nodeToMutate;12var mutate = nodeToMutate('test.js');13mutate('a + b', function (mutated) {14 console.log(mutated);15});16var nodeToMutate = require('stryker-parent').nodeToMutate;17var mutate = nodeToMutate('test.js');18mutate('a + b', function (mutated) {19 console.log(mutated);20});21var nodeToMutate = require('stryker-parent').nodeToMutate;22var mutate = nodeToMutate('test.js');23mutate('a + b', function (mutated) {24 console.log(mutated);25});26var nodeToMutate = require('stryker-parent').nodeToMutate;27var mutate = nodeToMutate('test.js');28mutate('a + b', function (mutated) {29 console.log(mutated);30});
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!!