用python写自动化测试脚本常用功能:结果记录,运行日志,测试配置,带颜色打印在控制台

用python写自动化测试脚本常用功能:结果记录,运行日志,测试配置,带颜色打印在控制台

    • 利用csv库来记录测试结果
    • 利用logging库来记录脚本运行信息
    • 利用ConfigParser库来读取测试配置信息
    • 利用ctypes库将测试信息带颜色打印在控制台
    • 总结

利用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

你可能感兴趣的:(脚本,测试)