python - 具有继承性的 pytest 参数化 fixture - 子类没有属性

标签 python inheritance pytest

我遇到了一个我无法理解的 pytest 参数化 fixture 的奇怪行为。

鉴于此 sample.py :

import pytest
import requests
import conftest

@pytest.mark.parametrize('handler_class', [conftest.Child])
def test_simple(my_fixture):
    try:
        requests.get("http://localhost:8000")
    except:
        pass

以及同一目录中的以下 conftest.py :
class Base(http.server.SimpleHTTPRequestHandler):
    def __init__(self, request, client_address, server):
        super().__init__(request, client_address, server)
        self.value = 0

    def do_GET(self):
        print(self.value)   # AttributeError: 'Child' object has no attribute 'value'
        self.send_error(500)

class Child(Base):
    def __init__(self, request, client_address, server):
        super().__init__(request, client_address, server)
        self.value = 1

@pytest.fixture
def my_fixture(handler_class):
    handler = handler_class
    httpd = http.server.HTTPServer(('', 8000), handler)
    http_thread = threading.Thread(target=httpd.serve_forever)
    http_thread.start()
    yield
    httpd.shutdown()

如果你跑

pytest -s sample.py



有一个异常(exception),“AttributeError: 'Child' object has no attribute 'value'” 为什么?类 Base 和 Child 都有一个 value 属性。

最佳答案

我的建议是该行 print(self.value)在行之前到达 self.value = 0在其他线程中,这就是发生此类错误的原因。你需要像这样重构你的代码:

class Base(http.server.SimpleHTTPRequestHandler):
    def __init__(self, request, client_address, server, value=0):
        self.value = value
        super().__init__(request, client_address, server)

    def do_GET(self):
        print(self.value)  # 1 when doing pytest -s sample.py
        self.send_error(500)

class Child(Base):
    def __init__(self, request, client_address, server):
        super().__init__(request, client_address, server, value=1)

关于python - 具有继承性的 pytest 参数化 fixture - 子类没有属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54790561/

相关文章:

python - 你将如何在 python 的数组中对这三个区域进行分组/聚类?

c++ - copy-and-swap 习语,继承

python - 如何使 pytest 显示 fixture 参数的自定义字符串表示形式?

python-3.x - PyTest - 将模拟应用于所有测试

python - Elastic Beanstalk 中的 enum34 问题

python - 正态分布样本的置信区间

inheritance - 在 Go 中实现 Struct 抽象的正确方法是什么?

java - 接口(interface)允许任何子类参数

python - 如何使用 pytest、fastapi 和 tortoise-orm 回滚每个测试?

python - 快速排序python递归