Selenium+pytest+allure踩过的坑

一、多进程运行报错

虽然pytest能设置并发,貌似不能对一次运行中的不同用例设置不同的并发数,所以加入了多进程。这里使用了继承式调用:

from selenium import webdriver
from multiprocessing import Process
import time
import random

class Rundriver(Process):
    def __init__(self, url='https://www.baidu.com'):
        super().__init__()
        self.url = url
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(20)

    def run(self):#该方法名固定
        self.driver.get(self.url)
        self.driver.maximize_window()
        time.sleep(random.randrange(5,8))
        self.driver.quit()


if __name__ == '__main__':
    p1 = Rundriver()
    p2 = Rundriver('https://weibo.com/')
    p1.start() #start会自动调用run()
    p2.start()
    while p1.is_alive() | p2.is_alive():
        time.sleep(1)
    print('运行完毕')

运行报错:

AttributeError: Can't pickle local object '_createenviron.<locals>.encodekey'

原代码:

from multiprocessing import Process

解决方法:

from multiprocessing.dummy import Process

二、Json格式参数传值接口返回400

接口调用返回状态码400,正常应该返回布尔值。

import requests
import json

url = r"http://192.168.1.15:10001/……/……/……"
payload = {"LaneNo":"E2.3"}
data_json = json.dumps(payload, indent=4)
response = requests.post(url=url,  json=data_json)
print(response.text)

实际返回:

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|8b3324c4-4bda8d6ce91f0941.","errors":{"$":["The JSON value could not be converted to IotItemService.Models.SimulationCarLeaveItem. Path: $ | LineNumber: 0 | BytePositionInLine: 24."]}}

原代码:

data_json = json.dumps(payload, indent=4)
response = requests.post(url=url, json=data_json)

解决办法:

response = requests.post(url=url, json=payload)

三、模块间导入文件报错提示找不着

报错:

ModuleNotFoundError: No module named 'login_submit'

解决办法:
将该文件的上级目录添加至python搜索模块的路径集,这里将以下代码写入与login_submit同级的初始化文件(init.py)中。
注意:如果login_submit在项目根目录下,此时没有与login_submit同级的初始化文件,则不能使用该方法。如果在项目根目录新建一个初始化文件则可能导致打包的时候报参数错误。

import os,sys

dirname = os.path.dirname(os.path.abspath(__file__))  # 获取当前文件所在目录
sys.path.append(dirname)  # 将目录dirname添加至python搜索模块的路径集,只在运行时修改,运行结束后失效

四、数据库查询不到结果

获取提交结论的任务的ID连接数据库查询结果为空,但是执行传ID值的语句发现查询结果与自己从库里查的相同。

c = Getresult()
result = c.getresult(PlateNo=PlateNo)
print(result)

打印出查询语句发现参数前后多了空格:

select image_check_result from XX.tasks where plate_no=' LPN0055 ';

解决办法:
去掉所传参数两侧的空格

PlateNo = PlateNo.strip()  # 去掉PlateNo两侧的空格
# 查询场内车辆
cursor.execute('select image_check_result from XX.tasks where plate_no=%r;' % PlateNo)

五、Allure报告总览只记录最后一遍的运行结果(未解决)

在一定时间范围内重复运行,或者运行多次后生成allure报告,allure总览只统计了运行一遍的结果,实际运行了多遍。
网上有人说:“同一个测试环境的多个执行节点执行同一个用例,测试结果以最后一次执行结果为准,会覆盖掉之前所有别的节点的执行结果,一份测试报告中同一个测试用例的执行结果必须唯一。这是分布式测试的设计机制。”
这里采取设定在一定时间范围内运行的方式,但是最后一遍之前执行的具体信息只能通过时间刻度查看。

六、定位不到元素(1)

同样的代码,环境不同,有的能执行,有的提示元素不能点击。
报错:

selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <button onclick="addinput()">...</button> is not clickable at point (826, 315). Other element would receive the click: <div style="">...</div>

原代码:

button = self.d.driver.find_element_by_xpath('//button[contains(@onclick,"addinput")]')
button.click()

解决办法:

button = self.d.driver.find_element_by_xpath('//button[contains(@onclick,"addinput")]')
self.d.driver.execute_script("arguments[0].click();", button)

七、定位不到元素(2)

报错:

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable: element has zero size

解决办法:方法同六、定位不到元素(1)

Python结合SeleniumpytestAllure可以创建强大的Web端自动化测试流程。以下是这个组合的工作方式: 1. **Selenium**[^1]: 是一个用于Web应用程序自动化测试的开源库,它允许你模拟用户在浏览器上的交互,如点击按钮、填写表单等。通过Selenium,你可以编写Python脚本来控制浏览器的行为。 2. **pytest**: 是一个流行的测试框架,以其简洁的语法和丰富的插件生态系统著称。它能更方便地编写测试用例,比如断言、参数化测试等。 3. **Allure**[^2]: 是一个报告工具,用于生成详细的测试报告,包括测试执行过程的可视化图表和详细的测试结果描述。这有助于团队更好地理解和跟踪测试状态。 4. **Jenkins**: 是一个持续集成/持续部署(CI/CD)服务器,它可以集成pytestAllure,自动运行测试并生成报告,从而实现自动化测试的持续执行。 具体操作流程如下: 1. 安装必要的库(如Selenium WebDriver、pytestpytest-seleniumallure-pytest等)。 2. 使用pytest编写测试用例,比如: ```python def test_login(self, driver): driver.get("http://example.com/login") username_input = driver.find_element_by_name("username") username_input.send_keys("test_user") password_input = driver.find_element_by_name("password") password_input.send_keys("test_password") password_input.submit() ``` 3. 使用pytest-selenium标记测试为Selenium测试: ```python import pytest_selenium @pytest.mark.selenium def test_login_with_selenium(driver): ... ``` 4. 在pytest配置中设置Allure插件: ```python pytest_plugins = ["allure_pytest"] ``` 5. 在Jenkins中配置一个job,连接到Allure服务器,每次构建后自动上传测试报告。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值