Selenium automated test data driven

Table of contents

1. Data preparation

2. Data splitting

 3. Automate

3.1 Import library

 3.2 Open the browser method, the method is the method that comes with unittest

 3.3 Closing the browser is also a built-in method

 3.4 Import test data

3.5 Run the test class

3.5 Complete code of the test script


1. Data preparation

Testdata.csv

search for the keyword
news
Douluo mainland
Bilibili

2. Data splitting

import csv

def testdata():
    # 打开CSV文件
    with open("testdata.csv", encoding="utf-8") as open_csv:
        # 创建CSV读取器对象
        split_csv = csv.reader(open_csv)
        # 跳过第一行标题行
        next(split_csv)
        # 读取剩余行并存储在data列表中
        data = [row for row in split_csv]
    
    return data

# 调用测试函数并打印结果
print(testdata())

operation result

 3. Automate

3.1 Import library

import time
from cs4.data import testdata
from selenium import webdriver
from selenium.webdriver.common.by import By
import unittest
from ddt import ddt, data

 3.2 Open the browser method, the method is the method that comes with unittest

    def setUp(self) -> None:
        self.driver = webdriver.Chrome()

 3.3 Closing the browser is also a built-in method

    def tearDown(self) -> None:
        self.driver.quit()

 3.4 Import test data

    #数据实例化
    aa=Adata()
    ss=aa.data()
    #遍历数据
    @data(*ss)

3.5 Run the test class

    #测试方法名称必须以test开头,否则无法运行
    def test_login(self, list):
        self.driver.get('https://www.baidu.com/')
        self.driver.find_element(By.NAME, 'wd').send_keys(list[0])
        self.driver.find_element(By.ID, 'su').click()
        time.sleep(3)

3.5 Complete code of the test script

import time
from cs4.data import testdata
from selenium import webdriver
from selenium.webdriver.common.by import By
import unittest
from ddt import ddt, data


@ddt
class Ada(unittest.TestCase):
    def setUp(self) -> None:
        # 在每个测试方法执行之前设置
        self.driver = webdriver.Chrome()

    def tearDown(self) -> None:
        # 在每个测试方法执行之后清理
        self.driver.quit()

    # 实例化testdata并获取测试数据
    aa = Adata()
    ss = aa.data()

    # 使用@data装饰器将测试数据传入测试方法
    @data(*ss)
    def test_login(self, list):
        # 打开百度网页
        self.driver.get('https://www.baidu.com/')
        # 在搜索框中输入关键词
        self.driver.find_element(By.NAME, 'wd').send_keys(list[0])
        # 点击搜索按钮
        self.driver.find_element(By.ID, 'su').click()
        # 等待3秒
        time.sleep(3)

Guess you like

Origin blog.csdn.net/weixin_62854251/article/details/130092140