python脚本实现安卓app的流量消耗测试。

一、用到的adb命令

(1)获取进程ID指令:
adb shell "ps | grep packagename"
(2)获取进程ID流量:
adb shell cat /proc/pid/net/dev

二、脚本实现策略

(1)设定一个场景,测试一段时间(此处最好再写一个自动化测试的脚本)。
(2)记录网卡eth0和eth1的Recevice和Transmit值,取本次流量值和上次流量值之差为所消耗的流量。

三、测试数据分析

(1)不同版本之间对比
(2)竞品之间对比

四、代码实现示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
#coding=utf-8

import os
import time
import csv

#控制类
class Controller(object):
def __init__(self,count):
self.counter = count
self.allData = [('timestamp','traffic')]

#单次获取流量值
def traffic(self):
cmd = 'adb shell "ps | grep com.android.browser"'
#截取进程id
pid = os.popen(cmd).readlines()[0].split(' ')[5]
#获取进程id所使用的流量
traffic = os.popen('adb shell cat /proc/'+pid+'/net/dev')

for line in traffic:
if 'eth0' in line:
#将所有空行换成'#'
line = '#'.join(line.split())
recevice0 = line.split('#')[1]
transmit0 = line.split('#')[9]
elif 'eth1' in line:
#将所有空行换成'#'
line = '#'.join(line.split())
recevice1 = line.split('#')[1]
transmit1 = line.split('#')[9]
#计算流量总和
alltraffic = int(recevice0)+int(transmit0)+int(recevice1)+int(transmit1)
#流量总和按KB计算
alltraffic = alltraffic/1024

currenttime = self.getCurrentTime()
self.allData.append((currenttime,alltraffic))

#多次获取流量值
def run(self):
while self.counter>0:
self.traffic()
self.counter = self.counter-1
time.sleep(5)

#获取当前时间戳
def getCurrentTime(self):
currentTime = time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime())
return currentTime

#数据存储
def SavaDataToCsv(self):
with open('traffic.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(self.allData)

if __name__ == '__main__':
controller = Controller(5)
controller.run()
controller.SavaDataToCsv()

五、测试结果示例

流量消耗

持续更新…

最后更新: 2018年05月11日 14:51

原始链接: http://pythonfood.github.io/2018/01/01/安卓专项测试-流量/

× 多少都行~
打赏二维码