параметризованный объект pytest с наследованием - дочерний класс не имеет атрибутов - PullRequest
0 голосов
/ 20 февраля 2019

Я столкнулся со странным поведением с параметризованным приспособлением 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 »имеетнет атрибута "значение" "Почему?оба класса Base и Child имеют атрибут value.

1 Ответ

0 голосов
/ 20 февраля 2019

Я предлагаю, чтобы строка 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...