Files
awx/awxkit/test/cli/test_authentication.py
Hao LiuandClaude Fable 5.1 8565291e43 Fix awxkit config monkeypatching under pytest 9.2 (#16763)
Use monkeypatch.setitem for awxkit config in tests

awxkit's `config` is a PseudoNamespace, a dict subclass that exposes
its keys as attributes. pytest 9.2.0 changed monkeypatch.setattr to
read the previous value from the target's __dict__ instead of via
getattr, so for a dict-backed namespace it always records the attribute
as "did not exist" and schedules a delattr on undo. Patching the same
key twice (autouse fixture plus test body) then deletes it twice, and
PseudoNamespace.__delattr__ raises KeyError at teardown. This breaks
13 tests in test/cli/test_authentication.py on pytest >= 9.2.0.

monkeypatch.setitem records the old value with dict.get, which sees the
dict-backed storage correctly, so undo restores or removes exactly what
was there on any pytest version. test/api/pages/test_base.py is updated
for the same reason: under 9.2.0 its undo would delete a pre-existing
base_url or credentials value instead of restoring it.


Claude-Session: https://claude.ai/code/session_01SbeYPdRRLaGCk74gJHq9yS

Signed-off-by: Hao Liu <44379968+TheRealHaoLiu@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 22:27:06 +00:00

104 lines
3.7 KiB
Python

import pytest
from typing import Tuple, List, Optional
from unittest.mock import Mock
from awxkit.cli import CLI
from awxkit import config
@pytest.fixture(autouse=True)
def reset_config_state(monkeypatch: pytest.MonkeyPatch) -> None:
"""Ensure clean config state for each test to prevent parallel test interference"""
monkeypatch.setitem(config, 'force_basic_auth', False)
monkeypatch.setitem(config, 'use_sessions', False)
# ============================================================================
# Test Helper Functions
# ============================================================================
def setup_basic_auth(cli_args: Optional[List[str]] = None) -> Tuple[CLI, Mock, Mock]:
"""Set up CLI with mocked connection for Basic auth testing"""
cli = CLI()
cli.parse_args(cli_args or ['awx', '--conf.username', 'testuser', '--conf.password', 'testpass'])
mock_root = Mock()
mock_connection = Mock()
mock_root.connection = mock_connection
cli.root = mock_root
return cli, mock_root, mock_connection
def setup_session_auth(cli_args: Optional[List[str]] = None) -> Tuple[CLI, Mock, Mock]:
"""Set up CLI with mocked session for Session auth testing"""
cli = CLI()
cli.parse_args(cli_args or ['awx', '--conf.username', 'testuser', '--conf.password', 'testpass'])
mock_root = Mock()
mock_load_session = Mock()
mock_root.load_session.return_value = mock_load_session
cli.root = mock_root
return cli, mock_root, mock_load_session
def test_basic_auth_enabled(monkeypatch):
"""Test that AWXKIT_FORCE_BASIC_AUTH=true enables Basic authentication"""
cli, mock_root, mock_connection = setup_basic_auth()
monkeypatch.setitem(config, 'force_basic_auth', True)
cli.authenticate()
mock_connection.login.assert_called_once_with('testuser', 'testpass')
mock_root.get.assert_called_once()
assert not config.use_sessions
def test_session_auth_default(monkeypatch):
"""Test that session auth is used by default (backward compatibility)"""
cli, mock_root, mock_load_session = setup_session_auth()
monkeypatch.setitem(config, 'force_basic_auth', False)
cli.authenticate()
mock_root.load_session.assert_called_once()
mock_load_session.get.assert_called_once()
assert config.use_sessions
def test_aap_gateway_scenario(monkeypatch):
"""Test the specific AAP Gateway scenario from AAP-46830"""
cli, mock_root, mock_connection = setup_basic_auth(
['awx', '--conf.host', 'https://aap-sbx.cambiahealth.com', '--conf.username', 'puretest', '--conf.password', 'testpass']
)
monkeypatch.setitem(config, 'force_basic_auth', True)
cli.authenticate()
mock_connection.login.assert_called_once_with('puretest', 'testpass')
mock_root.get.assert_called_once()
assert not config.use_sessions
def test_empty_credentials_error(monkeypatch):
"""Test error handling for explicitly empty credentials"""
cli, mock_root, mock_connection = setup_basic_auth(['awx', '--conf.username', '', '--conf.password', ''])
monkeypatch.setitem(config, 'force_basic_auth', True)
with pytest.raises(ValueError, match="Basic authentication requires both username and password"):
cli.authenticate()
mock_connection.login.assert_not_called()
def test_connection_failure(monkeypatch):
"""Test error handling when Basic auth connection fails"""
cli, mock_root, mock_connection = setup_basic_auth()
mock_connection.login.side_effect = Exception("Connection failed")
monkeypatch.setitem(config, 'force_basic_auth', True)
with pytest.raises(RuntimeError, match="Basic authentication failed: Connection failed"):
cli.authenticate()
mock_connection.login.assert_called_once_with('testuser', 'testpass')
assert not config.use_sessions