How to use fs.which method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

Run Appium Android Driver automation tests on LambdaTest cloud grid

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

screenshots-specs.js

Source: screenshots-specs.js Github

copy
1import sinon from 'sinon';
2import XCUITestDriver from '../../..';
3import { fs, tempDir } from 'appium-support';
4
5const simctlModule = require('node-simctl');
6const teenProcessModule = require('teen_process');
7
8describe('screenshots commands', function () {
9  let driver;
10  let proxyStub;
11
12  const base64Response = 'aGVsbG8=';
13
14  beforeEach(function () {
15    driver = new XCUITestDriver();
16    proxyStub = sinon.stub(driver, 'proxyCommand');
17  });
18  afterEach(function () {
19    proxyStub.reset();
20  });
21
22  describe('getScreenshot', function () {
23    describe('simulator', function () {
24      let simctlStub = sinon.stub(simctlModule, 'getScreenshot');
25
26      afterEach(function () {
27        simctlStub.reset();
28      });
29
30      it('should get a screenshot from WDA if no errors are detected', async function () {
31        proxyStub.returns(base64Response);
32        driver.opts.realDevice = false;
33
34        await driver.getScreenshot();
35
36        proxyStub.calledOnce.should.be.true;
37        proxyStub.firstCall.args[0].should.eql('/screenshot');
38        proxyStub.firstCall.args[1].should.eql('GET');
39
40        simctlStub.notCalled.should.be.true;
41      });
42
43      it('should get a screenshot from simctl if WDA call fails and Xcode version >= 8.1', async function () {
44        proxyStub.returns(null);
45        simctlStub.returns(base64Response);
46
47        driver.opts.realDevice = false;
48        driver.xcodeVersion = {
49          versionFloat: 8.3
50        };
51        const result = await driver.getScreenshot();
52        result.should.equal(base64Response);
53
54        proxyStub.calledOnce.should.be.true;
55        simctlStub.calledOnce.should.be.true;
56      });
57    });
58
59    describe('real device', function () {
60      it('should get a screenshot from WDA if no errors are detected', async function () {
61        proxyStub.returns(base64Response);
62        driver.opts.realDevice = true;
63
64        await driver.getScreenshot();
65
66        proxyStub.calledOnce.should.be.true;
67        proxyStub.firstCall.args[0].should.eql('/screenshot');
68        proxyStub.firstCall.args[1].should.eql('GET');
69      });
70
71      describe('idevicescreenshot', function () {
72        const tiffPath = '/some/file.tiff';
73        const pngPath = '/some/file.png';
74        const udid = '1234';
75        const toolName = 'idevicescreenshot';
76        const pngFileContent = 'blabla';
77
78        let fsExistsStub;
79        let fsWhichStub;
80        let fsRimRafStub;
81        let fsReadFileStub;
82        let execStub;
83        let pathStub;
84
85        beforeEach(function () {
86          driver.opts.realDevice = true;
87          driver.opts.udid = udid;
88        });
89        afterEach(function () {
90          for (const stub of [fsExistsStub, fsWhichStub, fsReadFileStub, fsRimRafStub, execStub, pathStub]) {
91            if (stub) {
92              stub.restore();
93            }
94          }
95        });
96
97        describe('success', function () {
98          beforeEach(function () {
99            fsExistsStub = sinon.stub(fs, 'exists');
100            fsExistsStub.returns(true);
101
102            fsWhichStub = sinon.stub(fs, 'which');
103            fsWhichStub.returns(toolName);
104
105            fsRimRafStub = sinon.stub(fs, 'rimraf');
106
107            fsReadFileStub = sinon.stub(fs, 'readFile');
108            fsReadFileStub.returns(pngFileContent);
109
110            execStub = sinon.stub(teenProcessModule, 'exec');
111
112            pathStub = sinon.stub(tempDir, 'path');
113            pathStub.withArgs({prefix: `screenshot-${udid}`, suffix: '.tiff'}).returns(tiffPath);
114            pathStub.withArgs({prefix: `screenshot-${udid}`, suffix: '.png'}).returns(pngPath);
115          });
116          afterEach(function () {
117            fsWhichStub.calledOnce.should.be.true;
118            fsWhichStub.firstCall.args[0].should.eql(toolName);
119
120            execStub.calledTwice.should.be.true;
121            execStub.firstCall.args[0].should.eql(toolName);
122            execStub.firstCall.args[1].should.eql(['-u', udid, tiffPath]);
123            execStub.secondCall.args[0].should.eql('sips');
124            execStub.secondCall.args[1].should.eql(
125              ['-r', '-90', '-s', 'format', 'png', tiffPath, '--out', pngPath]);
126
127            fsRimRafStub.callCount.should.eql(4);
128
129            fsReadFileStub.calledOnce.should.be.true;
130            fsReadFileStub.firstCall.args[0].should.eql(pngPath);
131
132            pathStub.calledTwice.should.be.true;
133          });
134
135          it('should use idevicescreenshot if WDA fails', async function () {
136            proxyStub.onFirstCall().returns(null);
137            proxyStub.onSecondCall().returns('LANDSCAPE');
138
139            (await driver.getScreenshot()).should.eql(pngFileContent.toString('base64'));
140
141            proxyStub.callCount.should.eql(2);
142            proxyStub.firstCall.args.should.eql(['/screenshot', 'GET']);
143            proxyStub.secondCall.args.should.eql(['/orientation', 'GET']);
144          });
145          it('should use idevicescreenshot if specified in realDeviceScreenshotter cap', async function () {
146            proxyStub.onFirstCall().returns('LANDSCAPE');
147            driver.opts.realDeviceScreenshotter = 'idevicescreenshot';
148
149            (await driver.getScreenshot()).should.eql(pngFileContent.toString('base64'));
150
151            proxyStub.callCount.should.eql(1);
152          });
153        });
154        describe('failure', function () {
155          beforeEach(function () {
156
157            proxyStub.onFirstCall().returns(null);
158
159            fsWhichStub = sinon.stub(fs, 'which');
160            fsWhichStub.throws(new Error('No program found'));
161          });
162          afterEach(function () {
163            fsWhichStub.calledOnce.should.be.true;
164            fsWhichStub.firstCall.args[0].should.eql(toolName);
165          });
166
167          it('should throw an error if idevicescreenshot is not available and realDeviceScreenshotter set', async function () {
168            driver.opts.realDeviceScreenshotter = 'idevicescreenshot';
169            await driver.getScreenshot().should.eventually.be.rejectedWith(/No 'idevicescreenshot' program found/);
170          });
171        });
172      });
173    });
174  });
175});
176
Full Screen

