How to use loadPatch method in backstopjs

Best JavaScript code snippet using backstopjs

loadSlate.js

Source:loadSlate.js Github

copy

Full Screen

1// dependencies2const Repository = require('gitsheets/lib/Repository')3const convertRecord = require('./convertRecord')4const slateLoadMappings = require('./mappings/load')5const slateExtractMappings = require('./mappings/extract-slate')6// constants7const RELATED_INSERT_RE = /^\/(?<field>relationships|contact_points)\/(?<position>[0-9]+|-)$/8const RELATED_PATCH_RE = /^\/(?<field>relationships|contact_points)\/(?<position>[0-9]+|-)\/(?<subfield>[^/]+)$/9const PATCH_USER_KEY = Symbol('patch-user')10const PATCH_PATH_KEY = Symbol('patch-path')11const PATCH_SOURCE_KEY = Symbol('patch-source')12const COMMIT_ERRORS = []13// library14function logError (error) {15 console.error(error)16 COMMIT_ERRORS.push(error)17}18async function loadSlate ({ ref, host, hostName, token, emptyCommit, maxAge }) {19 const slateApi = require('./api')({ host, token })20 // load repository21 const repo = await Repository.getFromEnvironment({ ref })22 const git = await repo.getGit()23 const usersSheet = await repo.openSheet('users')24 // find most recent extract ancestor for this host25 const [ancestorHash, ancestorTimestamp] = (await git.log(ref, {26 pretty: 'format:%H %ct %(trailers:key=Extracted-from,valueonly)',27 grep: `^Extracted-from: ${hostName}$`,28 'max-count': 129 })).split(' ')30 if (!ancestorHash) {31 throw new Error(`could not find an ancestor on ${ref} with /^Extracted-from: ${hostName}$/, run extract against same host first`)32 }33 // check age of ancestor34 const ancestorDate = new Date(ancestorTimestamp * 1000)35 const ancestorAge = Math.round((new Date() - ancestorDate) / 1000)36 if (ancestorAge > maxAge) {37 throw new Error(`ancestor commit ${ancestorHash.substr(0, 8)} is ${ancestorAge}s old, max age is ${maxAge}s`)38 }39 console.log(`using ${ancestorAge}s old ancestor ${ancestorHash.substr(0, 8)}`)40 // build operation batches41 const dirtyPeople = []42 const dirtyContactPoints = []43 const dirtyRelationships = []44 const peoplePatchMap = new Map()45 const contactPointPatchMap = new Map()46 const relationshipPatchMap = new Map()47 const dirtyUsers = new Set()48 const slatePeopleTemporaryIdMap = new Map()49 console.log('analyzing delta...')50 for await (const change of usersSheet.diffFrom(ancestorHash, { patches: true })) {51 console.log(`${change.status} ${change.path}\t${change.srcHash} -> ${change.dstHash}`)52 for (const { op, path, value } of change.patch) {53 const relatedInsertMatch = RELATED_INSERT_RE.exec(path)54 const { field: relatedInsertField, position: relatedInsertPosition } = relatedInsertMatch ? relatedInsertMatch.groups : {}55 if (op === 'add' && path === '/relationships') {56 console.log(`\tinsert ${value.length} relationship(s)`)57 for (const valueItem of value) {58 valueItem[PATCH_USER_KEY] = change.dst59 valueItem[PATCH_PATH_KEY] = path60 dirtyRelationships.push(valueItem)61 }62 } else if (op === 'add' && relatedInsertField === 'relationships') {63 console.log(`\tinsert relationship at position ${relatedInsertPosition === '-' ? change.src[relatedInsertField].length : relatedInsertPosition}`)64 value[PATCH_USER_KEY] = change.dst65 value[PATCH_PATH_KEY] = path66 dirtyRelationships.push(value)67 } else if (op === 'add' && path === '/contact_points') {68 console.log(`\tinsert ${value.length} contact point(s)`)69 for (const valueItem of value) {70 valueItem[PATCH_USER_KEY] = change.dst71 valueItem[PATCH_PATH_KEY] = path72 dirtyContactPoints.push(valueItem)73 }74 } else if (op === 'add' && relatedInsertField === 'contact_points') {75 console.log(`\tinsert contact point at position ${relatedInsertPosition === '-' ? change.src[relatedInsertField].length : relatedInsertPosition}`)76 value[PATCH_USER_KEY] = change.dst77 value[PATCH_PATH_KEY] = path78 dirtyContactPoints.push(value)79 } else if ((op === 'add' || op === 'replace') && path.lastIndexOf('/') === 0) {80 console.log(`\t${op} user field ${path.substr(1)} = ${value}`)81 let personPatch = peoplePatchMap.get(change.dst.id)82 if (!personPatch) {83 personPatch = {84 [PATCH_USER_KEY]: change.dst,85 [PATCH_PATH_KEY]: path86 }87 peoplePatchMap.set(change.dst.id, personPatch)88 dirtyPeople.push(personPatch)89 }90 personPatch[path.substr(1)] = value91 } else if (op === 'replace' && path === '') {92 console.log('\tadd new user')93 value[PATCH_USER_KEY] = change.dst94 value[PATCH_PATH_KEY] = path95 dirtyPeople.push(value)96 } else {97 const relatedPatchMatch = RELATED_PATCH_RE.exec(path)98 const {99 field: relatedPatchField,100 position: relatedPatchPosition,101 subfield: relatedPatchSubfield102 } = relatedPatchMatch ? relatedPatchMatch.groups : {}103 if (op === 'add' && relatedPatchField === 'relationships') {104 console.log(`\t${op} relationship field ${relatedPatchSubfield} = ${value}`)105 const relationshipId = change.dst[relatedPatchField][relatedPatchPosition].id106 let relationshipPatch = relationshipPatchMap.get(relationshipId)107 if (!relationshipPatch) {108 relationshipPatch = {109 id: relationshipId,110 [PATCH_USER_KEY]: change.dst,111 [PATCH_PATH_KEY]: path112 }113 relationshipPatchMap.set(relationshipId, relationshipPatch)114 dirtyRelationships.push(relationshipPatch)115 }116 relationshipPatch[relatedPatchSubfield] = value117 } else if (op === 'replace' && relatedPatchField === 'contact_points') {118 console.log(`\t${op} contact point field ${relatedPatchSubfield} = ${value}`)119 const contactPointId = change.dst[relatedPatchField][relatedPatchPosition].id120 let contactPointPatch = contactPointPatchMap.get(contactPointId)121 if (!contactPointPatch) {122 contactPointPatch = {123 id: contactPointId,124 [PATCH_USER_KEY]: change.dst,125 [PATCH_PATH_KEY]: path126 }127 contactPointPatchMap.set(contactPointId, contactPointPatch)128 dirtyContactPoints.push(contactPointPatch)129 }130 contactPointPatch[relatedPatchSubfield] = value131 } else if (op === 'replace' && relatedPatchField === 'relationships') {132 console.log(`\t${op} relationship field ${relatedPatchSubfield} = ${value}`)133 const relationshipId = change.dst[relatedPatchField][relatedPatchPosition].id134 let relationshipPatch = relationshipPatchMap.get(relationshipId)135 if (!relationshipPatch) {136 relationshipPatch = {137 id: relationshipId,138 [PATCH_USER_KEY]: change.dst,139 [PATCH_PATH_KEY]: path140 }141 relationshipPatchMap.set(relationshipId, relationshipPatch)142 dirtyRelationships.push(relationshipPatch)143 }144 relationshipPatch[relatedPatchSubfield] = value145 } else {146 throw new Error(`\tunhandled patch ${op} ${path}`)147 }148 }149 }150 }151 // prepare users batch upload152 console.log(`preparing batch upload for ${dirtyPeople.length} users...`)153 const slatePeoplePatches = []154 for (const patch of dirtyPeople) {155 const user = patch[PATCH_USER_KEY]156 const loadPatch = convertRecord(patch, slateLoadMappings.person)157 if (Object.keys(loadPatch).length === 0) {158 continue159 }160 loadPatch[PATCH_SOURCE_KEY] = patch161 if (user.id) {162 loadPatch.ID = user.id163 }164 // copy any related records embedded in the patch to their own queues;165 // convertRecord trimmed them out of loadPatch166 if (patch.contact_points) {167 for (const contactPoint of patch.contact_points) {168 dirtyContactPoints.push(contactPoint)169 contactPoint[PATCH_USER_KEY] = user170 }171 }172 if (patch.relationships) {173 for (const relationship of patch.relationships) {174 dirtyRelationships.push(relationship)175 relationship[PATCH_USER_KEY] = user176 }177 }178 slatePeoplePatches.push(loadPatch)179 loadPatch[PATCH_USER_KEY] = user180 }181 // upload batch to Slate182 if (slatePeoplePatches.length > 0) {183 try {184 console.log(`uploading ${slatePeoplePatches.length} changes to people...`)185 const {186 data: slatePeopleResponses,187 failed: slatePeopleFailed,188 success: slatePeopleSuccess,189 message: slatePeopleMessage190 } = await slateApi.post('people/save', {191 json: { data: slatePeoplePatches }192 })193 if (slatePeopleFailed.length > 0) {194 const failedIds = new Set()195 for (const { record, validationErrors } of slatePeopleFailed) {196 logError(`failed to save person ${record.ID}:\n\t${Object.keys(validationErrors).map(field => `${field}: ${validationErrors[field]}`).join('\n\t')}`)197 failedIds.add(record.ID)198 }199 for (let i = 0; i < slatePeoplePatches.length;) {200 if (failedIds.has(slatePeoplePatches[i].ID)) {201 slatePeoplePatches.splice(i, 1)202 } else {203 i++204 }205 }206 }207 if (!slatePeopleSuccess) {208 throw new Error(`people post failed: ${slatePeopleMessage || '[no message returned]'}`)209 }210 if (slatePeopleResponses.length !== slatePeoplePatches.length) {211 throw new Error(`${slatePeopleResponses.length} response objects does not match ${slatePeoplePatches.length} input objects`)212 }213 // process responses214 console.log(`loading ${slatePeopleResponses.length} person change responses...`)215 for (let i = 0; i < slatePeoplePatches.length; i++) {216 const inputData = slatePeoplePatches[i]217 const outputData = slatePeopleResponses[i]218 const inputId = inputData.ID219 // save negative ID mapping to server-provided ID220 if (inputId <= 0) {221 slatePeopleTemporaryIdMap.set(inputId, outputData.ID)222 }223 const existingUser = inputData[PATCH_USER_KEY]224 const extractPatch = convertRecord(outputData, slateExtractMappings.person)225 Object.assign(existingUser, extractPatch)226 dirtyUsers.add(existingUser)227 }228 } catch (err) {229 logError('Failed to upload people:', err.response && err.response.body ? err.response.body : err.message)230 return231 }232 }233 // prepare contact points batch upload234 console.log(`preparing batch upload for ${dirtyContactPoints.length} contact points...`)235 const slateContactPointsPatches = []236 let nextTemporaryContactPointId = -1237 for (const patch of dirtyContactPoints) {238 const user = patch[PATCH_USER_KEY]239 const loadPatch = convertRecord(patch, slateLoadMappings.contactPoint)240 if (Object.keys(loadPatch).length === 0) {241 continue242 }243 loadPatch[PATCH_SOURCE_KEY] = patch244 if (!loadPatch.ID) {245 loadPatch.ID = nextTemporaryContactPointId--246 }247 if (user.id) {248 loadPatch.PersonID = user.id249 }250 slateContactPointsPatches.push(loadPatch)251 loadPatch[PATCH_USER_KEY] = user252 }253 // upload batch to Slate254 if (slateContactPointsPatches.length > 0) {255 try {256 console.log(`uploading ${slateContactPointsPatches.length} changes to contact points...`)257 const {258 data: slateContactPointsResponses,259 failed: slateContactPointsFailed,260 success: slateContactPointsSuccess,261 message: slateContactPointsMessage262 } = await slateApi.post('contact-points/save', {263 json: { data: slateContactPointsPatches }264 })265 if (slateContactPointsFailed.length > 0) {266 const failedIds = new Set()267 for (const { record, validationErrors } of slateContactPointsFailed) {268 logError(`failed to save contact point ${record.Class}#${record.ID} ("${record.Label}" <${record.Data}>) for person ${record.PersonID}:\n\t${Object.keys(validationErrors).map(field => `${field}: ${validationErrors[field]}`).join('\n\t')}`)269 failedIds.add(record.ID)270 }271 for (let i = 0; i < slateContactPointsPatches.length;) {272 if (failedIds.has(slateContactPointsPatches[i].ID)) {273 slateContactPointsPatches.splice(i, 1)274 } else {275 i++276 }277 }278 }279 if (!slateContactPointsSuccess) {280 throw new Error(`contact point post failed: ${slateContactPointsMessage || '[no message returned]'}`)281 }282 if (slateContactPointsResponses.length !== slateContactPointsPatches.length) {283 throw new Error(`${slateContactPointsResponses.length} response objects does not match ${slateContactPointsPatches.length} input objects`)284 }285 // process responses286 console.log(`loading ${slateContactPointsResponses.length} contact point change responses...`)287 for (let i = 0; i < slateContactPointsPatches.length; i++) {288 const inputData = slateContactPointsPatches[i]289 const outputData = slateContactPointsResponses[i]290 const user = inputData[PATCH_USER_KEY]291 const extractPatch = convertRecord(outputData, slateExtractMappings.contactPoint)292 Object.assign(inputData[PATCH_SOURCE_KEY], extractPatch)293 dirtyUsers.add(user)294 }295 } catch (err) {296 logError('Failed to upload contact points:', err.response && err.response.body ? err.response.body : err.message)297 return298 }299 }300 // prepare relationships batch upload301 console.log(`preparing batch upload for ${dirtyRelationships.length} relationships...`)302 const slateRelationshipPatches = []303 let nextTemporaryRelationshipId = -1304 for (const patch of dirtyRelationships) {305 const user = patch[PATCH_USER_KEY]306 const loadPatch = convertRecord(patch, slateLoadMappings.relationship)307 if (Object.keys(loadPatch).length === 0) {308 continue309 }310 loadPatch[PATCH_SOURCE_KEY] = patch311 if (!loadPatch.ID) {312 loadPatch.ID = nextTemporaryRelationshipId--313 }314 if (user.id) {315 loadPatch.PersonID = user.id316 }317 const { RelatedPersonID: originalRelatedPersonID } = loadPatch318 if (originalRelatedPersonID && originalRelatedPersonID < 0) {319 loadPatch.RelatedPersonID = slatePeopleTemporaryIdMap.get(originalRelatedPersonID)320 if (!loadPatch.RelatedPersonID) {321 throw new Error(`unable to map negative RelatedPersonID ${originalRelatedPersonID} to assigned user ID`)322 }323 }324 slateRelationshipPatches.push(loadPatch)325 loadPatch[PATCH_USER_KEY] = user326 }327 // upload batch to Slate328 if (slateRelationshipPatches.length > 0) {329 try {330 console.log(`uploading ${slateRelationshipPatches.length} changes to relationships...`)331 const {332 data: slateRelationshipsResponses,333 failed: slateRelationshipsFailed,334 success: slateRelationshipsSuccess,335 message: slateRelationshipsMessage336 } = await slateApi.post('relationships/save', {337 json: { data: slateRelationshipPatches }338 })339 if (slateRelationshipsFailed.length > 0) {340 const failedIds = new Set()341 for (const { record, validationErrors } of slateRelationshipsFailed) {342 logError(`failed to save relationship ${record.Class}#${record.ID} (${record.Slot}: "${record.Label}" <${record.RelatedPersonID}>) for person ${record.PersonID}:\n\t${Object.keys(validationErrors).map(field => `${field}: ${validationErrors[field]}`).join('\n\t')}`)343 failedIds.add(record.ID)344 }345 for (let i = 0; i < slateRelationshipPatches.length;) {346 if (failedIds.has(slateRelationshipPatches[i].ID)) {347 slateRelationshipPatches.splice(i, 1)348 } else {349 i++350 }351 }352 }353 if (!slateRelationshipsSuccess) {354 throw new Error(`relationships post failed: ${slateRelationshipsMessage || '[no message returned]'}`)355 }356 if (slateRelationshipsResponses.length !== slateRelationshipPatches.length) {357 throw new Error(`${slateRelationshipsResponses.length} response objects does not match ${slateRelationshipPatches.length} input objects`)358 }359 // process responses360 console.log(`loading ${slateRelationshipsResponses.length} relationship change responses...`)361 for (let i = 0; i < slateRelationshipPatches.length; i++) {362 const inputData = slateRelationshipPatches[i]363 const outputData = slateRelationshipsResponses[i]364 const user = inputData[PATCH_USER_KEY]365 const extractPatch = convertRecord(outputData, slateExtractMappings.relationship)366 Object.assign(inputData[PATCH_SOURCE_KEY], extractPatch)367 dirtyUsers.add(user)368 }369 } catch (err) {370 logError('Failed to upload relationships:', err.response && err.response.body ? err.response.body : err.message)371 return372 }373 }374 // TODO: upload sections375 // TODO: upload enrollments, mapping temporary user ids376 // save all updated users377 console.log(`saving ${dirtyUsers.size} dirty user records`)378 for (const dirtyUser of dirtyUsers) {379 const { blob, path } = await usersSheet.upsert(dirtyUser)380 console.log(`${blob.hash}\t${path}`)381 }382 // save result383 const workspace = await repo.getWorkspace()384 const ancestor = await repo.resolveRef(ref)385 const treeHash = await workspace.root.write()386 if (emptyCommit || treeHash !== await git.getTreeHash(ancestor)) {387 let commitMessage = `⥃ ${COMMIT_ERRORS.length > 0 ? 'partially ' : ''}load data to ${slateApi.defaults.options.prefixUrl}`388 if (COMMIT_ERRORS.length) {389 commitMessage += `\n\n## ${COMMIT_ERRORS.length} errors:\n\n- ${COMMIT_ERRORS.join('\n- ')}`390 }391 commitMessage += `\n\nLoaded-to: ${hostName}`392 const commitHash = await git.commitTree(treeHash, {393 p: ancestor,394 m: commitMessage395 })396 await git.updateRef(`refs/heads/${ref}`, commitHash)397 console.log(`committed new Slate tree to "${ref}": ${ancestor}->${commitHash}`)398 return commitHash399 } else {400 console.log('Slate tree unchanged')401 }402}403// exports...

