-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathconftest.py
More file actions
172 lines (134 loc) · 3.87 KB
/
Copy pathconftest.py
File metadata and controls
172 lines (134 loc) · 3.87 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import os
import tempfile
import shutil
from pathlib import Path
from typing import Generator, Dict, Any
import pytest
import torch
@pytest.fixture
def temp_dir() -> Generator[Path, None, None]:
"""
Create a temporary directory for test files.
Yields:
Path: Path to the temporary directory
"""
temp_path = tempfile.mkdtemp()
yield Path(temp_path)
shutil.rmtree(temp_path)
@pytest.fixture
def sample_config() -> Dict[str, Any]:
"""
Provide a sample configuration dictionary for testing.
Returns:
Dict[str, Any]: Sample configuration
"""
return {
"model": {
"name": "test_model",
"num_classes": 10,
"input_size": 224,
"channels": 3,
},
"training": {
"batch_size": 32,
"learning_rate": 0.001,
"epochs": 10,
"device": "cpu",
},
"data": {
"train_path": "/path/to/train",
"val_path": "/path/to/val",
"test_path": "/path/to/test",
}
}
@pytest.fixture
def mock_dataset_path(temp_dir: Path) -> Path:
"""
Create a mock dataset directory structure.
Args:
temp_dir: Temporary directory fixture
Returns:
Path: Path to the mock dataset
"""
dataset_path = temp_dir / "mock_dataset"
# Create subdirectories
for split in ["train", "val", "test"]:
split_dir = dataset_path / split
split_dir.mkdir(parents=True, exist_ok=True)
# Create some mock class directories
for class_idx in range(3):
class_dir = split_dir / f"class_{class_idx}"
class_dir.mkdir(exist_ok=True)
# Create mock image files
for img_idx in range(2):
img_file = class_dir / f"image_{img_idx}.jpg"
img_file.touch()
return dataset_path
@pytest.fixture
def sample_tensor() -> torch.Tensor:
"""
Create a sample tensor for testing.
Returns:
torch.Tensor: A sample 4D tensor (batch, channels, height, width)
"""
return torch.randn(4, 3, 224, 224)
@pytest.fixture
def sample_labels() -> torch.Tensor:
"""
Create sample labels for testing.
Returns:
torch.Tensor: A sample label tensor
"""
return torch.randint(0, 10, (4,))
@pytest.fixture
def device() -> torch.device:
"""
Get the appropriate device for testing.
Returns:
torch.device: CPU device for consistent testing
"""
return torch.device("cpu")
@pytest.fixture(autouse=True)
def reset_random_seeds():
"""
Reset random seeds before each test for reproducibility.
"""
torch.manual_seed(42)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(42)
@pytest.fixture
def mock_model_checkpoint(temp_dir: Path) -> Dict[str, Any]:
"""
Create a mock model checkpoint.
Args:
temp_dir: Temporary directory fixture
Returns:
Dict[str, Any]: Mock checkpoint data
"""
checkpoint = {
"epoch": 5,
"model_state_dict": {"layer1.weight": torch.randn(10, 10)},
"optimizer_state_dict": {"param_groups": [{"lr": 0.001}]},
"loss": 0.1234,
"accuracy": 0.95,
}
checkpoint_path = temp_dir / "checkpoint.pth"
torch.save(checkpoint, checkpoint_path)
return {
"path": checkpoint_path,
"data": checkpoint
}
@pytest.fixture
def capture_stdout(monkeypatch):
"""
Capture stdout for testing print statements.
Args:
monkeypatch: pytest monkeypatch fixture
Returns:
list: List to collect stdout outputs
"""
outputs = []
def mock_print(*args, **kwargs):
outputs.append(" ".join(map(str, args)))
monkeypatch.setattr("builtins.print", mock_print)
return outputs