用python写自动化测试脚本常用功能:结果记录,运行日志,测试配置,带颜色打印在控制台
2018-10-27 13:02
447 查看
用python写自动化测试脚本常用功能:结果记录,运行日志,测试配置,带颜色打印在控制台
利用csv库来记录测试结果
在进行自动化测试时,我们需要记录测试运行结果,将结果存入文件进行自动化测试结果报告; python csv库完全能满足这个功能,下面直接看code:
#生成测试结果 import csv class Report_test: def __init__(self): self.setting = Config() #生成的csv文件: ..\Report_20181025101010.csv self.fname = "..\\Report_"+str(time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())))+".csv" #将测试结果写入csv文件 def writer_data(self,data_log): with open(self.fname,'ab') as csvfile: csvwriter = csv.writer(csvfile,delimiter=',',lineterminator='\r\n') csvwriter.writerow(data_log) #读取csv文件 def read(self): with open(self.fname, 'r+') as csv_file: reader = csv.reader(csv_file) ''' reader_list=[] for i in reader: reader_list.append(i) return reader_list ''' return [row for row in reader] #写入测试结果并将信息打印在控制台 def now_data(self,data_log): Report_test.writer_data(self,data_log) print Report_test.read(self)[len(Report_test.read(self))-1] # ===== test ===== rep=Report_test() rep.now_data(["pass"]) rep.writer_data(["333","3333","33333","3333"]) print rep.read()[len(rep.read())-1]
利用logging库来记录脚本运行信息
在自动化脚本运行时,我们需要了解当前脚本运行的状态, 需要了解脚本运行的所有信息来帮助我们进一步的优化和调试脚本; python logging库完全能满足这个功能,下面直接看code:
#生成测试结果 class AddLog: setting = Config() logger=logging.getLogger() log_path= 'c:\\'#setting.log_path() #False log内容不会再控制台显示 #True log内容会在控制台显示 def __init__(self,input=True): try: date=str(time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))) logname=AddLog.log_path+"\\"+date+".log" logging.basicConfig(filename=logname, level=logging.DEBUG , format='%(asctime)s %(levelname)s :$ %(message)s', datefmt='[ %Y-%m-%d %H:%M:%S ]', filemode='w', encoding='utf-8') if input == True: console=logging.StreamHandler() console.setLevel(logging.DEBUG) formatter=logging.Formatter(" %(asctime)s %(levelname)s : %(message)s ","[ %Y-%m-%d %H:%M:%S ]") console.setFormatter(formatter) AddLog.logger.addHandler(console) elif input == False: print "Not show logs." else: print "The parameter is wrong, only False and True." except: import os os.makedirs(AddLog.log_path) def log(self): return AddLog.logger # ===== test ===== logger=AddLog(True).log() logger.info("aaaaaaaaaa")
利用ConfigParser库来读取测试配置信息
自动化测试脚本常常会用到外部配置参数来健壮脚本的重复利用。 python ConfigParser库完全能满足这个功能,下面直接看code:
#读取配置文件 class Config(): def __init__(self): self.setting_path="C:\\Users\\utility\\settings.ini" def get_config(self, sector, item): config = ConfigParser.ConfigParser() config.read(self.setting_path) value = config.get(sector, item) return value def get_dir_path(self): res = self.get_config('Path', 'dir_path') return res.replace("\\", "\\\\") def agent_path(self): res = self.get_config('Path', 'agent_path') return res.replace("\\", "\\\\") def client_path(self): res = self.get_config('Path', 'client_path') return res.replace("\\", "\\\\") def call_number(self): res = self.get_config('Test_cfg', 'call_number') return res def log_path(self): res = self.get_config('Settings', 'log_path') return res def report_path(self): res = self.get_config('Settings','report_path') return res # ===== test ===== test_init = Config() log_path = test_init.log_path()
settings.ini
[Path] dir_path = C:\Users\ agent_path = C:\Users\ client_path = C:\Users\ [Test_cfg] call_number = 10086 [Settings] log_path = C:\Users\ report_path = C:\Users\
利用ctypes库将测试信息带颜色打印在控制台
有时候我们需要更直观看到当前测试状态,测试结果Passed 将以绿色显示在控制台,测试结果failed以红色显示在控制台; python ctypes库完全能满足这个功能,下面直接看code:
#生成测试结果 class Out_color: FOREGROUND_WHITE = 0x0007 FOREGROUND_BLUE = 0x01 | 0x08# text color contains blue. FOREGROUND_GREEN= 0x02 | 0x08 # text color contains green. FOREGROUND_RED = 0x04 | 0x08 # text color contains red. FOREGROUND_YELLOW = FOREGROUND_RED | FOREGROUND_GREEN STD_OUTPUT_HANDLE= -11 std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) def __init__(self): pass #@ set color in computer terminal. def set_color(self, color, handle=std_out_handle): bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color) return bool # Failed or Error messge is text color contains red. def messge_error(self, str): self.set_color(Out_color.FOREGROUND_RED) print str logger.info(str) self.set_color(Out_color.FOREGROUND_WHITE) # Passed messge is text color contains green. def messge_pass(self, str): self.set_color(Out_color.FOREGROUND_GREEN) print str logger.info(str) self.set_color(Out_color.FOREGROUND_WHITE) # Title messge is text color contains blue. def title(self, str): self.set_color(Out_color.FOREGROUND_BLUE) print str logger.info(str) self.set_color(Out_color.FOREGROUND_WHITE) # ===== test ===== output=Out_color() output.messge_pass("Passed") output.messge_fail("Failed")
总结
使用以上功能可以提高测试脚本的健壮性;
版权声明:本文出自Man_ge博客原创文章,转载必须注明出处:https://blog.csdn.net/Man_ge/article/details/83445358
作者:Man_ge https://blog.csdn.net/Man_ge
阅读更多相关文章推荐
- 运行测试用例集过程中在jenkins控制台打印当前用例测试结果(testng)
- Python+Selenium进行UI自动化测试项目中,常用的小技巧4:日志打印,longging模块(控制台和文件同时输出)
- 测试博客园日志运行脚本
- 解析百度搜索结果页面的python脚本(Linux/Win都可以运行)
- Python 数据库备份脚本(邮件通知+日志记录)
- 运行QTP测试脚本后,将编译结果写入指定文件(二)
- loadrunner创建测试脚本运行无响应 不记录脚本
- 树莓派把一个python脚本作为服务运行,配置开机自动启动
- python loggin记录日志,traceback打印stack
- [Python]基于Splinter的自动化回归/测试脚本
- Badboy自动化测试工具4 运行脚本
- selenium+python关于登录的脚本代码,使用了读取excel以及向excel中写入测试结果的方法
- 配置Apache2.x 支持shell脚本和Python编写CGI程序+测试程序
- 把Tomcat控制台的运行日志打印到log文件中
- 基于Selenium2与Python的自动化测试环境配置搭建
- Appium环境的安装与配置,Python测试脚本测试
- python _自动化性能测试脚本
- 用Python开发自动化测试脚本
- 用Python开发自动化测试脚本