Как заставить пользователя войти в систему один раз, а затем повторно использовать один и тот же сеанс в разных тестах?Python

Программы на Python
Ответить
Anonymous
 Как заставить пользователя войти в систему один раз, а затем повторно использовать один и тот же сеанс в разных тестах?

Сообщение Anonymous »

Использование

Код: Выделить всё

dependencies = [
"pytest>=9.0.2",
"pytest-playwright",
]
в приложении Python я устанавливаю сквозной тест браузера.
Я определил пользовательские маркеры:

Код: Выделить всё

[tool.pytest.ini_options]
markers = [
"user: test user role, e.g. admin",
"authenticated: session prepared, user already logged-in (log in will still happen once per test runner thread)",
"unauthenticated: no session, user not already logged-in",
]
В моем conftest.py я определил:

Код: Выделить всё

def pytest_sessionstart(session):
# Check variables before ANY test or browser starts
required = ["ADMIN_USER", "ADMIN_PASSWORD", "URL"]
missing = [var for var in required if var not in os.environ]
if missing:
pytest.exit(f"QUICK-FAIL: Missing environment variables: {missing}")

@pytest.fixture
def user(request):
marker = request.node.get_closest_marker("user")

if marker:
role = marker.args[0]
if role == "admin":
return request.getfixturevalue("admin_user")

pytest.fail("Test requested 'user' fixture but has no @pytest.mark.user('role') annotation.")

@pytest.fixture
def page(context: BrowserContext, user: User, request) -> Page:
is_auth = request.node.get_closest_marker("authenticated")
is_unauth = request.node.get_closest_marker("unauthenticated")

if not is_auth and not is_unauth:
pytest.fail("Test missing authentication marker. Please decorate with @pytest.mark.authenticated or @pytest.mark.unauthenticated")

if is_auth and is_unauth:
pytest.fail("Test has conflicting markers: cannot be both authenticated and unauthenticated.")

page = context.new_page()

if is_auth:
login_p = LoginPage(page, user)
login_p.login()

return page

@pytest.fixture
def user(request):
marker = request.node.get_closest_marker("user")

if marker:
role = marker.args[0]
if role == "admin":
return request.getfixturevalue("admin_user")

pytest.fail("Test requested 'user' fixture but has no @pytest.mark.user('role') annotation.")

@pytest.fixture
def page(context: BrowserContext, user: User, request) -> Page:
is_auth = request.node.get_closest_marker("authenticated")
is_unauth = request.node.get_closest_marker("unauthenticated")

if not is_auth and not is_unauth:
pytest.fail("Test missing authentication marker. Please decorate with @pytest.mark.authenticated or @pytest.mark.unauthenticated")

if is_auth and is_unauth:
pytest.fail("Test has conflicting markers: cannot be both authenticated and unauthenticated.")

page = context.new_page()

if is_auth:
login_p = LoginPage(page, user)
login_p.login()

return page
Идея состоит в том, что я могу проверить фактический вход в систему самостоятельно:

Код: Выделить всё

@pytest.mark.user("admin")
@pytest.mark.unauthenticated
def test_user_can_login(page: Page, user: User):
login_page = LoginPage(page, user)
login_page.login()

expect(page.get_by_role("link", name="expected_text")).to_be_visible()
И другие тесты могут использовать:

Код: Выделить всё

@pytest.mark.user("admin")
@pytest.mark.authenticated
def test_user_sees_main_page(page: Page, user: User):
target = f"{user.url}/dashboard"
page.goto(target)
page.wait_for_load_state("domcontentloaded")

expect(page.get_by_role("link", name="Address")).to_be_visible()

@pytest.mark.user("admin")
@pytest.mark.authenticated
def test_user_sees_address_page(page: Page, user: User):
target = f"{user.url}/address"
page.goto(target)
page.wait_for_load_state("domcontentloaded")

expect(page.get_by_role("link", name="Adressen")).to_be_visible()
Тем не менее, это в основном выполняет вход в систему каждый раз заново для каждого теста. Я хочу, чтобы вход в систему происходил в отдельном специальном тесте, но все остальные тесты должны повторно использовать один и тот же сеанс входа в систему;

Код: Выделить всё

    login_page = LoginPage(page, user)
login_page.login()
должен выполняться только один раз для каждого потока запуска теста. (Я согласен с тем, что вход в систему происходит иногда, но это не должно происходить все время для всех тестов.
Страница входа в систему не должна использоваться совместно между тестами; они должны требовать, чтобы вход в систему происходил только один раз для каждого определенного пользователя, браузера и рабочего потока/бегуна тестов (я хочу добавить pytest-xdist в будущем, иначе некоторые ci будут запускаться тест выполняется параллельно; скорее всего, для каждого файла.)
Как этого добиться?

Подробнее здесь: https://stackoverflow.com/questions/798 ... erent-test
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»