You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python+Selenium+Pytest执行自动化脚本时遇0用例收集问题

解决Pytest未收集到测试用例的问题

核心原因:测试文件存在语法错误 + 未遵循Pytest识别规范

1. 修复test_login.py的语法错误

你的test_login.py存在明显的语法混乱,直接导致Pytest无法解析文件,因此收集不到测试用例:

错误代码片段:

import pytest
from selenium import webdriver
from p    username = "shubhamgupta191190@gmail.com"ages.login import Loginchatbot

class test001_login:
baseurl = "https://teacher-learning-test.ef.com/"

    password = "freeBugs!"
    
    def test_login1(self,setup):
        # ... 方法内容

修复后代码:

import pytest
from selenium import webdriver
from pages.login import Loginchatbot  # 修正import路径,移除错位的变量定义

class Test001Login:  # 类名改为大写Test开头,符合Pytest规范
    baseurl = "https://teacher-learning-test.ef.com/"
    username = "shubhamgupta191190@gmail.com"  # 将变量移到类内正确位置,对齐缩进
    password = "freeBugs!"  # 修正缩进
    
    def test_login1(self, setup):
        self.driver = setup
        self.driver.get(self.baseurl)
        self.lp = Loginchatbot(self.driver)
        self.lp.set_username(self.username)
        self.lp.set_password(self.password)
        self.lp.clicklogin()

2. 严格遵循Pytest测试识别规则

Pytest默认仅收集符合以下规则的测试用例:

  • 测试文件名以test_开头(你的test_login.py符合要求)
  • 测试类以**大写Test**开头,且类中不能包含__init__方法(原类名test001_login为小写t,不符合规范)
  • 测试方法以test_开头(你的test_login1符合要求)

3. 潜在运行时问题提前修复(避免后续报错)

虽然不影响用例收集,但修复后运行测试可能会报错,建议提前处理:

  • Loginchatbot类中使用self.wait.driver但未初始化等待对象,需在__init__中添加显式等待:
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    class Loginchatbot():
        username_xpath = '//input[@id="username"]'
        password_xpath = '//input[@id="password"]'
        login_xpath = '//span[contains(text(),"Log in")]'
    
        def __init__(self,driver):
            self.driver = driver
            self.wait = WebDriverWait(driver, 10)  # 初始化显式等待,超时时间10秒
    
  • 元素操作链式调用错误:click().send_keys()无效,因为click()无返回值,需拆分操作:
    def set_username(self,username):
        ele = self.wait.until(EC.visibility_of_element_located((By.XPATH, self.username_xpath)))
        ele.clear()
        ele.send_keys(username)
    

内容的提问来源于stack exchange,提问作者kulpreet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:05:15