繁体   English   中英

带有继承的pytest参数化夹具-子类没有属性

[英]pytest parametrized fixture with inheritance - child class has no attributes

我无法理解pytest参数化固定装置的异常行为。

给定这个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

有一个例外,“ AttributeError:'Child'对象没有属性'value'”为什么? Base和Child类都具有value属性。

我的建议是在其他线程中,在行self.value = 0之前到达行print(self.value) ,这就是为什么会发生这种错误的原因。 您需要重构代码,如下所示:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM