怎么样通过编写Python小程序来统计测试脚本的关键字

通常自动化测试项目到了一定的程序,编写的测试代码自然就会很多,如果很早已经编写的测试脚本现在某些基础函数、业务函数需要修改,那么势必要找出那些引用过这个被修改函数的地方,有些IDE支持全文查找和引用查找,而有些简单的可能就没有,因为日后要用到统计功能、和一些其它的需求,所以写了一个脚本。除了跟目录下全文查找引用过的文件外,还是支持统计查找到的数量,一次可以查找多个关键字,支持按主关键字来归类。
#encoding: utf-8
import os
import sys
import re
 
reload(sys)
sys.setdefaultencoding("utf-8")
 
short_exclude = [".svn", "sendbox"] ##不检查的文件、目录名
long_exclude = [] ##不包含检查的文件、目录的完整路径
extend_name = [".rb"] ##指定检查的文件后缀
temp_key_words = [
 {
  "key" : "#作者:",
  "display" : "作者",
  "times" : -1,
  "match" : "include",
  "primary_key" : True,
 },
 {
  "key" : "#[summary]",
  "display" : "完成用例数",
  "times" : -1,
  "match" : "include",
 }, 
 {
  "key" : "File.expand_path",
  "display" : "有状态行数",
  "times" : -1,
  "ignore_case" : True,
 }, 
 {
  "key" : "def\s+test_",
  "display" : "有效用例数",
  "times" : -1,
  "match" : "regex",
  "ignore_case" : True,
 }, 
 {
  "key" : "#def\s+test_",
  "display" : "注释用例数",
  "times" : -1,
  "match" : "regex",
  "ignore_case" : True,
 }, 
]
 
for kv in temp_key_words:
 if not "key" in kv:
  raise "以下的列表中没有【key】值!\n%s" % kv
 if not "key" in kv:
  raise "以下的列表中没有【display】值!\n%s" % kv 
 kv['times'] = kv.get('times', -1) ##默认为不限制检查次数 
 if kv.get("ignore_case", True)==False: ##默认忽略大小写
  flag = 0
 else:
  flag = re.I  
 kv['pattern'] = re.compile(kv['key'], flag)
 if kv.get("primary_key", False):
  kv['times'] = 1
import copy
key_words = []  
 
def deepcopy(objs):
 t_list = []
 for obj in objs:
  t_list.append(copy.copy(obj))
 return t_list
 
def loop_case(root_dir):
 t_sum = []
 print root_dir
 sub_gen = os.listdir(root_dir)
 for sub in sub_gen:
  if sub in short_exclude: ##在不检查文件、目录范围中
   continue
  abs_path = os.path.join(root_dir, sub)
  if long_exclude:
   is_exclude = False
   for exclude in long_exclude:
    if exclude == abs_path[-len(exclude):]:
     is_exclude = True
     break
   if is_exclude:
    continue
  print abs_path
  if os.path.isdir(abs_path):
   print "dir"
   t_sum.extend(loop_case(abs_path))
  elif os.path.isfile(abs_path):   
   if not "." + abs_path.rsplit(".", 1) in extend_name: ##不在后缀名 检查范围中
    continue
   print "file"
   global key_words
   key_words = deepcopy(temp_key_words)  
   t_sum.append(count_case(abs_path))
 return t_sum  
 
def count_case(abs_path): 
 t_dict = {}
 with open(abs_path) as f:
  for l in f:
   l = l.strip()
   match_rule(l)
 index = 0
 count_result = [0] * len(key_words) 
 for kv in key_words:
  if 'primary_key' in kv:
   t_dict['primary_key'] = kv.get('display')
   t_dict['primary_key_value'] = kv.get('primary_key_value', "None")
  count_result[index] = -1-kv['times']
  index += 1
 t_dict['match_result'] = count_result
 t_dict['file_path'] = abs_path
 return t_dict
 
