How to use driver.getBatteryInfo 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.

performance-specs.js

Source: performance-specs.js Github

copy
1import chai from 'chai';
2import chaiAsPromised from 'chai-as-promised';
3import sinon from 'sinon';
4import AndroidDriver from '../../..';
5import { SUPPORTED_PERFORMANCE_DATA_TYPES, NETWORK_KEYS, CPU_KEYS, BATTERY_KEYS,
6         MEMORY_KEYS} from '../../../lib/commands/performance.js';
7import _ from 'lodash';
8import ADB from 'appium-adb';
9import * as asyncbox from 'asyncbox';
10
11chai.should();
12chai.use(chaiAsPromised);
13
14const PACKAGE_NAME = 'io.appium.android.apis';
15const RETRY_PAUSE = 1000;
16const RETRY_COUNT = 2;
17
18let sandbox = sinon.createSandbox();
19let adb;
20let driver;
21
22describe('performance data', function () {
23  beforeEach(function () {
24    adb = new ADB();
25    driver = new AndroidDriver();
26    driver.adb = adb;
27    sandbox.stub(adb);
28    sandbox.stub(asyncbox, 'retryInterval').callsFake(async function (times, sleepMs, fn) {
29      return await fn();
30    });
31  });
32  afterEach(function () {
33    sandbox.restore();
34  });
35  describe('getPerformanceDataTypes', function () {
36    it('should get the list of available getPerformance data type', function () {
37      let types = driver.getPerformanceDataTypes();
38      types.should.eql(_.keys(SUPPORTED_PERFORMANCE_DATA_TYPES));
39    });
40  });
41  describe('getPerformanceData', function () {
42    it('should return battery info', async function () {
43      sandbox.stub(driver, 'getBatteryInfo').returns('data');
44      await driver.getPerformanceData(null, 'batteryinfo').should.become('data');
45    });
46    it('should return cpu info', async function () {
47      sandbox.stub(driver, 'getCPUInfo').withArgs('pkg').returns('data');
48      await driver.getPerformanceData('pkg', 'cpuinfo').should.become('data');
49    });
50    it('should return memory info', async function () {
51      sandbox.stub(driver, 'getMemoryInfo').withArgs('pkg').returns('data');
52      await driver.getPerformanceData('pkg', 'memoryinfo').should.become('data');
53    });
54    it('should return network info', async function () {
55      sandbox.stub(driver, 'getNetworkTrafficInfo').returns('data');
56      await driver.getPerformanceData(null, 'networkinfo').should.become('data');
57    });
58    it('should throw error if data type is not valid', async function () {
59      await driver.getPerformanceData(null, 'invalid')
60        .should.be.rejectedWith(/No performance data of type 'invalid' found./);
61    });
62  });
63  describe('getCPUInfo', function () {
64    it('should return cpu data', async function () {
65      adb.shell.withArgs(['dumpsys', 'cpuinfo', '|', 'grep', `'${PACKAGE_NAME}'`])
66        .returns(' +0% 2209/io.appium.android.apis: 14% user + 23% kernel');
67      (await driver.getCPUInfo(PACKAGE_NAME)).should.be.deep
68        .equal([CPU_KEYS, ['14', '23']]);
69      asyncbox.retryInterval.calledWith(RETRY_COUNT, RETRY_PAUSE).should.be.true;
70    });
71    it('should throw error if no data', async function () {
72      adb.shell.returns(null);
73      await driver.getCPUInfo(PACKAGE_NAME, 1).should.be
74        .rejectedWith(/No data from dumpsys/);
75    });
76    it('should throw error if cpu data is not in valid format', async function () {
77      adb.shell.returns('invalid data');
78      await driver.getCPUInfo(PACKAGE_NAME, 1).should.be
79        .rejectedWith(/Unable to parse cpu data/);
80    });
81  });
82  describe('getBatteryInfo', function () {
83    it('should return battery info', async function () {
84      adb.shell.withArgs(['dumpsys', 'battery', '|', 'grep', 'level'])
85        .returns('  level: 47');
86      await driver.getBatteryInfo().should.become([BATTERY_KEYS, ['47']]);
87      asyncbox.retryInterval.calledWith(RETRY_COUNT, RETRY_PAUSE).should.be.true;
88    });
89    it('should throw error if data is not valid', async function () {
90      adb.shell.returns('invalid data');
91      await driver.getBatteryInfo(1).should.be
92        .rejectedWith(/Unable to parse battery data/);
93    });
94    it('should throw error if no data', async function () {
95      adb.shell.returns(null);
96      await driver.getBatteryInfo(1).should.be.rejectedWith(/No data from dumpsys/);
97    });
98  });
99  describe('getMemoryInfo', function () {
100    const shellArgs = ['dumpsys', 'meminfo', `'${PACKAGE_NAME}'`, '|', 'grep', '-E', "'Native|Dalvik|EGL|GL|TOTAL'"];
101    const dumpsysDataAPI19 = `
102                          Pss  Private  Private  Swapped     Heap     Heap     Heap
103                        Total    Dirty    Clean    Dirty     Size    Alloc     Free
104                       ------   ------   ------   ------   ------   ------   ------
105         Native Heap      107      102        0        0      112      111      555
106         Dalvik Heap      108      103        0        0      555      555      555
107        Dalvik Other      555      555        0        0
108          EGL mtrack      109      104        0      555        0        0        0
109           GL mtrack      110      105        0      555        0        0        0
110               TOTAL      555      555      555        0               555      555
111               TOTAL      106      101      555        0      555      555      555`;
112    const dumpsysDataAPI18 = `
113                                Shared  Private     Heap     Heap     Heap
114                          Pss    Dirty    Dirty     Size    Alloc     Free
115                       ------   ------   ------   ------   ------   ------
116              Native      107      555      102      112      111      555
117              Dalvik      108      555      103      555      555      555
118                 EGL      109      555      104      555        0        0
119                  GL      110      555      105      555        0        0
120               TOTAL      106      555      101      555      555      555`;
121    const expectedResult = [MEMORY_KEYS,
122      [
123        '101', '102', '103', '104', '105', // private dirty total|native|dalvik|egl|gl
124        '106', '107', '108', '109', '110', // pss           total|native|dalvik|egl|gl
125        '111', '112' // native        heap_alloc|heap_size
126      ],
127    ];
128    it('should return memory info for API>18', async function () {
129      adb.getApiLevel.returns(19);
130      adb.shell.withArgs(shellArgs).returns(dumpsysDataAPI19);
131      (await driver.getMemoryInfo(PACKAGE_NAME)).should.be.deep
132        .equal(expectedResult);
133      asyncbox.retryInterval.calledWith(RETRY_COUNT, RETRY_PAUSE).should.be.true;
134    });
135    it('should return memory info for API<=18', async function () {
136      adb.getApiLevel.returns(18);
137      adb.shell.withArgs(shellArgs).returns(dumpsysDataAPI18);
138      (await driver.getMemoryInfo(PACKAGE_NAME)).should.be.deep
139        .equal(expectedResult);
140      asyncbox.retryInterval.calledWith(RETRY_COUNT, RETRY_PAUSE).should.be.true;
141    });
142    it('should throw error if data is not valid', async function () {
143      adb.shell.returns('TOTAL nodex nodex nodex nodex nodex nodex nodex');
144      await driver.getMemoryInfo(PACKAGE_NAME, 1).should.be
145        .rejectedWith(/Unable to parse memory data/);
146    });
147    it('should throw error if no data', async function () {
148      adb.shell.returns(null);
149      await driver.getMemoryInfo(PACKAGE_NAME, 1).should.be
150        .rejectedWith(/No data from dumpsys/);
151    });
152  });
153  describe('getNetworkTrafficInfo', function () {
154    const shellArgs = ['dumpsys', 'netstats'];
155    const header = `
156      Xt stats:
157        Pending bytes: pbytes
158        History since boot:
159        ident=[[type=MOBILE, subType=COMBINED, subscriberId=555]] uid=-1 set=ALL tag=0x0
160          NetworkStatsHistory: bucketDuration=dur`;
161    const data = header + `
162            st=start1 rb=rb1 rp=rp1 tb=tb1 tp=tp1 op=op1
163            st=start2 rb=rb2 rp=rp2 tb=tb2 tp=tp2 op=op2`;
164    const dataInOldFormat = header + `
165            bucketStart=start1 activeTime=time1 rxBytes=rb1 rxPackets=rp1 txBytes=tb1 txPackets=tp1 operations=op1
166            bucketStart=start2 activeTime=time2 rxBytes=rb2 rxPackets=rp2 txBytes=tb2 txPackets=tp2 operations=op2`;
167    it('should return network stats', async function () {
168      adb.shell.withArgs(shellArgs).returns(data);
169      (await driver.getNetworkTrafficInfo()).should.be.deep
170        .equal([
171          NETWORK_KEYS[1],
172          ['start1', undefined, 'rb1', 'rp1', 'tb1', 'tp1', 'op1', 'dur'],
173          ['start2', undefined, 'rb2', 'rp2', 'tb2', 'tp2', 'op2', 'dur']
174        ]);
175      asyncbox.retryInterval.calledWith(RETRY_COUNT, RETRY_PAUSE).should.be.true;
176    });
177    it('should be able to parse data in old format', async function () {
178      adb.shell.withArgs(shellArgs).returns(dataInOldFormat);
179      (await driver.getNetworkTrafficInfo()).should.be.deep
180        .equal([
181          NETWORK_KEYS[0],
182          ['start1', 'time1', 'rb1', 'rp1', 'tb1', 'tp1', 'op1', 'dur'],
183          ['start2', 'time2', 'rb2', 'rp2', 'tb2', 'tp2', 'op2', 'dur']
184        ]);
185      asyncbox.retryInterval.calledWith(RETRY_COUNT, RETRY_PAUSE).should.be.true;
186    });
187    it('should be fulfilled if history is empty', async function () {
188      adb.shell.returns(header);
189      (await driver.getNetworkTrafficInfo()).should.be.deep.equal([]);
190    });
191    it('should throw error if data is not valid', async function () {
192      adb.shell.returns('nodex');
193      await driver.getNetworkTrafficInfo(1).should.be
194        .rejectedWith(/Unable to parse network traffic data/);
195    });
196    it('should throw error if no data', async function () {
197      adb.shell.returns(null);
198      await driver.getNetworkTrafficInfo(1).should.be
199        .rejectedWith(/No data from dumpsys/);
200    });
201  });
202});
203
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)