location-specs.js

Source: location-specs.js Github

copy
1import sinon from 'sinon';
2import XCUITestDriver from '../../..';
3import { fs } from 'appium-support';
4import * as teenProcess from 'teen_process';
5
6describe('location commands', function () {
7  const udid = '1234';
8  const toolName = 'idevicelocation';
9
10  const driver = new XCUITestDriver();
11  const proxySpy = sinon.stub(driver, 'proxyCommand');
12
13  afterEach(function () {
14    proxySpy.reset();
15  });
16
17  describe('setLocation', function () {
18    let execStub;
19    let fsWhichStub;
20
21    beforeEach(function () {
22      execStub = sinon.stub(teenProcess, 'exec');
23      fsWhichStub = sinon.stub(fs, 'which');
24    });
25
26    afterEach(function () {
27      execStub.restore();
28      fsWhichStub.restore();
29    });
30
31    it('should fail when location object is wrong', async function () {
32      await driver.setGeoLocation({}).should.be.rejectedWith('Both latitude and longitude should be set');
33    });
34
35    describe('on real device', function () {
36      beforeEach(function () {
37        driver.opts.udid = udid;
38        driver.opts.realDevice = true;
39      });
40
41      it('should use idevicelocation to set a location', async function () {
42        fsWhichStub.returns(toolName);
43        await driver.setGeoLocation({latitude: '1.234', longitude: '2.789'});
44
45        execStub.calledOnce.should.be.true;
46        execStub.firstCall.args[0].should.eql(toolName);
47        execStub.firstCall.args[1].should.eql(['-u', udid, '1.234', '2.789']);
48      });
49
50      it('should use idevicelocation to set a location with negative values', async function () {
51        fsWhichStub.returns(toolName);
52        await driver.setGeoLocation({latitude: 1.234, longitude: -2});
53
54        execStub.calledOnce.should.be.true;
55        execStub.firstCall.args[0].should.eql(toolName);
56        execStub.firstCall.args[1].should.eql(['-u', udid, '1.234', '--', '-2']);
57      });
58
59      it('should fail when idevicelocation doesnt exist on the host', async function () {
60        fsWhichStub.throws();
61        await driver.setGeoLocation({
62          latitude: '1.234',
63          longitude: '2.789'}
64        ).should.be.rejectedWith(`idevicelocation doesn't exist on the host`);
65      });
66    });
67
68    describe('on simulator', function () {
69      let deviceSetLocationSpy;
70      beforeEach(function () {
71        driver.opts.realDevice = false;
72
73        deviceSetLocationSpy = sinon.spy();
74        driver.opts.device = {
75          setGeolocation: deviceSetLocationSpy,
76        };
77      });
78      afterEach(function () {
79        deviceSetLocationSpy.resetHistory();
80      });
81      it('should set string coordinates', async function () {
82        await driver.setGeoLocation({latitude: '1.234', longitude: '2.789'});
83        deviceSetLocationSpy.firstCall.args[0].should.eql('1.234');
84        deviceSetLocationSpy.firstCall.args[1].should.eql('2.789');
85      });
86      it('should set number coordinates', async function () {
87        await driver.setGeoLocation({latitude: 1, longitude: -2});
88        deviceSetLocationSpy.firstCall.args[0].should.eql('1');
89        deviceSetLocationSpy.firstCall.args[1].should.eql('-2');
90      });
91    });
92  });
93});
94
Full Screen

