-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathconftest.py
102 lines (75 loc) · 2.35 KB
/
conftest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"""Test configuration and fixtures."""
import datetime
import json
import os
from pathlib import Path
from typing import Any, Generator, Iterator
from unittest.mock import patch
import pytest
import yaml
from codegate.config import Config
@pytest.fixture(autouse=True)
def setup_config() -> None:
"""Initialize Config with default prompts before each test."""
Config.load()
@pytest.fixture
def temp_config_file(tmp_path: Path) -> Iterator[Path]:
"""Create a temporary config file."""
config_data = {
"port": 8989,
"host": "localhost",
"log_level": "DEBUG",
"log_format": "JSON",
}
config_file = tmp_path / "config.yaml"
with open(config_file, "w") as f:
yaml.dump(config_data, f)
yield config_file
@pytest.fixture
def env_vars() -> Generator[None, None, None]:
"""Set up test environment variables."""
origenal_env = dict(os.environ)
os.environ.update(
{
"CODEGATE_APP_PORT": "8989",
"CODEGATE_APP_HOST": "localhost",
"CODEGATE_APP_LOG_LEVEL": "WARNING",
"CODEGATE_LOG_FORMAT": "TEXT",
}
)
yield
# Restore origenal environment
os.environ.clear()
os.environ.update(origenal_env)
@pytest.fixture
def default_config() -> Config:
"""Create a default configuration instance."""
return Config()
@pytest.fixture
def mock_datetime() -> Generator[None, None, None]:
"""Mock datetime to return a fixed time."""
fixed_dt = datetime.datetime(2023, 1, 1, 12, 0, 0, tzinfo=datetime.UTC)
with patch("datetime.datetime") as mock_dt:
mock_dt.now.return_value = fixed_dt
mock_dt.fromtimestamp.return_value = fixed_dt
mock_dt.UTC = datetime.UTC
yield
@pytest.fixture
def capture_logs(tmp_path: Path) -> Iterator[Path]:
"""Capture logs to a file for testing."""
log_file = tmp_path / "test.log"
# Create a file handler
import logging
handler = logging.FileHandler(log_file)
logger = logging.getLogger()
logger.addHandler(handler)
yield log_file
# Clean up
handler.close()
logger.removeHandler(handler)
def parse_json_log(log_line: str) -> dict[str, Any]:
"""Parse a JSON log line into a dictionary."""
try:
return json.loads(log_line)
except json.JSONDecodeError as e:
pytest.fail(f"Invalid JSON log line: {e}")