自动化测试(二)Python内置csv模块及项目框架构建

CSV文件 

import csv
#读取csv第一种方式
# csvfile=open('data.csv','r')
# # reader=csv.reader(csvfile)
# # print(reader)
# # data=[]
# # for row in reader:
# #     print(row)
# #     data.append(row)
# # print(data)
# # print(data[0][1])

#读取csv第二种方式
# data=[]
# with open('data.csv','r') as csvfile:
#     reader=csv.reader(csvfile)
#     for row in reader:
#         print(row)
#         data.append(row)

# data=[['test1', '123456'], ['test2', '123457'], ['test3', '123458'], ['test4', '123459']]
# # csvfile=open('data.csv','w') #csv写入文件,默认会加换行
# csvfile=open('data.csv','w',newline='')# 加 newline='' 取消换行
# writer=csv.writer(csvfile)
# for i in range(len(data)):
#     writer.writerow(data[i])


#字典写入
# dic={'zhangsan':123456,'lisi':'222222','wangwu':'3333'}
# csvfile=open('data.csv','w',newline='')
# writer=csv.writer(csvfile)
# for key in dic:
#     writer.writerow([key,dic[key]])

构建项目文档结构

新建项目并选择解释器

新建包并非文件夹

cases/data 测试用例 CSV文件

public/common 公共方法

config 配置相关

log 日志

pages 页面元素定位相关

repor 报告

screenshot 截图

 

 

config.ini文件

[browser]
browserName=firefox
host=http://106.13.46.164:8080

[login_info]
loginname=zhang
loginpwd=111111

 readConfig的公共方法

import configparser
import os

def readConfig(tagname,name,logger):
	try:
		cf=configparser.ConfigParser()
		cfpath=os.path.dirname(os.path.abspath('.'))+"\\config\\config.ini"
		cf.read(cfpath)
		res_name=cf.get(tagname,name)
		return res_name
	except:
		logger.error("读取配置文件出错,tagname为 %s,name 为 %s" % (tagname,name))

if __name__ == "__main__":
	from common.logging_method import LoggingMethod
	logger=LoggingMethod().getlogger()
	name=readConfig("login_info","loginpwd",logger)
	print(name)

拼接URL和HOST的公共方法 

from common.readConfig import readConfig

def getUrl(url,logger):
	configUrl = readConfig("browser", "host", logger)
	url=configUrl+url
	return url

if __name__ == "__main__":
	from common.logging_method import LoggingMethod
	logger = LoggingMethod().getlogger()
	url = '/iwebshop/index.php?controller=site&action=pro_list&cat=157'
	print(getUrl(url,logger))

识别浏览器的公共方法

from selenium import webdriver
from common.readConfig import readConfig

class BrowserSetup():
	def __init__(self,logger):
		self.logger=logger
		self.browserName = readConfig("browser", "browserName", logger)
		self.browserName=self.browserName.lower()

	def browserSetup(self):
		if self.browserName=='chrome':
			return webdriver.Chrome()
		elif self.browserName=='firefox':
			return webdriver.Firefox()
		elif self.browserName=='ie':
			return webdriver.Ie()
		else:
			self.logger.error("浏览器名称有误 %s" %self.browserName)

if __name__ == "__main__":
	from common.logging_method import LoggingMethod
	logger = LoggingMethod().getlogger()
	browser=BrowserSetup(logger)
	browser.browserSetup()

时间的公共方法

import time

class TimeUtil():
	def currentDate(self):
		today=time.strftime('%Y-%m-%d') #格式为:2019-03-02
		return today

	def currentTime(self):
		now=time.strftime('%H_%M_%S') #格式为: 21_03_11
		return now

	def fullTime(self):
		day_time=time.strftime('%Y-%m-%d_%H_%M_%S') #格式为:2019-03-02_21_03_11
		return day_time

if __name__ == "__main__":
	times=TimeUtil()
	print(times.currentDate())
	print(times.currentTime())
	print(times.fullTime())

截图的公共方法

from common.timeUtil import TimeUtil
import os

def screenShot(driver):
	scrTime=TimeUtil().fullTime()
	scrName=os.path.dirname(os.path.abspath('.'))+'\\screenshot\\'+scrTime+'.png'
	driver.get_screenshot_as_file(scrName)

if __name__ == "__main__":
	from selenium import webdriver
	driver=webdriver.Chrome()
	screenShot(driver)

日志的公共方法

import logging
import time
import os
from common.timeUtil import TimeUtil

# 同一天的所有日志输入到同一个log文件
class LoggingMethod():
	def getlogger(self):
		# 设置存储日志的文件名
		now =TimeUtil().currentDate()
		filename = os.path.dirname(os.path.abspath('.')) + '\\log\\' + now + '.log'
		# err_filename=os.path.dirname(os.path.abspath('.')) + '\\log\\' + now+'-error' + '-' + '.log'

		# 第一步,创建一个logger
		logger = logging.getLogger()#实例化logger对象
		logger.setLevel(logging.DEBUG)  # Log等级总开关

		# 第二步
		# 1)创建一个handler,用于写入所有日志
		fh1 = logging.FileHandler(filename,encoding='utf-8')
		fh1.setLevel(logging.DEBUG)  # 输出到file的log等级的开关

		# 2)创建一个handler,用于写入错误日志
		# fh2 = logging.FileHandler(err_filename,encoding='utf-8')
		# fh2.setLevel(logging.WARNING)  # 输出到file的log等级的开关

		# 3)创建控制台输出
		consoleh=logging.StreamHandler()
		consoleh.setLevel(logging.WARNING)

		# 第三步,定义handler的输出格式
		formatter = logging.Formatter('%(asctime)s - %(levelname)s -%(pathname)s-%(lineno)d'+'行'+'- %(message)s')
		fh1.setFormatter(formatter)
		# fh2.setFormatter(formatter)
		consoleh.setFormatter(formatter)
		# 第四步,将handlers 添加到 logger
		logger.addHandler(fh1)
		# logger.addHandler(fh2)
		logger.addHandler(consoleh)

		return logger

if __name__=='__main__':
	logger = LoggingMethod().getlogger()
	logger.info('测试info日志')
	logger.error('error')

用例执行文件

import unittest
from selenium import webdriver
from common.excelUtil import ExcelMethod
from time import sleep
import os
from common.logging_method import LoggingMethod
class Excele_Test(unittest.TestCase):
	@classmethod
	def setUpClass(cls):
		cls.logger = LoggingMethod().getlogger()
		cls.data_path = os.path.dirname(os.path.abspath('.')) + '\\data' + '\\test.xlsx'
		cls.excelmethod = ExcelMethod(cls.logger, cls.data_path, "Sheet1")
		cls.user_list=cls.excelmethod.readExcel()

		cls.driver = webdriver.Chrome()
		cls.driver.get('https://www.baidu.com')

	def test_search(self):
		for i in range(0,len(self.user_list)):
			searchbox=self.driver.find_element_by_id('kw')
			searchbox.clear()
			searchbox.send_keys(self.user_list[i][1])
			sleep(1)
			self.driver.find_element_by_id('su').click()
			sleep(1)
			if self.user_list[i][2] in self.driver.page_source :
				self.excelmethod.saveExcel(i + 2, 'pass')
			else:
				self.excelmethod.saveExcel(i + 2, 'fail')
				self.logger.error(u'第 %s 行用例执行失败' % (i + 1))

	@classmethod
	def tearDownClass(cls):
		cls.driver.quit()

if __name__ == "__main__":
	unittest.main()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值