whichFallback.js

Source: whichFallback.js Github

copy
1// TODO: properly rewrite tests by using sinon
2import { module, test } from "qunit";
3
4import whichFallbackInjector from "inject-loader!utils/node/fs/whichFallback";
5
6
7module( "utils/node/fs/whichFallback" );
8
9
10test( "No fallback", async assert => {
11
12	assert.expect( 24 );
13
14	let expected;
15	let isExecutable = () => true;
16
17	const { default: whichFallback } = whichFallbackInjector({
18		"path": {},
19		"utils/node/resolvePath": {},
20		"utils/node/platform": {
21			platform: "linux"
22		},
23		"utils/node/fs/stat": {
24			isExecutable,
25			async stat() {
26				assert.ok( false, "Should not get called" );
27			}
28		},
29		"utils/node/fs/which": async ( path, callback ) => {
30			assert.step( path );
31			if ( path !== expected ) {
32				throw new Error();
33			}
34			assert.strictEqual( callback, isExecutable, "Uses the correct verification callback" );
35			return path;
36		}
37	});
38
39	await assert.rejects(
40		whichFallback( "" ),
41		new Error( "Missing executable name" ),
42		"Rejects on missing executable"
43	);
44
45	await assert.rejects(
46		whichFallback( "foo" ),
47		new Error( "Executables were not found" ),
48		"Rejects"
49	);
50	assert.checkSteps( [ "foo" ], "Calls which() in correct order" );
51
52	await assert.rejects(
53		whichFallback([ "foo", "bar" ]),
54		new Error( "Executables were not found" ),
55		"Rejects"
56	);
57	assert.checkSteps( [ "foo", "bar" ], "Calls which() in correct order" );
58
59	await assert.rejects(
60		whichFallback({ linux: "foo", darwin: "bar" }),
61		new Error( "Executables were not found" ),
62		"Rejects"
63	);
64	assert.checkSteps( [ "foo" ], "Calls which() in correct order" );
65
66	await assert.rejects(
67		whichFallback({ linux: [ "foo", "baz" ], darwin: "bar" }),
68		new Error( "Executables were not found" ),
69		"Rejects"
70	);
71	assert.checkSteps( [ "foo", "baz" ], "Calls which() in correct order" );
72
73	expected = "bar";
74
75	await ( async () => {
76		const resolvedPath = await whichFallback([ "foo", "bar", "baz" ]);
77		assert.strictEqual( resolvedPath, "bar", "Resolves with correct path" );
78		assert.checkSteps( [ "foo", "bar" ], "Calls which() in correct order" );
79	})();
80
81	isExecutable = () => false;
82
83	await ( async () => {
84		const resolvedPath = await whichFallback( "bar", null, isExecutable );
85		assert.strictEqual( resolvedPath, "bar", "Resolves with correct path" );
86		assert.checkSteps( [ "bar" ], "Calls which() in correct order" );
87	})();
88
89});
90
91
92test( "Fallback only", async assert => {
93
94	assert.expect( 73 );
95
96	let expected;
97	let isExecutable = () => true;
98
99	const { default: whichFallback } = whichFallbackInjector({
100		"path": {
101			join( ...args ) {
102				assert.step( "join" );
103				return args.join( "/" );
104			}
105		},
106		"utils/node/platform": {
107			platform: "linux"
108		},
109		"utils/node/resolvePath": path => {
110			assert.step( "resolvePath" );
111			assert.step( path );
112			return path;
113		},
114		"utils/node/fs/stat": {
115			isExecutable,
116			async stat( path, callback ) {
117				assert.step( "stat" );
118				assert.step( path );
119				if ( expected !== path ) {
120					throw new Error();
121				}
122				assert.strictEqual( callback, isExecutable, "Uses correct verification callback" );
123				return path;
124			}
125		},
126		"utils/node/fs/which": async () => {
127			assert.ok( false, "Should not get called" );
128		}
129	});
130
131	await assert.rejects(
132		whichFallback( "a", "/A", null, true ),
133		new Error( "Executables were not found" ),
134		"Rejects"
135	);
136	assert.checkSteps(
137		[
138			"resolvePath", "/A",
139			"join", "stat", "/A/a"
140		],
141		"Calls methods in correct order"
142	);
143
144	await assert.rejects(
145		whichFallback( [ "a", "b" ], [ "/A", "/B" ], null, true ),
146		new Error( "Executables were not found" ),
147		"Rejects"
148	);
149	assert.checkSteps(
150		[
151			"resolvePath", "/A",
152			"join", "stat", "/A/a",
153			"join", "stat", "/A/b",
154			"resolvePath", "/B",
155			"join", "stat", "/B/a",
156			"join", "stat", "/B/b"
157		],
158		"Calls methods in correct order"
159	);
160
161	await assert.rejects(
162		whichFallback(
163			[ "a", "b" ],
164			{
165				linux: [ "/A", "/B" ],
166				darwin: [ "/C", "/D" ]
167			},
168			null,
169			true
170		),
171		new Error( "Executables were not found" ),
172		"Rejects"
173	);
174	assert.checkSteps(
175		[
176			"resolvePath", "/A",
177			"join", "stat", "/A/a",
178			"join", "stat", "/A/b",
179			"resolvePath", "/B",
180			"join", "stat", "/B/a",
181			"join", "stat", "/B/b"
182		],
183		"Calls methods in correct order"
184	);
185
186	expected = "/B/b";
187
188	await ( async () => {
189		const path = await whichFallback( [ "a", "b", "c" ], [ "/A", "/B", "/C" ], null, true );
190		assert.strictEqual( path, expected, "Resolves" );
191		assert.checkSteps(
192			[
193				"resolvePath", "/A",
194				"join", "stat", "/A/a",
195				"join", "stat", "/A/b",
196				"join", "stat", "/A/c",
197				"resolvePath", "/B",
198				"join", "stat", "/B/a",
199				"join", "stat", "/B/b"
200			],
201			"Calls methods in correct order"
202		);
203	})();
204
205	isExecutable = () => false;
206
207	await ( async () => {
208		const path = await whichFallback( "b", "/B", isExecutable, true );
209		assert.strictEqual( path, expected, "Resolves" );
210		assert.checkSteps(
211			[
212				"resolvePath", "/B",
213				"join", "stat", "/B/b"
214			],
215			"Calls methods in correct order"
216		);
217	})();
218
219});
220
221
222test( "With fallback", async assert => {
223
224	assert.expect( 49 );
225
226	let expected;
227	let isExecutable = () => true;
228
229	const check = name => async ( path, callback ) => {
230		assert.step( name );
231		assert.step( path );
232		if ( expected !== path ) {
233			throw new Error();
234		}
235		assert.strictEqual( callback, isExecutable, "Uses correct verification callback" );
236		return path;
237	};
238
239	const { default: whichFallback } = whichFallbackInjector({
240		"path": {
241			join( ...args ) {
242				assert.step( "join" );
243				return args.join( "/" );
244			}
245		},
246		"utils/node/platform": {
247			platform: "linux"
248		},
249		"utils/node/resolvePath": path => {
250			assert.step( "resolvePath" );
251			assert.step( path );
252			return path;
253		},
254		"utils/node/fs/stat": {
255			isExecutable,
256			stat: check( "stat" )
257		},
258		"utils/node/fs/which": check( "which" )
259	});
260
261	await assert.rejects(
262		whichFallback( [ "a", "b" ], [ "/A", "/B" ] ),
263		new Error( "Executables were not found" ),
264		"Rejects"
265	);
266	assert.checkSteps(
267		[
268			"which", "a",
269			"which", "b",
270			"resolvePath", "/A",
271			"join", "stat", "/A/a",
272			"join", "stat", "/A/b",
273			"resolvePath", "/B",
274			"join", "stat", "/B/a",
275			"join", "stat", "/B/b"
276		],
277		"Calls methods in correct order"
278	);
279
280	expected = "b";
281
282	await ( async () => {
283		const resolvedPath = await whichFallback( [ "a", "b" ], [ "/A", "/B" ] );
284		assert.strictEqual( resolvedPath, expected, "Resolves" );
285		assert.checkSteps(
286			[
287				"which", "a",
288				"which", "b"
289			],
290			"Calls methods in correct order"
291		);
292	})();
293
294	expected = "/B/a";
295
296	await ( async () => {
297		const resolvedPath = await whichFallback( [ "a", "b" ], [ "/A", "/B" ] );
298		assert.strictEqual( resolvedPath, expected, "Resolves" );
299		assert.checkSteps(
300			[
301				"which", "a",
302				"which", "b",
303				"resolvePath", "/A",
304				"join", "stat", "/A/a",
305				"join", "stat", "/A/b",
306				"resolvePath", "/B",
307				"join", "stat", "/B/a"
308			],
309			"Calls methods in correct order"
310		);
311	})();
312
313});
314
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Appium Android Driver on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)