Full Screen

Full Screen

patch-management-spec.js

Source:patch-management-spec.js Github

copy

Full Screen

...14 expect(modLevel(getState())).toEqual(0)15 dispatch(updateModLevel(0.5))16 expect(modLevel(getState())).toEqual(0.5)17 dispatch(savePatch(1))18 dispatch(loadPatch(2))19 expect(modLevel(getState())).toEqual(0)20 dispatch(updateModLevel(0.75))21 expect(modLevel(getState())).toEqual(0.75)22 dispatch(savePatch(2))23 dispatch(loadPatch(1))24 expect(modLevel(getState())).toEqual(0.5)25 dispatch(loadPatch(2))26 expect(modLevel(getState())).toEqual(0.75)27 })28 it('edits are dismissed if a patch is not saved before changing patches', async () => {29 const { dispatch, getState } = await createStore()30 expect(modLevel(getState())).toEqual(0)31 dispatch(updateModLevel(0.5))32 expect(modLevel(getState())).toEqual(0.5)33 // patch 1 not saved34 dispatch(loadPatch(2))35 dispatch(loadPatch(1))36 expect(modLevel(getState())).toEqual(0)37 })38 describe('A/B comparison', () => {39 const assertIsAWithB = (state) => {40 expect(currentPatchIsModified(state)).toEqual(false)41 expect(currentPatchHasModifiedVersion(state)).toEqual(true)42 }43 const assertIsAWithoutB = (state) => {44 expect(currentPatchIsModified(state)).toEqual(false)45 expect(currentPatchHasModifiedVersion(state)).toEqual(false)46 }47 const assertIsB = (state) => {48 expect(currentPatchIsModified(state)).toEqual(true)49 expect(currentPatchHasModifiedVersion(state)).toEqual(false)50 }51 describe('reverting to the unedited "A" version of a patch', () => {52 it('is not possible on loading patch', async () => {53 const { getState } = await createStore()54 assertIsAWithoutB(getState())55 })56 it('is possible after modifying a patch', async () => {57 const { dispatch, getState } = await createStore()58 dispatch(updateModLevel(0.5)) // B59 assertIsB(getState())60 })61 it('is not possible after modifying a patch then saving it', async () => {62 const { dispatch, getState } = await createStore()63 dispatch(updateModLevel(0.5)) // B64 dispatch(savePatch(1)) // A65 assertIsAWithoutB(getState())66 })67 it('is not possible after modifying a patch then loading a different one it', async () => {68 const { dispatch, getState } = await createStore()69 dispatch(updateModLevel(0.5)) // B70 // patch 1 not saved71 dispatch(loadPatch(2)) // A72 assertIsAWithoutB(getState())73 })74 })75 describe('(re-)applying the edited "B" version of a patch', () => {76 it('is not possible on loading patch', async () => {77 const { getState } = await createStore() // A (no B)78 assertIsAWithoutB(getState())79 })80 it('is not possible on modifying a patch', async () => {81 const { dispatch, getState } = await createStore() // A82 dispatch(updateModLevel(0.5)) // B83 assertIsB(getState())84 })85 it('is possible on modifying a patch then reverting to the "A" version', async () => {86 const { dispatch, getState } = await createStore()87 dispatch(updateModLevel(0.5)) // B88 dispatch(togglePatchAB()) // A (has B)89 assertIsAWithB(getState())90 })91 it('is not possible on modifying a patch then reverting to the "A" version, then re-applying the "B" version', async () => {92 const { dispatch, getState } = await createStore()93 dispatch(updateModLevel(0.5)) // B94 dispatch(togglePatchAB()) // A95 dispatch(togglePatchAB()) // B96 assertIsB(getState())97 })98 it('is not possible on modifying a patch then reverting to the "A" version, then loading another patch', async () => {99 const { dispatch, getState } = await createStore()100 dispatch(updateModLevel(0.5)) // B101 dispatch(togglePatchAB()) // A (has B)102 dispatch(loadPatch(2)) // A (no B)103 assertIsAWithoutB(getState())104 })105 it('is not possible on modifying a patch then reverting to the "A" version, then modifying again', async () => {106 const { dispatch, getState } = await createStore()107 dispatch(updateModLevel(0.5)) // B108 dispatch(togglePatchAB()) // A109 dispatch(updateModLevel(0.75)) // B110 assertIsB(getState())111 })112 it('is not possible on modifying a patch then reverting to the "A" version, then saving the patch', async () => {113 const { dispatch, getState } = await createStore()114 dispatch(updateModLevel(0.5)) // B115 dispatch(togglePatchAB()) // A (with B)116 dispatch(savePatch(1)) // A (no B)...

Full Screen

Full Screen

app.js

Source:app.js Github

copy

Full Screen

...54function freePatch() {55 baliset_state.freePatch();56 return osc_client.freePatch();57}58function loadPatch(msg) {59 const path = "patches/" + msg.name;60 const patch = JSON.parse(fs.readFileSync(path));61 osc_client.loadPatch(patch);62 baliset_state.loadPatch(patch);63 console.log(`loaded patch: ${msg.name}`);64}65function listPatches() {66 const path = "patches/";67 return fs.readdirSync(path);68}69function messageHandler(ws) {70 const handler = function(msg) {71 msg = JSON.parse(msg);72 // console.log(`got message: ${msg}`);73 if(msg.route === undefined) {74 console.log(`expected message to be a json array containing a route parameter, got ${msg}`);75 return;76 }77 switch(msg.route) {78 case "/node/add": {79 const clientMsg = osc_client.addNode(msg);80 wss.broadcast(clientMsg);81 break;82 }83 case "/node/connect": {84 const clientMsg = osc_client.connectNode(msg);85 wss.broadcast(clientMsg);86 break;87 }88 case "/node/control": {89 const clientMsg = osc_client.controlNode(msg);90 wss.notifyOtherClients(ws, clientMsg);91 break;92 }93 case "/node/disconnect": {94 const clientMsg = osc_client.disconnectNode(msg);95 wss.broadcast(clientMsg);96 break;97 }98 case "/node/delete": {99 const clientMsg = osc_client.deleteNode(msg);100 wss.broadcast(clientMsg);101 break;102 }103 case "/node/move": {104 const clientMsg = baliset_state.moveNode(msg);105 wss.notifyOtherClients(ws, clientMsg);106 break;107 }108 case "/patch/save": {109 const patchSavedMsg = savePatch(msg);110 wss.broadcast(patchSavedMsg);111 break;112 }113 case "/patch/load": {114 loadPatch(msg);115 wss.broadcast({"route": "/app_state",116 "nodes": baliset_state.getNodes(),117 "connections": baliset_state.getConnections(),118 "patches": listPatches()});119 break;120 }121 default:122 console.log(`unrecognized websocket msg: ${msg.route}`);123 }124 };125 return handler;126}127wss.on("connection", function connection(ws) {128 console.log("got a connection.");129 //console.log(`clients: ${wss.clients}`);130 //wss.clients.forEach(function(client){console.log(`client: ${client}`)})131 ws.on("message", messageHandler(ws));132 ws.on("close", function close(){133 console.log("disconnected.");134 });135 ws.send(JSON.stringify({"route": "/app_state",136 "nodes": baliset_state.getNodes(),137 "connections": baliset_state.getConnections(),138 "patches": listPatches()}));139});140//load init patch if provided as a cli arg141if (init_patch) {142 console.log(`Loading init patch: ${init_patch}`);143 loadPatch({"name": init_patch});144}145//trap SIGINT and free the patch before exiting146process.on('SIGINT', function() {147 console.log("Freeing patch and terminating.");148 wss.close(() => {149 freePatch()150 .then(data => {process.exit()})151 .catch(err => {console.error(`Error freeing patch: ${err}`);152 process.exit(1);})153 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 {3 },4 {5 },6 {7 },8 {9 }10 {11 }12 "paths": {13 },14}15module.exports = function (casper, scenario) {16};17module.exports = function (casper, scenario) {18};

Full Screen

Using AI Code Generation

copy

Full Screen

1var backstop = require('backstopjs');2var backstopConfig = require('./backstop.json');3backstop('test', { config: backstopConfig });4{5 {6 },7 {8 },9 {10 },11 {12 }13 {14 }15 "paths": {16 },17}

Full Screen

Using AI Code Generation

copy

Full Screen

1var backstop = require('backstopjs');2var config = require('./backstop.json');3backstop('test', {config: config})4 .then(function(){5 console.log('done');6 })7 .catch(function(error){8 console.log(error);9 });10{11 {12 },13 {14 },15 {16 },17 {18 },19 {20 }21 {22 }23 "paths": {24 },25 "engineOptions": {26 },

Full Screen

Using AI Code Generation

copy

Full Screen

1var loadPatch = require('backstopjs/core/util/loadPatches');2loadPatch('chromy/allowLocalFilesAccess');3module.exports = {4 {5 },6 {7 },8 {9 },10 {11 },12 {13 }14 {15 }16 "paths": {17 },18}19var loadPatch = require('backstopjs/core/util/loadPatches');20loadPatch('chromy/allowLocalFilesAccess');21module.exports = {22 {

Full Screen

Using AI Code Generation

copy

Full Screen

1const backstop = require('backstopjs');2backstop('test', {3});4{5 {6 }7 {8 },9 {10 },11 {12 },13 {14 }15 "paths": {16 },17 "engineOptions": {18 },19}

Full Screen

Using AI Code Generation

copy

Full Screen

1 {2 },3 {4 }5module.exports = {6 {7 },8 {9 },10 {11 }12 {13 }14 paths: {15 },16 engineOptions: {17 },18}

Full Screen

Using AI Code Generation

copy

Full Screen

1var backstopjs = require('backstopjs');2var config = require('./backstop.json');3backstopjs('reference', {config: config})4.then(function () {5 console.log('Reference created');6 backstopjs('test', {config: config})7 .then(function () {8 console.log('Test completed');9 })10 .catch(function (error) {11 console.error(error);12 });13})14.catch(function (error) {15 console.error(error);16});17{18 {19 },20 {21 },22 {23 }24 {25 }26 "paths": {27 },28 "engineOptions": {29 },30}

Full Screen

Using AI Code Generation

copy

Full Screen

1var backstop = require('backstopjs');2var config = {3 {4 },5 {6 },7 {8 }9 {10 }11 "paths": {12 },13 "engineOptions": {14 },15};16backstop('loadPatches', {config: config})17 .then(function (compareConfig) {18 backstop('test', {config: compareConfig})19 .then(function () {

Full Screen

Using AI Code Generation

copy

Full Screen

1var loadPatch = require('backstopjs/core/command/loadPatches');2loadPatch('backstopjs/core/util/compareScreenshot.js', function (compareScreenshot) {3 compareScreenshot.default = function (config, reference, test, options) {4 return new Promise(function (resolve, reject) {5 var image1 = reference.get();6 var image2 = test.get();7 var width = image1.getWidth();8 var height = image1.getHeight();9 var misMatchThreshold = config.misMatchThreshold;10 var misMatchTolerance = config.misMatchTolerance;11 var misMatchPercentage = 0;12 var misMatchCount = 0;13 var diff = new PNG({ width: width, height: height });14 var diffImage = PNG.sync.write(diff);15 var diffImageBuffer = new Buffer(diffImage);16 var output = {17 getImageDataUrl: function () {18 return diff.pack().pipe(new stream.PassThrough());19 }20 };21 if (image1.getWidth() !== image2.getWidth() || image1.getHeight() !== image2.getHeight()) {22 output.isSameDimensions = false;23 resolve(output);24 }25 else {26 var diffPixelCount = 0;27 var diffPixelCountThreshold = misMatchThreshold * width * height / 100;28 for (var y = 0; y < height; y++) {29 for (var x = 0; x < width; x++) {30 var idx = (width * y + x) << 2;31 var r1 = image1.getPixel(x, y)[0];32 var g1 = image1.getPixel(x, y)[1];33 var b1 = image1.getPixel(x, y)[2];34 var a1 = image1.getPixel(x, y)[3];35 var r2 = image2.getPixel(x, y)[0];36 var g2 = image2.getPixel(x, y)[1];37 var b2 = image2.getPixel(x, y)[2];38 var a2 = image2.getPixel(x, y)[3];39 var diffRed = Math.abs(r1 - r2);40 var diffGreen = Math.abs(g1 - g2);

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 backstopjs automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful