1. 安装Python和相关库

首先需要安装Python和相关的库,建议使用最新版本的Python 3.x。安装完成后,需要安装一些必要的库,例如selenium、pytest、requests等。

可以使用pip安装这些库,打开命令行窗口,输入以下命令:

pip install selenium pytest requests
  1. 编写测试用例

编写测试用例需要使用pytest库,创建一个test文件夹,在该文件夹中创建test_example.py文件,编写测试用例代码。

例如:

import pytest
from selenium import webdriver

@pytest.fixture(scope='session')
def browser():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

def test_search(browser):
    browser.get('https://www.baidu.com')
    browser.find_element_by_id('kw').send_keys('python')
    browser.find_element_by_id('su').click()
    assert 'python' in browser.title
  1. 编写配置文件

创建一个config文件夹,在该文件夹中创建config.py文件,编写配置信息。

例如:

class Config:
    BROWSER = 'Chrome'
    BASE_URL = 'https://www.baidu.com'
  1. 编写测试框架

创建一个framework文件夹,在该文件夹中创建base_page.py文件,编写测试框架。

例如:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.remote.webdriver import WebDriver


class BasePage:

    def __init__(self, driver: WebDriver):
        self.driver = driver

    def find_element(self, locator, timeout=10):
        return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator))

    def find_elements(self, locator, timeout=10):
        return WebDriverWait(self.driver, timeout).until(EC.presence_of_all_elements_located(locator))

    def click(self, locator):
        self.find_element(locator).click()

    def input(self, locator, text):
        ele = self.find_element(locator)
        ele.clear()
        ele.send_keys(text)

    def move_to_element(self, locator):
        ele = self.find_element(locator)
        ActionChains(self.driver).move_to_element(ele).perform()
  1. 运行测试用例

在命令行窗口中进入test文件夹,输入以下命令运行测试用例:

pytest test_example.py

运行结果会显示测试用例是否通过。

以上就是用Python搭建软件测试自动化框架的步骤。可以根据需要,继续完善框架,例如添加日志、报告、数据驱动等功能。

用python搭建软件测试自动化框架

原文地址: https://www.cveoy.top/t/topic/bESN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录