def match_rule(line):
 primary_key = None
 for kv in key_words:
  match = False    
  if kv['times']==0: ##检查次数已满,不再检查

   continue
  if kv.get('match', "") == "regex": ##指定了匹配方式为:正则
   if kv['pattern'].match(line): ##匹配正则成功
    match = True
  else: ##默认匹配方式为: 包含
   if kv['key'] in line: ##包含了指定字符串
    match = True
  if match:
   if kv.get('primary_key', False):
    kv['primary_key_value'] = line.split(kv['key']).strip() 
#    kv['primary_key'] = False   
   kv['times'] -= 1   ##匹配成功,同理剩余匹配的次数 -1
 return primary_key  
 
def format_info(sum_list):
 tip_list = [] 
 p_k_dict = {}
 for d in sum_list:
  p_k = d['primary_key_value']
  if p_k not in p_k_dict:
   p_k_dict[p_k] = [0] * len(key_words)
  temp_list = []
  m = d['match_result']
  temp_list.append("文件名称:%s\n%s:%s\n" % (d['file_path'], d['primary_key'], d['primary_key_value']))
  for i in range(len(m)):
   if 'primary_key' in key_words[i]:    
    continue
   else:
    t_s = str(m[i])
   temp_list.append("%s:%s\n" % (key_words[i]["display"], t_s))
   p_k_dict[p_k][i] += m[i]
  tip_list.append("".join(temp_list))
  p_k_dict[p_k][0] += 1
 tip_list.append("===========================主键统计分割线===============================")
 total_dict = {}
 for kv in key_words:
  if 'primary_key' not in kv:
   total_dict[kv['display']] = 0
 total_dict['全部文件数'] = 0
 for k,v in p_k_dict.items():
  temp_list = []
  temp_list.append("主键:%s\n文件总数:%s\n" % (k, v[0]))
  for i in range(1, len(v)):
   temp_list.append("%s:%s\n" % (key_words[i]["display"], str(v[i])))
   total_dict[key_words[i]["display"]] += v[i]  
  tip_list.append("".join(temp_list))
  total_dict['全部文件数'] += v[0]
 tip_list.append("===========================全部统计分割线===============================")
 temp_list = []
 for k,v in total_dict.items():
  temp_list.append("全部%s:%s\n" % (k,v))
 tip_list.append("".join(temp_list))
 tip_msg = "\n".join(tip_list)
 print tip_msg
 open(r"sum_case.log", "w").write(tip_msg)
 
if __name__=="__main__":
 if len(sys.argv) > 1:
  root_list = sys.argv[1:]
 else:
  root_list = [os.curdir]
 sum_list = []
 for root_dir in root_list: 
  if os.path.exists(root_dir) and os.path.isdir(root_dir):
   sum_list.extend(loop_case(root_dir))
   format_info(sum_list)
  else:
   print "给定的根目录无效\n%s" % root_dir
可以通过配置开头的设置来确定检查什么关键字,文件类型,过滤哪些文件和目录等

上一页    

