如何使用文件进行数据驱动?
1、使用yaml
2、使用json
3、使用csv
- test_data.yaml
- selenium
- python
- DDT
- test_data_interface.yaml
可用于接口json格式数据
- {"name":"linda","age":18}
- {"name":"sophoe","age":88}
- test_data.json
{"name":"linda","age": 18}
- test_data1.json
可用于接口json格式数据
{
"data": {
"name": "linda",
"age": 18
},
"data2": {
"name": "jenkins",
"age": 88
}
}
代码
from ddt import ddt,file_data
import unittest
'''
实现DDT的步骤:
1、在测试类上使用@ddt装饰符
2、在测试方法上使用@file_data装饰符
3、@file_data
4、将传入的列表解析(折包)使用@unpack
'''
@ddt
class TestDdtFile(unittest.TestCase):
@unittest.skip
@file_data('test_data.yml')
def test_yaml(self, value):
print(value)
# json----dict --**
@unittest.skip
@file_data('test_data_interface.yaml')
def test_yaml_interface(self, **value):
print(value)
print(type(value))
@file_data('test_data.json')
def test_json(self, value):
print(value)
@unittest.skip
@file_data('test_data1.json')
def test_json_com(self, **value):
print(value)
if __name__ == '__main__':
unittest.main()
- test_data.csv
Username,Password
admin,123456.
linda,123456.
代码
import csv
import unittest
from ddt import ddt,data
def get_csv_data(file_name):
rows=[]
with open("test_data.csv",'r') as f:
reader = csv.reader(f)
# 跳过第 一行
next(reader,None)
for row in reader:
rows.append(row)
return rows
@ddt
class TestDdtCsv(unittest.TestCase):
@data(*get_csv_data("test_data.csv"))
def test_get_data(self,value):
username = value[0]
password = value[1]
print('登陆的用户名:%s'% username, '密码是%s' % password)
if __name__ == '__main__':
unittest.main()
实践 :对用户名和密码进行数据驱动,完成不同用户登陆的自动化
# 建立csv文件--excel表建立完成导出成csv格式 ,utf-8 ,记事本另存为csv
# 读取csv每一个数据
# 在通过ddt方式 实现数据驱动
import csv
import unittest
from ddt import ddt,data
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
def get_csvdata(file_name):
rows=[]
with open(file_name,'r') as f:
reader1 = csv.reader(f)
# 跳过第一行
next(reader1, None)
for row in reader1:
rows.append(row)
print(rows)
return rows
@ddt
class TestDdtCsv(unittest.TestCase):
@classmethod
def setUpClass(cls):
path = '/Users/lindafang/PycharmProjects/selenium3forpython2020/driver/chromedriver'
cls.driver = webdriver.Chrome(executable_path=path)
cls.driver.maximize_window()
cls.driver.get("http://172.16.166.129:81/zentao/user-login.html")
@classmethod
def tearDownClass(cls):
# pass
cls.driver.close()
cls.driver.quit()
@data(*get_csvdata("test_data.csv"))
def test_csv_getdata(self,value):
username=value[0]
password=value[1]
print("用户名是%s" % username,"密码是%s" % password)
self.driver.find_element_by_id("account").send_keys(username)
self.driver.find_element(By.NAME, 'password').send_keys(password)
self.driver.find_element_by_id("submit").click()
time.sleep(3)
self.driver.find_element_by_class_name("dropdown-toggle").click()
self.driver.find_element_by_link_text("退出").click()
if __name__ == '__main__':
unittest.main()
网友评论