Flask pytest AttributeError: у объекта 'Function' нет атрибута 'get_marker' - PullRequest
0 голосов
/ 23 марта 2020

Я пытаюсь запустить тесты на примере Flask -SQLAlchemy в https://github.com/pallets/flask-sqlalchemy/tree/master/examples/flaskr с использованием pytest.

Файл conftest.py выглядит следующим образом:

from datetime import datetime

import pytest
from werkzeug.security import generate_password_hash

from flaskr import create_app
from flaskr import db
from flaskr import init_db
from flaskr.auth.models import User
from flaskr.blog.models import Post

_user1_pass = generate_password_hash("test")
_user2_pass = generate_password_hash("other")


@pytest.fixture
def app():
    """Create and configure a new app instance for each test."""
    # create the app with common test config
    app = create_app({"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:"})

    # create the database and load test data
    # set _password to pre-generated hashes, since hashing for each test is slow
    with app.app_context():
        init_db()
        user = User(username="test", _password=_user1_pass)
        db.session.add_all(
            (
                user,
                User(username="other", _password=_user2_pass),
                Post(
                    title="test title",
                    body="test\nbody",
                    author=user,
                    created=datetime(2018, 1, 1),
                ),
            )
        )
        db.session.commit()

    yield app


@pytest.fixture
def client(app):
    """A test client for the app."""
    return app.test_client()


@pytest.fixture
def runner(app):
    """A test runner for the app's Click commands."""
    return app.test_cli_runner()


class AuthActions(object):
    def __init__(self, client):
        self._client = client

    def login(self, username="test", password="test"):
        return self._client.post(
            "/auth/login", data={"username": username, "password": password}
        )

    def logout(self):
        return self._client.get("/auth/logout")


@pytest.fixture
def auth(client):
    return AuthActions(client)

Один из тестов выглядит следующим образом:

import pytest
from flask import g
from flask import session

from flaskr.auth.models import User


def test_register(client, app):
    # test that viewing the page renders without template errors
    assert client.get("/auth/register").status_code == 200

    # test that successful registration redirects to the login page
    response = client.post("/auth/register", data={"username": "a", "password": "a"})
    assert "http://localhost/auth/login" == response.headers["Location"]

    # test that the user was inserted into the database
    with app.app_context():
        assert User.query.filter_by(username="a").first() is not None


def test_user_password(app):
    user = User(username="a", password="a")
    assert user.password != "a"
    assert user.check_password("a")


@pytest.mark.parametrize(
    ("username", "password", "message"),
    (
        ("", "", b"Username is required."),
        ("a", "", b"Password is required."),
        ("test", "test", b"already registered"),
    ),
)
def test_register_validate_input(client, username, password, message):
    response = client.post(
        "/auth/register", data={"username": username, "password": password}
    )
    assert message in response.data


def test_login(client, auth):
    # test that viewing the page renders without template errors
    assert client.get("/auth/login").status_code == 200

    # test that successful login redirects to the index page
    response = auth.login()
    assert response.headers["Location"] == "http://localhost/"

    # login request set the user_id in the session
    # check that the user is loaded from the session
    with client:
        client.get("/")
        assert session["user_id"] == 1
        assert g.user.username == "test"


@pytest.mark.parametrize(
    ("username", "password", "message"),
    (("a", "test", b"Incorrect username."), ("test", "a", b"Incorrect password.")),
)
def test_login_validate_input(auth, username, password, message):
    response = auth.login(username, password)
    assert message in response.data


def test_logout(client, auth):
    auth.login()

    with client:
        auth.logout()
        assert "user_id" not in session

Однако, когда я запускаю pytest, я получаю следующее ошибка для всех тестов.

AttributeError: 'Function' object has no attribute 'get_marker'

Вот более подробная ошибка:

________________ ERROR at setup of test_login_required[/create] ________________

item = <Function test_login_required[/create]>

    def pytest_runtest_setup(item):

>       remote_data = item.get_marker('remote_data')
E       AttributeError: 'Function' object has no attribute 'get_marker'

../../../../../../anaconda3/lib/python3.6/site-packages/pytest_remotedata/plugin.py:59: AttributeError

Кажется, что я получаю эту ошибку для любого pytest / flask настроить. Что здесь происходит?

...