怎么样通过编写Python小程序来统计测试脚本的关键字的更多相关文章

  1. 编写 python 小程序,将LOL官网的皮肤保存下来,上传百度云,记录那些强撸灰飞烟灭的日子

    to 撸的血泪史:大学四年几乎都在宿舍打撸,So,把官网的皮肤都保存下来,存到百度云,就当一种纪念 编辑器:pycharm 用到的包:urllib.request, requests, json, r ...

  2. 基于php基础语言编写的小程序之计算器

    基于php基础语言编写的小程序之计算器 需求:在输入框中输入数字进行加.减.乘.除运算(html+php) 思路: 1首先要创建输入数字和运算符的输入框,数字用input的text属性,运算符用sel ...

  3. Python 小程序,对文件操作及其它

    以下是自己写的几个对文件操作的小程序,里面涉及到文件操作,列表(集合,字典)的运用等.比方说,从文件里读取一行数据.分别存放于列表中,再对列表进行操作.如去掉里面的反复项.排序等操作. 常见对文件里行 ...

  4. Day1:第一个python小程序

    Day1:第一个python小程序与开发工具Pycharm 一.Hello World C:\Users\wenxh>python Python 3.6.2 (v3.6.2:5fd33b5, J ...

  5. Python获取程序运行目录和脚本目录

    Python获取程序运行目录和脚本目录 import os import sys #获取脚本所在目录 print os.path.split( os.path.realpath( sys.argv[0 ...

  6. 利用Python代码编写计算器小程序

    import tkinter import tkinter.messagebox import math class JSQ: def __init__(self): #创建主界面 self.root ...

  7. Python编写购物小程序

    购物车要求: 用户名和密码存放于文件中 启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序 允许用户根据商品编号购买商品 用户选择商品后,检测余额是否够 ...

  8. 一个有意思的Python小程序(全国省会名称随机出题)

    本文为作者原创,转载请注明出处(http://www.cnblogs.com/mar-q/)by 负赑屃 最近比较迷Python,仿照<Python编程快速上手>8.5写了一个随机出卷的小 ...

  9. 高效编写微信小程序

    原文:https://isux.tencent.com/high-performance-wechat-app-development.html 前言 微信小程序是一个工程,就和盖房子一样,打好了地基 ...

随机推荐

  1. Multiple Instance Learning

    ///////////////////////////////////////////推荐学习组////////////////////////////// http://www.robots.ox. ...

  2. js浏览器缩放提示

    data() { return { instance: null, isZoomOpen: false }; }, mounted() { const that = this; this.isZoom ...

  3. [洛谷P5216]DLS 采花

    题目大意:有$n$个数,任意排列,排列后第$i$个数会产生贡献当且仅当$1\sim i-1$中的数不是它的因子,问所有排列的贡献和 题解:发现一个数要产生贡献要求所有它的因子在它的右边,设有$cnt_ ...

  4. BZOJ 3230 相似子串 | 后缀数组 二分 ST表

    BZOJ 3230 相似子串 题面 题解 首先我们要知道询问的两个子串的位置. 先正常跑一遍后缀数组并求出height数组. 对于每一个后缀suffix(i),考虑以i开头的子串有多少是之前没有出现过 ...

  5. 【Learning】插头DP

    简介 插头DP(轮廓线DP)是用来解决网格图回路问题的一种算法. 插头DP解决的经典问题就是统计经过所有格子的哈密顿回路条数,某些格子有障碍. ​ 如果问题稍微进阶一点的话,不一定要求路径是回路.路径 ...

  6. laravel mapSpread 例子

    $collection = collect(range(1, 9)); $chunks = $collection->chunk(2); $labeld = $chunks->mapSpr ...

  7. Java入门:基础算法之检查素数

    程序提示用户输入一个数,然后检查所输入的数是否是素数. import java.util.Scanner; class PrimeCheck { public static void main(Str ...

  8. P2042 [NOI2005]维护数列 && Splay区间操作(四)

    到这里 \(A\) 了这题, \(Splay\) 就能算入好门了吧. 今天是个特殊的日子, \(NOI\) 出成绩, 大佬 \(Cu\) 不敢相信这一切这么快, 一下子机房就只剩我和 \(zrs\) ...

  9. UITableViewCell的separatorInset属性

    separatorInset这个属性是IOS7后才有的属性,所以需要判断一下,才能修改 if (IOS7_OR_LATER) { cell.separatorInset = UIEdgeInsetsZ ...

  10. HDU 4857 拓扑排序 优先队列

    n个数,已经有大小关系,现给m个约束,规定a在b之前,剩下的数要尽可能往前移.输出序列 大小关系显然使用拓扑结构,关键在于n个数本身就有大小关系,那么考虑反向建图,优先选择值最大的入度为零的点,这样得 ...