How to use d.findByImage method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

finder-specs.js

Source:finder-specs.js Github

copy

Full Screen

1import _ from 'lodash';2import { imageUtil } from '@appium/support';3import BaseDriver from '@appium/base-driver';4import ImageElementPlugin, { IMAGE_STRATEGY } from '../../index';5import ImageElementFinder from '../../lib/finder';6import ImageElement from '../../lib/image-element';7import sinon from 'sinon';8import { TINY_PNG, TINY_PNG_DIMS } from '../fixtures';9import chai from 'chai';10import chaiAsPromised from 'chai-as-promised';11const compareModule = require('../../lib/compare');12chai.use(chaiAsPromised);13const should = chai.should();14const plugin = new ImageElementPlugin();15class PluginDriver extends BaseDriver {16 async getWindowSize () {}17 async getScreenshot () {}18 findElement (strategy, selector) {19 return plugin.findElement(_.noop, this, strategy, selector);20 }21 findElements (strategy, selector) {22 return plugin.findElements(_.noop, this, strategy, selector);23 }24}25describe('finding elements by image', function () {26 describe('findElement', function () {27 it('should use a different special method to find element by image', async function () {28 const d = new PluginDriver();29 sinon.stub(plugin.finder, 'findByImage').returns(true);30 sinon.stub(d, 'findElOrElsWithProcessing').returns(false);31 await d.findElement(IMAGE_STRATEGY, 'foo').should.eventually.be.true;32 await d.findElements(IMAGE_STRATEGY, 'foo').should.eventually.be.true;33 });34 it('should not be able to find image element from any other element', async function () {35 const d = new PluginDriver();36 await d.findElementFromElement(IMAGE_STRATEGY, 'foo', 'elId')37 .should.eventually.be.rejectedWith(/Locator Strategy.+is not supported/);38 await d.findElementsFromElement(IMAGE_STRATEGY, 'foo', 'elId')39 .should.eventually.be.rejectedWith(/Locator Strategy.+is not supported/);40 });41 });42 describe('findByImage', function () {43 const rect = {x: 10, y: 20, width: 30, height: 40};44 const score = 0.9;45 const size = {width: 100, height: 200};46 const screenshot = 'iVBORfoo';47 const template = 'iVBORbar';48 let compareStub;49 let d = new PluginDriver();50 let f = new ImageElementFinder(d);51 function basicStub (driver, finder) {52 const sizeStub = sinon.stub(driver, 'getWindowSize').returns(size);53 const screenStub = sinon.stub(finder, 'getScreenshotForImageFind').returns(screenshot);54 return {sizeStub, screenStub};55 }56 function basicImgElVerify (imgElProto, finder) {57 const imgElId = imgElProto.ELEMENT;58 finder.imgElCache.has(imgElId).should.be.true;59 const imgEl = finder.imgElCache.get(imgElId);60 (imgEl instanceof ImageElement).should.be.true;61 imgEl.rect.should.eql(rect);62 imgEl.score.should.eql(score);63 return imgEl;64 }65 beforeEach(function () {66 compareStub = sinon.stub(compareModule, 'compareImages').returns({rect, score});67 d = new PluginDriver();68 f = new ImageElementFinder(d);69 basicStub(d, f);70 });71 afterEach(function () {72 compareStub.restore();73 });74 it('should find an image element happypath', async function () {75 const imgElProto = await f.findByImage(template, {multiple: false});76 basicImgElVerify(imgElProto, f);77 });78 it('should find image elements happypath', async function () {79 compareStub.restore();80 compareStub = sinon.stub(compareModule, 'compareImages').returns([{rect, score}]);81 const els = await f.findByImage(template, {multiple: true});82 els.should.have.length(1);83 basicImgElVerify(els[0], f);84 });85 it('should fail if driver does not support getWindowSize', async function () {86 d.getWindowSize = null;87 await f.findByImage(template, {multiple: false})88 .should.eventually.be.rejectedWith(/driver does not support/);89 });90 it('should fix template size if requested', async function () {91 const newTemplate = 'iVBORbaz';92 await d.settings.update({fixImageTemplateSize: true});93 sinon.stub(f, 'ensureTemplateSize').returns(newTemplate);94 const imgElProto = await f.findByImage(template, {multiple: false});95 const imgEl = basicImgElVerify(imgElProto, f);96 imgEl.template.should.eql(newTemplate);97 _.last(compareStub.args)[2].should.eql(newTemplate);98 });99 it('should fix template size scale if requested', async function () {100 const newTemplate = 'iVBORbaz';101 await d.settings.update({fixImageTemplateScale: true});102 sinon.stub(f, 'fixImageTemplateScale').returns(newTemplate);103 const imgElProto = await f.findByImage(template, {multiple: false});104 const imgEl = basicImgElVerify(imgElProto, f);105 imgEl.template.should.eql(newTemplate);106 _.last(compareStub.args)[2].should.eql(newTemplate);107 });108 it('should not fix template size scale if it is not requested', async function () {109 const newTemplate = 'iVBORbaz';110 await d.settings.update({});111 sinon.stub(f, 'fixImageTemplateScale').returns(newTemplate);112 f.fixImageTemplateScale.callCount.should.eql(0);113 });114 it('should throw an error if template match fails', async function () {115 compareStub.throws(new Error('Cannot find any occurrences'));116 await f.findByImage(template, {multiple: false})117 .should.eventually.be.rejectedWith(/element could not be located/);118 });119 it('should return empty array for multiple elements if template match fails', async function () {120 compareStub.throws(new Error('Cannot find any occurrences'));121 await f.findByImage(template, {multiple: true}).should.eventually.eql([]);122 });123 it('should respect implicit wait', async function () {124 d.setImplicitWait(10);125 compareStub.resetHistory();126 compareStub.onCall(0).throws(new Error('Cannot find any occurrences'));127 compareStub.returns({rect, score});128 const imgElProto = await f.findByImage(template, {multiple: false});129 basicImgElVerify(imgElProto, f);130 compareStub.callCount.should.eql(2);131 });132 it('should not add element to cache and return it directly when checking staleness', async function () {133 const imgEl = await f.findByImage(template, {multiple: false, shouldCheckStaleness: true});134 (imgEl instanceof ImageElement).should.be.true;135 f.imgElCache.has(imgEl.id).should.be.false;136 imgEl.rect.should.eql(rect);137 });138 });139 describe('fixImageTemplateScale', function () {140 const d = new PluginDriver();141 const f = new ImageElementFinder(d);142 const basicTemplate = 'iVBORbaz';143 it('should not fix template size scale if no scale value', async function () {144 await f.fixImageTemplateScale(basicTemplate, {fixImageTemplateScale: true})145 .should.eventually.eql(basicTemplate);146 });147 it('should not fix template size scale if it is null', async function () {148 await f.fixImageTemplateScale(basicTemplate, null)149 .should.eventually.eql(basicTemplate);150 });151 it('should not fix template size scale if it is not number', async function () {152 await f.fixImageTemplateScale(basicTemplate, 'wrong-scale')153 .should.eventually.eql(basicTemplate);154 });155 it('should fix template size scale', async function () {156 const actual = 'iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAYAAADgzO9IAAAAWElEQVR4AU3BQRWAQAhAwa/PGBsEgrC16AFBKEIPXW7OXO+Rmey9iQjMjHFzrLUwM7qbqmLcHKpKRFBVuDvj4agq3B1VRUQYT2bS3QwRQVUZF/CaGRHB3wc1vSZbHO5+BgAAAABJRU5ErkJggg==';157 await f.fixImageTemplateScale(TINY_PNG, {158 fixImageTemplateScale: true, xScale: 1.5, yScale: 1.5159 }).should.eventually.eql(actual);160 });161 it('should not fix template size scale because of fixImageTemplateScale being false', async function () {162 await f.fixImageTemplateScale(TINY_PNG, {163 fixImageTemplateScale: false, xScale: 1.5, yScale: 1.5164 }).should.eventually.eql(TINY_PNG);165 });166 it('should fix template size scale with default scale', async function () {167 const actual = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABwUlEQVR4AaXBPUsrQQCG0SeX+cBdkTjwTpG1NPgLpjY/fW1stt4UYmm2cJqwMCsaw70uJJ3CBc9Z/P3Cl+12S9u2tG1L27bEGLm/v2ez2bDZbJDEd/7wS4YT7z3X19fc3Nxwd3dHXdd47xnHkefnZ8ZxpKoq6rqmqiqMMcwMJ1VV0TQN0zThnOPj44O6rsk503UdkmiahqZpWK1WGGOYGU7quqZpGqy1SCLnTM6Z19dXcs5IYpomrLVI4uLigpnhpKoqVqsVkjgcDjw9PdF1HTlnuq5DEs45JHE4HDgznByPR97e3pimiVIK4zhyPB7x3hNCIITA5eUl3nsWiwVnhpNSCsMwsNvtGIaB/X5PKQVJpJSQxHq9RhLOOc4MJ9M0sdvt2G639H3PTBIxRiQhCUnEGLHWcmY4KaUwDAN93/P4+MhyuSSlhCRSSkjCOYe1FmstZ6bve2YvLy/s93tmy+USSUhCEpIIIfAd8/DwwOz9/Z1SCpJIKSGJ9XqNJJxz/MS0bcvs6uoKScQYkYQkJBFjxFrLT0zbtsxub29JKSGJlBKScM5hrcVay09MzplZjJHPz0+894QQCCHwP/7wS/8A4e6nAg+R8LwAAAAASUVORK5CYII=';168 await f.fixImageTemplateScale(TINY_PNG, {169 defaultImageTemplateScale: 4.0170 }).should.eventually.eql(actual);171 });172 it('should fix template size scale with default scale and image scale', async function () {173 const actual = 'iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAACaUlEQVR4AbXBMWvrWBSF0c9BsFPtW91UR1U6+///FKlKKt8qqnyqnMozggkI8xgMj6x1uv+L/6zryrIsrOvKsiys68qyLFwuF87nM5fLhfP5zOVy4Xw+84wXftkLv2ziQBK26b0TEVQVu4jANrvM5Hq9spOEJCQhCUlI4mjiQBK26b1TVewkYRvb7DKTMQaZiW1s01rDNraRxNHEgSRaa1QVO0m01jjKTDKTXe+d3jtVxU4SjyYOJGGbnSRs03snM8lMMpPb7UZmkplEBFXFThK2eTRxIAnbSMI2VcX39zdjDMYYZCaZyRiDMQZVxU4StqkqHk0cSEISf5KZ7DKTMQbLsrCTRGuN3jtVxaOJg6qiqqgqqoqqoqoYY5CZ7GwTEdzvd97f34kIeu/YRhKPJg6qiswkM7ndbmQmmUlmkpnsbBMR2CYimOeZ3ju2kcSjiYOqIjP5+vpi2za2bWPbNo5aa7TW2PXe6b3Te6e1hiQeTRxUFbfbjW3bGGNwvV4ZY2Ab27TWsI1tbGMb27TWsI0kHk0cVBWZybZtXK9XPj8/+fj4YJ5nIoLWGraJCOZ5RhKSkIQkJPFo4qCqyEy2bWOMwefnJ+u6cjqdsM3ONvM8cz6feca0ris/rtcrmcnONhHB/X7n/f2diKD3jm0k8axpWRZ+ZCaZyc42EYFtIoJ5num9YxtJPGta15U/sY1tdm9vb/Te6b1jG0k8a1qWhR+2sU1rjdYatrGNbWxjm9YaknjWtK4rPyKCiKC1hm0igojg9fUVSUhCEpJ41rQsC0e22dkmIrhcLvyNF/7H6XTib73wy174Zf8AJEsePtlPj10AAAAASUVORK5CYII=';174 await f.fixImageTemplateScale(TINY_PNG, {175 defaultImageTemplateScale: 4.0,176 fixImageTemplateScale: true,177 xScale: 1.5, yScale: 1.5178 }).should.eventually.eql(actual);179 });180 it('should not fix template size scale with default scale and image scale', async function () {181 const actual = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABwUlEQVR4AaXBPUsrQQCG0SeX+cBdkTjwTpG1NPgLpjY/fW1stt4UYmm2cJqwMCsaw70uJJ3CBc9Z/P3Cl+12S9u2tG1L27bEGLm/v2ez2bDZbJDEd/7wS4YT7z3X19fc3Nxwd3dHXdd47xnHkefnZ8ZxpKoq6rqmqiqMMcwMJ1VV0TQN0zThnOPj44O6rsk503UdkmiahqZpWK1WGGOYGU7quqZpGqy1SCLnTM6Z19dXcs5IYpomrLVI4uLigpnhpKoqVqsVkjgcDjw9PdF1HTlnuq5DEs45JHE4HDgznByPR97e3pimiVIK4zhyPB7x3hNCIITA5eUl3nsWiwVnhpNSCsMwsNvtGIaB/X5PKQVJpJSQxHq9RhLOOc4MJ9M0sdvt2G639H3PTBIxRiQhCUnEGLHWcmY4KaUwDAN93/P4+MhyuSSlhCRSSkjCOYe1FmstZ6bve2YvLy/s93tmy+USSUhCEpIIIfAd8/DwwOz9/Z1SCpJIKSGJ9XqNJJxz/MS0bcvs6uoKScQYkYQkJBFjxFrLT0zbtsxub29JKSGJlBKScM5hrcVay09MzplZjJHPz0+894QQCCHwP/7wS/8A4e6nAg+R8LwAAAAASUVORK5CYII=';182 await f.fixImageTemplateScale(TINY_PNG, {183 defaultImageTemplateScale: 4.0,184 fixImageTemplateScale: false,185 xScale: 1.5, yScale: 1.5186 }).should.eventually.eql(actual);187 });188 it('should not fix template size scale because of ignoreDefaultImageTemplateScale', async function () {189 await f.fixImageTemplateScale(TINY_PNG, {190 defaultImageTemplateScale: 4.0,191 ignoreDefaultImageTemplateScale: true,192 }).should.eventually.eql(TINY_PNG);193 });194 it('should ignore defaultImageTemplateScale to fix template size scale because of ignoreDefaultImageTemplateScale', async function () {195 const actual = 'iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAYAAADgzO9IAAAAWElEQVR4AU3BQRWAQAhAwa/PGBsEgrC16AFBKEIPXW7OXO+Rmey9iQjMjHFzrLUwM7qbqmLcHKpKRFBVuDvj4agq3B1VRUQYT2bS3QwRQVUZF/CaGRHB3wc1vSZbHO5+BgAAAABJRU5ErkJggg==';196 await f.fixImageTemplateScale(TINY_PNG, {197 defaultImageTemplateScale: 4.0,198 ignoreDefaultImageTemplateScale: true,199 fixImageTemplateScale: true,200 xScale: 1.5, yScale: 1.5201 }).should.eventually.eql(actual);202 });203 });204 describe('ensureTemplateSize', function () {205 const d = new PluginDriver();206 const f = new ImageElementFinder(d);207 it('should not resize the template if it is smaller than the screen', async function () {208 const screen = TINY_PNG_DIMS.map((n) => n * 2);209 await f.ensureTemplateSize(TINY_PNG, ...screen)210 .should.eventually.eql(TINY_PNG);211 });212 it('should not resize the template if it is the same size as the screen', async function () {213 await f.ensureTemplateSize(TINY_PNG, ...TINY_PNG_DIMS)214 .should.eventually.eql(TINY_PNG);215 });216 it('should resize the template if it is bigger than the screen', async function () {217 const screen = TINY_PNG_DIMS.map((n) => n / 2);218 const newTemplate = await f.ensureTemplateSize(TINY_PNG, ...screen);219 newTemplate.should.not.eql(TINY_PNG);220 newTemplate.length.should.be.below(TINY_PNG.length);221 });222 });223 describe('getScreenshotForImageFind', function () {224 let d;225 let f;226 beforeEach(function () {227 d = new PluginDriver();228 f = new ImageElementFinder(d);229 sinon.stub(d, 'getScreenshot').returns(TINY_PNG);230 });231 it('should fail if driver does not support getScreenshot', async function () {232 const d = new BaseDriver();233 const f = new ImageElementFinder(d);234 await f.getScreenshotForImageFind()235 .should.eventually.be.rejectedWith(/driver does not support/);236 });237 it('should not adjust or verify screenshot if asked not to by settings', async function () {238 await d.settings.update({fixImageFindScreenshotDims: false});239 const screen = TINY_PNG_DIMS.map((n) => n + 1);240 const {b64Screenshot, scale} = await f.getScreenshotForImageFind(...screen);241 b64Screenshot.should.eql(TINY_PNG);242 should.equal(scale, undefined);243 });244 it('should return screenshot without adjustment if it matches screen size', async function () {245 const {b64Screenshot, scale} = await f.getScreenshotForImageFind(...TINY_PNG_DIMS);246 b64Screenshot.should.eql(TINY_PNG);247 should.equal(scale, undefined);248 });249 it('should return scaled screenshot with same aspect ratio if matching screen aspect ratio', async function () {250 const screen = TINY_PNG_DIMS.map((n) => n * 1.5);251 const {b64Screenshot, scale} = await f.getScreenshotForImageFind(...screen);252 b64Screenshot.should.not.eql(TINY_PNG);253 const screenshotObj = await imageUtil.getJimpImage(b64Screenshot);254 screenshotObj.bitmap.width.should.eql(screen[0]);255 screenshotObj.bitmap.height.should.eql(screen[1]);256 scale.should.eql({ xScale: 1.5, yScale: 1.5 });257 });258 it('should return scaled screenshot with different aspect ratio if not matching screen aspect ratio', async function () {259 // try first with portrait screen, screen = 8 x 12260 let screen = [TINY_PNG_DIMS[0] * 2, TINY_PNG_DIMS[1] * 3];261 let expectedScale = { xScale: 2.67, yScale: 4 };262 const {b64Screenshot, scale} = await f.getScreenshotForImageFind(...screen);263 b64Screenshot.should.not.eql(TINY_PNG);264 let screenshotObj = await imageUtil.getJimpImage(b64Screenshot);265 screenshotObj.bitmap.width.should.eql(screen[0]);266 screenshotObj.bitmap.height.should.eql(screen[1]);267 scale.xScale.toFixed(2).should.eql(expectedScale.xScale.toString());268 scale.yScale.should.eql(expectedScale.yScale);269 // then with landscape screen, screen = 12 x 8270 screen = [TINY_PNG_DIMS[0] * 3, TINY_PNG_DIMS[1] * 2];271 expectedScale = { xScale: 4, yScale: 2.67 };272 const {b64Screenshot: newScreen, scale: newScale} = await f.getScreenshotForImageFind(...screen);273 newScreen.should.not.eql(TINY_PNG);274 screenshotObj = await imageUtil.getJimpImage(newScreen);275 screenshotObj.bitmap.width.should.eql(screen[0]);276 screenshotObj.bitmap.height.should.eql(screen[1]);277 newScale.xScale.should.eql(expectedScale.xScale);278 newScale.yScale.toFixed(2).should.eql(expectedScale.yScale.toString());279 });280 it('should return scaled screenshot with different aspect ratio if not matching screen aspect ratio with fixImageTemplateScale', async function () {281 // try first with portrait screen, screen = 8 x 12282 let screen = [TINY_PNG_DIMS[0] * 2, TINY_PNG_DIMS[1] * 3];283 let expectedScale = { xScale: 2.67, yScale: 4 };284 const {b64Screenshot, scale} = await f.getScreenshotForImageFind(...screen);285 b64Screenshot.should.not.eql(TINY_PNG);286 let screenshotObj = await imageUtil.getJimpImage(b64Screenshot);287 screenshotObj.bitmap.width.should.eql(screen[0]);288 screenshotObj.bitmap.height.should.eql(screen[1]);289 scale.xScale.toFixed(2).should.eql(expectedScale.xScale.toString());290 scale.yScale.should.eql(expectedScale.yScale);291 // 8 x 12 stretched TINY_PNG292 await f.fixImageTemplateScale(b64Screenshot, {fixImageTemplateScale: true, scale})293 .should.eventually.eql('iVBORw0KGgoAAAANSUhEUgAAAAgAAAAMCAYAAABfnvydAAAAJ0lEQVR4AYXBAQEAIACDMKR/p0fTBrKdbZcPCRIkSJAgQYIECRIkPAzBA1TpeNwZAAAAAElFTkSuQmCC');294 // then with landscape screen, screen = 12 x 8295 screen = [TINY_PNG_DIMS[0] * 3, TINY_PNG_DIMS[1] * 2];296 expectedScale = { xScale: 4, yScale: 2.67 };297 const {b64Screenshot: newScreen, scale: newScale} = await f.getScreenshotForImageFind(...screen);298 newScreen.should.not.eql(TINY_PNG);299 screenshotObj = await imageUtil.getJimpImage(newScreen);300 screenshotObj.bitmap.width.should.eql(screen[0]);301 screenshotObj.bitmap.height.should.eql(screen[1]);302 newScale.xScale.should.eql(expectedScale.xScale);303 newScale.yScale.toFixed(2).should.eql(expectedScale.yScale.toString());304 // 12 x 8 stretched TINY_PNG305 await f.fixImageTemplateScale(newScreen, {fixImageTemplateScale: true, scale})306 .should.eventually.eql('iVBORw0KGgoAAAANSUhEUgAAAAwAAAAICAYAAADN5B7xAAAAI0lEQVR4AZXBAQEAMAyDMI5/T5W2ayB5245AIokkkkgiiST6+W4DTLyo5PUAAAAASUVORK5CYII=');307 });308 });...

Full Screen

Full Screen

upload.js

Source:upload.js Github

copy

Full Screen

1import Service from '@ember/service';2import { inject as service } from '@ember/service';3import { task, all } from 'ember-concurrency';4import { isEqual } from '@ember/utils';5import ENV from '../config/environment';6import ImageOverrideCollection from '../classes/ImageOverrideCollection';7export default Service.extend({8 fq: service('file-queue'),9 rs: service('resolutions'),10 ajax: service('ajax'),11 options: null,12 uploadProgress: 0,13 completedImages: 0,14 numImages: 0,15 uploadComplete: false,16 uploadResults: null,17 watermarkText: null,18 _imageOverrides: ImageOverrideCollection.create(),19 clearOverrides() {20 this.get('_imageOverrides').empty();21 },22 updateOptions(options) {23 this.set('options', options);24 },25 updateImageOverride(imgOverride) {26 this.get('_imageOverrides').update(imgOverride);27 },28 getImageOverride(image) {29 return this.get('_imageOverrides').findByImage(image);30 },31 async uploadImages() {32 await this.get('_uploadImages').perform();33 },34 clearPreviousUpload() {35 this.set('uploadProgress', 0);36 this.set('completedImages', 0);37 this.set('numImages', 0);38 this.set('uploadComplete', false);39 this.set('uploadResults', null);40 },41 clearAll() {42 this.clearPreviousUpload();43 this.set('options', null);44 this.set('watermarkText', null);45 this.clearOverrides();46 },47 _uploadImages: task(function*() {48 const iq = this.get('fq').find('images');49 const images = iq.get('files');50 this.set('numImages', images.get('length'));51 const resolutions = this.get('rs').get('resolutions');52 const watermark = this.get('fq')53 .find('watermarks')54 .get('files.firstObject');55 const watermarkText = this.get('watermarkText');56 const options = this.get('options');57 let childTasks = [];58 for (const image of images) {59 let form = new FormData();60 form.append('image', image.get('blob'), image.get('name'));61 const ovr = this.get('_imageOverrides').findByImage(image);62 let quality = options.get('quality');63 if (ovr) {64 if (ovr.get('quality')) {65 quality = ovr.get('quality');66 } else quality = '0';67 form.append('quality', quality);68 if (ovr.get('resolutions')) {69 let exclusions = ovr.get('resolutions.exclusions');70 let inclusions = ovr.get('resolutions.inclusions');71 let resFilteredExclusions = resolutions.filter((res) => {72 for (const ex of exclusions) {73 if (isEqual(ex, res)) {74 return false;75 }76 }77 return true;78 });79 resFilteredExclusions = resFilteredExclusions.concat(inclusions);80 if (resFilteredExclusions.get('length')) {81 let resMapped = resFilteredExclusions.map(82 this._mapResolutionForUpload83 );84 form.append('resolutions', resMapped);85 }86 }87 if (ovr.get('useWatermark')) {88 if (watermark) {89 form.append(90 'watermark',91 watermark.get('blob'),92 watermark.get('name')93 );94 }95 if (watermarkText) form.append('watermarkText', watermarkText);96 }97 } else {98 form.append('quality', quality);99 if (resolutions.get('length')) {100 let resMapped = resolutions.map(this._mapResolutionForUpload);101 form.append('resolutions', resMapped);102 }103 if (watermark) {104 form.append(105 'watermark',106 watermark.get('blob'),107 watermark.get('name')108 );109 }110 if (watermarkText) form.append('watermarkText', watermarkText);111 }112 childTasks.push(113 this.get('_doUpload').perform(114 form,115 image.get('name'),116 image.get('type')117 )118 );119 }120 let results = yield all(childTasks);121 this.set('uploadResults', results);122 this.set('uploadComplete', true);123 }).restartable(),124 _mapResolutionForUpload(res) {125 return res.get('width').toString() + 'x' + res.get('height').toString();126 },127 _doUpload: task(function*(form, name, type) {128 let resp = yield this._uploadForm(form);129 this.set('completedImages', this.get('completedImages') + 1);130 this.set(131 'uploadProgress',132 this.get('completedImages') / this.get('numImages') * 100133 );134 return { response: resp, name: name, type: type };135 })136 .maxConcurrency(10)137 .enqueue(),138 _uploadForm(form) {139 return this.get('ajax').request(ENV.APP.API_URL + '/aperture', {140 method: 'POST',141 data: form,142 processData: false,143 contentType: false144 });145 }...

Full Screen

Full Screen

findbyimage_client.js

Source:findbyimage_client.js Github

copy

Full Screen

1import React from 'react'2import { API } from 'aws-amplify';3class FindByImageComp extends React.Component {4 constructor(props) {5 super(props);6 this.findbyimage_style = {7 marginTop: '20px',8 marginBottom: '20px'9 }10 }11 onChange = (e) => {12 console.log("file to upload:", e.target.files[0])13 this.file = e.target.files[0]14 if (this.file) {15 const reader = new FileReader();16 reader.onload = this._handleReaderLoaded.bind(this)17 reader.readAsBinaryString(this.file)18 }19 }20 _handleReaderLoaded = (readerEvt) => {21 let binaryString = readerEvt.target.result22 this.setState({23 base64TextString: btoa(binaryString)24 })25 }26 onFileSubmit = (e) => {27 e.preventDefault()28 //console.log("binary string:", this.state.base64TextString)29 console.log("binary string:", this.file.name)30 const apiName = 'fit5225web'; // replace this with your api name.31 const path = '/find-by-image'; //replace this with the path you have configured on your API32 const myInit = {33 body: { name: this.file.name, file: this.state.base64TextString }, // replace this with attributes you need34 headers: {35 }, // OPTIONAL36 };37 API38 .post(apiName, path, myInit)39 .then(response => {40 alert('Relevant urls: ' + response.body.links); // <- might be need some test41 console.log(response.status);42 })43 .catch(error => {44 console.log(error.response);45 });46 }47 render() {48 return (49 <React.Fragment>50 <div style={this.findbyimage_style}>51 <h2> Find by image </h2>52 <p> Please submit the file to search relevant image urls</p>53 <form onSubmit={(e) => this.onFileSubmit(e)} onChange={(e) => this.onChange(e)}>54 <input type="file" name="image" id="file" accept=".jpeg, .png, .jpg" />55 <input type="submit" />56 </form>57 </div>58 </React.Fragment>59 )60 }61}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const express = require('express');2const parser = require('body-parser').json();3const formidble = require('express-formidable')({ uploadDir: './public' });4const fs = require('fs');5const getFaceByImageUrl = require('./api/uploadFace');6const getNameByFaceId = require('./api/identify');7const app = express();8app.use(express.static('public'));9app.listen(process.env.PORT || 3000, () => console.log('server started'));10app.get('/', (req, res) => res.send('Still alive'));11app.post('/findByUrl', parser, async (req, res) => {12 const { imageUrl } = req.body;13 console.log('URL:::', imageUrl);14 try {15 const faceId = await getFaceByImageUrl(imageUrl);16 const name = await getNameByFaceId(faceId);17 res.send(name);18 } catch (e) {19 console.log(e + '');20 res.send(`${e} `);21 }22});23app.post('/findByImage', formidble, (req, res) => {24 let { path } = req.files.avatar;25 fs.rename(path, `${path}.png`.replace('_', ''), err => {26 if (err) return res.send(`${err} `);27 path = `${path}.png`;28 let output = path.replace('public/', '').replace('_', '');29 output = `https://khoapham-face.herokuapp.com/${output}`;30 res.send(output);31 });32});33app.get('/list', (req, res) => {34 fs.readdir('./public', (err, files) => {35 if (err) return res.send(`${err} `); 36 res.send(files.join('\n'));37 });...

Full Screen

Full Screen

petActions.js

Source:petActions.js Github

copy

Full Screen

1import { navigate } from "@reach/router";2import { getAuthHeader } from "../Auth/firebaseService";3import { config } from "../config";4export const SET_PETS = 'SET_PETS';5export const SET_LOADER = "SET_LOADER";6export const loadPetsWithQuery = (query) => (dispatch, getStore) => {7 const url = new URL(`${config.hostname}/pet/get`);8 fetch(url, {9 method: "POST",10 headers: {11 "Content-Type": "application/json",12 Authorization: getAuthHeader(),13 },14 body: JSON.stringify(query),15 }).then(async (response) => {16 if (response.ok) {17 const pets = await response.json();18 dispatch({19 type: SET_PETS,20 pets,21 });22 } else {23 console.error(response);24 }25 });26};27export const findByImage = (petId) => (dispatch, getStore) => {28 const url = new URL(`${config.hostname}/pet/photo/${petId}`);29 console.log('SEND REQUEST', url);30 fetch(url, {31 method: "GET",32 headers: {33 Authorization: getAuthHeader(),34 },35 }).then(async (response) => {36 if (response.ok) {37 const pets = await response.json();38 console.log(pets);39 dispatch({40 type: SET_PETS,41 pets,42 });43 navigate("/photo-result");44 } else {45 console.error(response);46 }47 });48};49export const setLoaderMainPage=(isLoading)=>(dispatch, getStore) => {50 dispatch({51 type:SET_LOADER,52 value:isLoading53 })...

Full Screen

Full Screen

productRepository.js

Source:productRepository.js Github

copy

Full Screen

1const Products = require('../../../models/products')2const Model = require('../../../models')3const repository = Products(Model.sequelize, Model.Sequelize.DataTypes)45module.exports = {6 findByimage,7 create,8 findAll,9 findById10}1112async function findByimage(image) {13 const product = await repository.findOne({ where: { image } })14 return product15}1617async function create(price, title, reviewScore, brand, image) {18 const product = await repository.create({ price, title, reviewScore, brand, image})19 return product20}2122async function findAll(){23 const product = await repository.findAll()24 return product25}2627async function findById(id){28 const customer = await repository.findOne({ where: { id } })29 return customer ...

Full Screen

Full Screen

uploadRemove.js

Source:uploadRemove.js Github

copy

Full Screen

1import RNFetchBlob from 'react-native-fetch-blob'2//original: https://khoapham-face.herokuapp.com/findByImage3// dont forget to include port 5000 or whatever when using this4let uploadRemove = (data) => {5 console.log("SENDING NEW TO LOCAL???")6 return RNFetchBlob.config({7 fileCache : true,8 })9 .fetch('POST', 'http://10.0.1.9:5000/face_remove', {10 Authorization : "Bearer access-token",11 otherHeader : "foo",12 'Content-Type' : 'multipart/form-data',13 }, data);14}...

Full Screen

Full Screen

uploadNew.js

Source:uploadNew.js Github

copy

Full Screen

1import RNFetchBlob from 'react-native-fetch-blob'2//original: https://khoapham-face.herokuapp.com/findByImage3// dont forget to include port 5000 or whatever when using this4let uploadNew = (data) => {5 console.log("SENDING NEW TO LOCAL???")6 return RNFetchBlob.config({7 fileCache : true,8 })9 .fetch('POST', 'http://10.0.1.9:5000/face_new', {10 Authorization : "Bearer access-token",11 otherHeader : "foo",12 'Content-Type' : 'multipart/form-data',13 }, data);14}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')5 .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10driver.findElement(By.image('/path/to/image.png')).click();11driver.findElement(By.image('/path/to/image.png')).click();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { driver } = require('appium-base-driver');2const { BaseDriver } = require('appium-base-driver');3const { ImageElement } = require('appium-base-driver');4const { ImageElementStore } = require('appium-base-driver');5const { ImageElementCommand } = require('appium-base-driver');6const { ImageElementCommandHandler } = require('appium-base-driver');7const { ImageElementCommandHandlerFactory } = require('appium-base-driver');8 at Object.<anonymous> (/Users/username/Documents/AppiumTests/test.js:4:13)9const { driver } = require('appium-base-driver');10const { BaseDriver } = require('appium-base-driver');11const { ImageElement } = require('appium-base-driver');12const { ImageElementStore } = require('appium-base-driver');13const { ImageElementCommand } = require('appium-base-driver');14const { ImageElementCommandHandler } = require('appium-base-driver');15const { ImageElementCommandHandlerFactory } = require('appium-base-driver');

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.init({2}).then(function() {3 return driver.findElementsByImage("test.png");4}).then(function(el) {5 console.log(el);6 return driver.quit();7}).done();

Full Screen

Using AI Code Generation

copy

Full Screen

1var driver = new webdriver.Builder()2 .forBrowser('chrome')3 .build();4var d = new AppiumDriver(driver);5d.findByImage('test.png').then(function (el) {6 console.log('Found element: ' + el);7});8driver.quit();9var driver = new webdriver.Builder()10 .forBrowser('chrome')11 .build();12var d = new AppiumDriver(driver);13d.findByImage('test.png').then(function (el) {14 console.log('Found element: ' + el);15});16driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var path = require('path');3var wdHelper = require('./helpers/wdHelper');4var desired = {5 app: path.resolve(__dirname, '../apps/ApiDemos-debug.apk')6};7var driver = wd.promiseChainRemote('localhost', 4723);8wdHelper.configureAppium(driver, desired);9 .init(desired)10 .then(function () {11 return driver.findByImage(path.resolve(__dirname, '../test.png'));12 })13 .then(function (el) {14 return driver.elementIdText(el.ELEMENT);15 })16 .then(function (text) {17 console.log(text);18 })19 .fin(function () {20 return driver.quit();21 })22 .done();23var wd = require('wd');24module.exports.configureAppium = function (driver, desired) {25 driver.configureHttp({26 });27 driver.on('status', function (info) {28 console.log('\x1b[36m%s\x1b[0m', info);29 });30 driver.on('command', function (meth, path, data) {31 console.log(' > \x1b[33m%s\x1b[0m: %s', meth, path, data || '');32 });33 driver.on('http', function (meth, path, data) {34 console.log(' > \x1b[90m%s\x1b[0m %s %j', meth, path, data || '');35 });36};37{38 "scripts": {39 },40 "dependencies": {

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 Base Driver 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