Pytest - 没有运行任何测试

26

我正在使用pytest和selenium。当我尝试运行我的测试脚本时:

import pytest
from selenium import webdriver
from pages import *
from locators import *
from selenium.webdriver.common.by import By
import time

class RegisterNewInstructor:
    def setup_class(cls):
        cls.driver = webdriver.Firefox()
        cls.driver.get("http://mytest.com")

    def test_01_clickBecomeTopButtom(self):
        page = HomePage(self.driver)
        page.click_become_top_button()
        self.assertTrue(page.check_instructor_form_page_loaded())


    def teardown_class(cls):
        cls.driver.close()

显示的信息为:0.84秒内没有运行测试

有人可以帮我运行这个简单的测试吗?

7个回答

31
根据pytest测试约定,你的类应该以Test开头,这样才能被测试发现机制自动识别。改成TestRegisterNewInstructor吧。
或者,继承unittest.TestCase类:
import unittest

class RegisterNewInstructor(unittest.TestCase):
    # ...

请记住,.py测试脚本本身的文件名必须以test_开头或以_test结尾。

1
我不确定为什么这个答案会有赞和被接受。OP的帖子是关于pytest库,而不是unittest。也许我错了。它们在底层下面是否相关?@alecxe @AlSweigart @RafaelC. - StressedBoi69420
Pytest 还将包括类的方法以测试它们是否继承了 unittest.TestCase。我认为这是为了使其具有跨兼容性,方便从一个框架迁移到另一个框架。 - Al Sweigart

26

看起来很简单:

  1. 确保你的文件名符合以下模式:test_*.py*_test.py
  2. 确保你的函数名test前缀开头。

在此处查看有关pytest惯例的更多信息here


1

尝试在setUp和tearDown的顶部添加@classmethod。


0

你执行了这个类本身吗?
我在你展示的代码中没有看到你调用类或定义来运行。
例如,在Python中,你可以像这样运行一个类或定义:

class Hello():
    # __init__ is a definition runs itself. 
    def __init__(self): 
        print('Hello there')
        # Call another definition. 
        self.andBye()

    # This definition should be calles in order to be executed. 
    def andBye(self):
        print('Goodbye')

# Run class 
Hello()

5
实际上,pytest 具有自动测试发现功能。 - alecxe

0
如果使用conda环境,请勿忘记激活它!

0
我收到了与下面显示的相同的消息。
$ pytest -q -rP

no tests ran in 0.10s

因为即使我的测试文件名是my_test_ex1.pymy_tests/中如下所示:
django-project
 |-core
 |  └-settings.py
 |-my_app1
 |-my_app2
 |-my_tests
 |  |-__init__.py
 |  └-my_test_ex1.py # Here
 |-pytest.ini
 ...

我将test_*.py设置为python_filespytest.ini中如下所示:

# "pytest.ini"

[pytest]
DJANGO_SETTINGS_MODULE = core.settings
python_files = test_*.py # Here

所以,我将my_test_*.py设置为python_files,如下所示,然后我就可以运行my_test_ex1.py中的测试了:

# "pytest.ini"

[pytest]
DJANGO_SETTINGS_MODULE = core.settings
python_files = my_test_*.py # Here

此外,默认情况下会搜索test_*.py*_test.py,如果您没有在pytest.ini中设置python_files,如下所示:
# "pytest.ini"

[pytest]
DJANGO_SETTINGS_MODULE = core.settings
# python_files = my_test_*.py
# `test_*.py` and `*_test.py` are searched

0
我在 pytest.ini 文件中找到了问题,其中我写成了 pyton_files = tests_*.py。去掉了 's' 后一切都顺利运行了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接