Single Global Authentication Setup with Pytest and YAML: Auto-Injecting Bearer Tokens into All Test Requests

This workflow uses Python 3.10, pytest 7.4, and a fixture-based pytest-YAML testing stack. A built-in session_client fixture with scope="session" (instantiated once across all test sessions) is the core component here—we’ll attach our authenticated headers directly to it.

import pytest
import uuid

# Helper function to simulate credential exchange and token retrieval
def fetch_auth_token():
    # Replace this block with actual login API POST call
    return str(uuid.uuid4())

@pytest.fixture(scope="session", autouse=True)
def initialize_session_auth(session_client):
    # Fetch token exactly once during test suite initialization
    active_bearer = fetch_auth_token()
    auth_headers = {
        "Authorization": f"Bearer {active_bearer}"
    }
    session_client.headers.update(auth_headers)

With the session fixture configured, individual YAML test files no longer need redundant header configurations. Below are two simplified test cases:

test_get_resource.yml

config:
  name: Retrieve sample resource

teststeps:
  - name: Execute GET resource request
    request:
      method: GET
      url: http://httpbin.org/get
    validate:
      - eq: [status_code, 200]

test_post_payload.yml

config:
  name: Submit test payload
  variables:
    user_email: demo@example.com
    passcode: "secure123"

teststeps:
  - name: Send POST with JSON data
    request:
      method: POST
      url: http://httpbin.org/post
      json:
        email: ${user_email}
        pwd: ${passcode}
    validate:
      - eq: [status_code, 200]
      - eq: [headers.Server, gunicorn/19.9.0]
      - eq: [$..email, demo@example.com]
      - eq: [body.json.pwd, secure123]

To execute, run pytest in the terminal. Traffic inspection will confirm that the Authorization header is automatically appended to every outgoing test request. This same pattern aplies to cookie-based sessions—most HTTP client sessions automatically persist cookies after a succesfull login response.

For endpoints that skip authentication (like login, registration, or public health checks), avoid the universal session_client. The framework includes additional scoped fixtures: module_client (instantiated once per YAML test file) and function_client (instantiated once per individual test step).

Tags: pytest YAML Automated Testing Authentication test fixtures

Posted on Thu, 25 Jun 2026 16:52:59 +0000 by bsgrules