python3 利用wget下载文件,并对下载时间进行统计分析

背景

产品页面某个资源下载慢,初步推断服务端配置问题,需进行多次测试验证。

测试设计

  1. 利用wget下载资源文件
  2. 记录下载时间
  3. 多次下载,计算超过3秒频次

为什么不用并发测试?

下载是写文件,磁盘会是瓶颈。
如果能把文件只是网络读取到内存中,而不写到磁盘的话,并发测试没问题。

代码

import subprocess
from subprocess import Popen, PIPE
import time
import os
from os import listdir
import re
import logging
logging.basicConfig(filename=r'./download_%s.log' % time.strftime("%Y-%m-%d_%H%M%S", time.localtime()), level=logging.DEBUG)

def down(args):
  	ret = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    str_ret = ret.stdout.decode("utf-8","ignore")

    print('downloading %s' % args[1])
    logging.debug(str_ret)
    return str_ret

def out_format(s):
    pat = r'(?<=100%\s).+'
    ans = re.search(pat, s).group()
    ans2 = re.search(r'(?<==).+', ans).group()
    ans3 = ans2.split('s')[0]
    return ans3


def del_file():
    file_path = './'
    for file_name in listdir(file_path):
        if file_name.startswith('test'):
            os.remove(file_path+file_name)

def get_public_ip():
    args = ['curl', 'http://myip.ipip.net']
    ret = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    str_ret = ret.stdout.decode("utf-8","ignore")
    print(str_ret)
    pat = r'(?<=当前\s).+'
    ip = re.search(pat, str_ret).group()
    logging.debug(ip)
    return ip


if __name__=="__main__":
    hosts = ['im.test1.com', '192.168.0.0', '192.168.0.1', '192.168.0.2']
    url = 'https://%s/test.js' % hosts[3]
    
    time_list = []
    cnt = 0
    get_public_ip()

    args = ['wget', url, '--no-check-certificate', '--timeout=3']
    for i in range(3):
        stdout = down(args)
        print('download successful - %s' % i)
        cnt += 1
        ans = out_format(stdout)
        print('download time: %sS' % ans)
        time_list.append(ans)
        time.sleep(1)
        del_file()
    
    tg3 = list(filter(lambda x: float(x) >=3.0, time_list))
    float_time = [float(x) for x in time_list]
    print(float_time)
    logging.debug('下载时间详情:\n%s' % float_time)
    max_t = max(float_time)
    min_t = min(float_time)
    print('下载总数:\t%s\n超过3s次数:\t%s\n最大时间:\t%sS\n最小时间:\t%sS' %(cnt, len(tg3), max_t, min_t))
    logging.debug('下载总数:\t%s\n超过3s次数:\t%s\n最大时间:\t%sS\n最小时间:\t%sS' %(cnt, len(tg3), max_t, min_t))
        

你可能感兴趣的:(python)