Debian Codegraph @

tests/TESTING_GUIDE.md

raw
1 # Fenrir Testing Guide
2
3 Complete guide to running and writing tests for the Fenrir screen reader.
4
5 ## Quick Start
6
7 ### 1. Install Test Dependencies
8
9 ```bash
10 # Install test requirements
11 pip install -r tests/requirements.txt
12
13 # Or install individually
14 pip install pytest pytest-cov pytest-mock pytest-timeout
15 ```
16
17 ### 2. Run Tests
18
19 ```bash
20 # Run all tests (unit + integration)
21 pytest tests/
22
23 # Run only unit tests (fastest)
24 pytest tests/unit/ -v
25
26 # Run only integration tests
27 pytest tests/integration/ -v
28
29 # Run with coverage report
30 pytest tests/ --cov=src/fenrirscreenreader --cov-report=html
31 # Then open htmlcov/index.html in a browser
32
33 # Run specific test file
34 pytest tests/unit/test_settings_validation.py -v
35
36 # Run specific test class
37 pytest tests/unit/test_settings_validation.py::TestSpeechSettingsValidation -v
38
39 # Run specific test
40 pytest tests/unit/test_settings_validation.py::TestSpeechSettingsValidation::test_speech_rate_valid_range -v
41 ```
42
43 ### 3. Useful Test Options
44
45 ```bash
46 # Stop on first failure
47 pytest tests/ -x
48
49 # Show test output (print statements, logging)
50 pytest tests/ -s
51
52 # Run tests in parallel (faster, requires: pip install pytest-xdist)
53 pytest tests/ -n auto
54
55 # Show slowest 10 tests
56 pytest tests/ --durations=10
57
58 # Run only tests matching a keyword
59 pytest tests/ -k "remote"
60
61 # Run tests with specific markers
62 pytest tests/ -m unit # Only unit tests
63 pytest tests/ -m integration # Only integration tests
64 pytest tests/ -m "not slow" # Skip slow tests
65 ```
66
67 ## Test Structure
68
69 ```
70 tests/
71 ├── README.md # Test overview and strategy
72 ├── TESTING_GUIDE.md # This file - detailed usage guide
73 ├── requirements.txt # Test dependencies
74 ├── conftest.py # Shared fixtures and pytest config
75 ├── unit/ # Unit tests (fast, isolated)
76 │ ├── __init__.py
77 │ ├── test_settings_validation.py # Settings validation tests
78 │ ├── test_cursor_utils.py # Cursor calculation tests
79 │ └── test_text_utils.py # Text processing tests
80 ├── integration/ # Integration tests (require mocking)
81 │ ├── __init__.py
82 │ ├── test_remote_control.py # Remote control functionality
83 │ ├── test_command_manager.py # Command loading/execution
84 │ └── test_event_manager.py # Event queue processing
85 └── drivers/ # Driver tests (require root)
86 ├── __init__.py
87 ├── test_vcsa_driver.py # TTY screen reading
88 └── test_evdev_driver.py # Keyboard input capture
89 ```
90
91 ## Writing New Tests
92
93 ### Unit Test Example
94
95 ```python
96 """tests/unit/test_my_feature.py"""
97 import pytest
98
99 @pytest.mark.unit
100 def test_speech_rate_calculation():
101 """Test that speech rate is calculated correctly."""
102 rate = calculate_speech_rate(0.5)
103 assert 0.0 <= rate <= 1.0
104 assert rate == 0.5
105 ```
106
107 ### Integration Test Example
108
109 ```python
110 """tests/integration/test_my_integration.py"""
111 import pytest
112
113 @pytest.mark.integration
114 def test_remote_command_execution(mock_environment):
115 """Test remote command execution flow."""
116 manager = RemoteManager()
117 manager.initialize(mock_environment)
118
119 result = manager.handle_command_execution_with_response("say test")
120
121 assert result["success"] is True
122 mock_environment["runtime"]["OutputManager"].speak_text.assert_called_once()
123 ```
124
125 ### Using Fixtures
126
127 Common fixtures are defined in `conftest.py`:
128
129 ```python
130 def test_with_mock_environment(mock_environment):
131 """Use the shared mock environment fixture."""
132 # mock_environment provides mocked runtime managers
133 assert "runtime" in mock_environment
134 assert "DebugManager" in mock_environment["runtime"]
135
136 def test_with_temp_config(temp_config_file):
137 """Use a temporary config file."""
138 # temp_config_file is a Path object to a valid test config
139 assert temp_config_file.exists()
140 content = temp_config_file.read_text()
141 assert "[speech]" in content
142 ```
143
144 ## Test Markers
145
146 Tests can be marked to categorize them:
147
148 ```python
149 @pytest.mark.unit # Fast, isolated unit test
150 @pytest.mark.integration # Integration test with mocking
151 @pytest.mark.driver # Requires root access (skipped by default)
152 @pytest.mark.slow # Takes > 1 second
153 @pytest.mark.remote # Tests remote control functionality
154 @pytest.mark.settings # Tests settings/configuration
155 @pytest.mark.commands # Tests command system
156 @pytest.mark.vmenu # Tests VMenu system
157 ```
158
159 Run tests by marker:
160 ```bash
161 pytest tests/ -m unit # Only unit tests
162 pytest tests/ -m "unit or integration" # Unit and integration
163 pytest tests/ -m "not slow" # Skip slow tests
164 ```
165
166 ## Code Coverage
167
168 ### View Coverage Report
169
170 ```bash
171 # Generate HTML coverage report
172 pytest tests/ --cov=src/fenrirscreenreader --cov-report=html
173
174 # Open report in browser
175 firefox htmlcov/index.html # Or your preferred browser
176
177 # Terminal coverage report
178 pytest tests/ --cov=src/fenrirscreenreader --cov-report=term-missing
179 ```
180
181 ### Coverage Goals
182
183 - **Unit Tests**: 80%+ coverage on utility functions and validation logic
184 - **Integration Tests**: 60%+ coverage on core managers
185 - **Overall**: 70%+ coverage on non-driver code
186
187 Driver code is excluded from coverage as it requires hardware interaction.
188
189 ## Testing Best Practices
190
191 ### 1. Test One Thing
192
193 ```python
194 # Good - tests one specific behavior
195 def test_speech_rate_rejects_negative():
196 with pytest.raises(ValueError):
197 validate_rate(-1.0)
198
199 # Bad - tests multiple unrelated things
200 def test_speech_settings():
201 validate_rate(0.5) # Rate validation
202 validate_pitch(1.0) # Pitch validation
203 validate_volume(0.8) # Volume validation
204 ```
205
206 ### 2. Use Descriptive Names
207
208 ```python
209 # Good - clear what's being tested
210 def test_speech_rate_rejects_values_above_three():
211 ...
212
213 # Bad - unclear purpose
214 def test_rate():
215 ...
216 ```
217
218 ### 3. Arrange-Act-Assert Pattern
219
220 ```python
221 def test_remote_command_parsing():
222 # Arrange - set up test data
223 manager = RemoteManager()
224 command = "say Hello World"
225
226 # Act - execute the code being tested
227 result = manager.parse_command(command)
228
229 # Assert - verify the result
230 assert result["action"] == "say"
231 assert result["text"] == "Hello World"
232 ```
233
234 ### 4. Mock External Dependencies
235
236 ```python
237 def test_clipboard_export(mock_environment, tmp_path):
238 """Test clipboard export without real file operations."""
239 # Use mock environment instead of real Fenrir runtime
240 manager = RemoteManager()
241 manager.initialize(mock_environment)
242
243 # Use temporary path instead of /tmp
244 clipboard_path = tmp_path / "clipboard"
245 mock_environment["runtime"]["SettingsManager"].get_setting = Mock(
246 return_value=str(clipboard_path)
247 )
248
249 manager.export_clipboard()
250
251 assert clipboard_path.exists()
252 ```
253
254 ### 5. Test Error Paths
255
256 ```python
257 def test_remote_command_handles_invalid_input():
258 """Test that invalid commands are handled gracefully."""
259 manager = RemoteManager()
260
261 # Test with various invalid inputs
262 result1 = manager.handle_command_execution_with_response("")
263 result2 = manager.handle_command_execution_with_response("invalid")
264 result3 = manager.handle_command_execution_with_response("command unknown")
265
266 # All should return error results, not crash
267 assert all(not r["success"] for r in [result1, result2, result3])
268 ```
269
270 ## Debugging Tests
271
272 ### Run with More Verbosity
273
274 ```bash
275 # Show test names and outcomes
276 pytest tests/ -v
277
278 # Show test names, outcomes, and print statements
279 pytest tests/ -v -s
280
281 # Show local variables on failure
282 pytest tests/ --showlocals
283
284 # Show full diff on assertion failures
285 pytest tests/ -vv
286 ```
287
288 ### Use pytest.set_trace() for Debugging
289
290 ```python
291 def test_complex_logic():
292 result = complex_function()
293 pytest.set_trace() # Drop into debugger here
294 assert result == expected
295 ```
296
297 ### Run Single Test Repeatedly
298
299 ```bash
300 # Useful for debugging flaky tests
301 pytest tests/unit/test_my_test.py::test_specific_test --count=100
302 ```
303
304 ## Continuous Integration
305
306 ### GitHub Actions Example
307
308 ```yaml
309 name: Tests
310
311 on: [push, pull_request]
312
313 jobs:
314 test:
315 runs-on: ubuntu-latest
316 steps:
317 - uses: actions/checkout@v3
318 - uses: actions/setup-python@v4
319 with:
320 python-version: '3.9'
321 - name: Install dependencies
322 run: |
323 pip install -r requirements.txt
324 pip install -r tests/requirements.txt
325 - name: Run tests
326 run: pytest tests/ --cov=src/fenrirscreenreader --cov-report=xml
327 - name: Upload coverage
328 uses: codecov/codecov-action@v3
329 ```
330
331 ## Common Issues
332
333 ### ImportError: No module named 'fenrirscreenreader'
334
335 **Solution**: Make sure you're running pytest from the project root, or set PYTHONPATH:
336 ```bash
337 export PYTHONPATH="${PYTHONPATH}:$(pwd)/src"
338 pytest tests/
339 ```
340
341 ### Tests hang or timeout
342
343 **Solution**: Use the timeout decorator or pytest-timeout:
344 ```bash
345 pytest tests/ --timeout=30 # Global 30s timeout
346 ```
347
348 Or mark specific tests:
349 ```python
350 @pytest.mark.timeout(5)
351 def test_that_might_hang():
352 ...
353 ```
354
355 ### Mocks not working as expected
356
357 **Solution**: Check that you're patching the right location:
358 ```python
359 # Good - patch where it's used
360 @patch('fenrirscreenreader.core.remoteManager.OutputManager')
361
362 # Bad - patch where it's defined
363 @patch('fenrirscreenreader.core.outputManager.OutputManager')
364 ```
365
366 ## Advanced Topics
367
368 ### Parametrized Tests
369
370 Test multiple inputs with one test:
371
372 ```python
373 @pytest.mark.parametrize("rate,expected", [
374 (0.0, True),
375 (1.5, True),
376 (3.0, True),
377 (-1.0, False),
378 (10.0, False),
379 ])
380 def test_rate_validation(rate, expected):
381 try:
382 validate_rate(rate)
383 assert expected is True
384 except ValueError:
385 assert expected is False
386 ```
387
388 ### Test Fixtures with Cleanup
389
390 ```python
391 @pytest.fixture
392 def temp_fenrir_instance():
393 """Start a test Fenrir instance."""
394 fenrir = FenrirTestInstance()
395 fenrir.start()
396
397 yield fenrir # Test runs here
398
399 # Cleanup after test
400 fenrir.stop()
401 fenrir.cleanup()
402 ```
403
404 ### Testing Async Code
405
406 ```python
407 @pytest.mark.asyncio
408 async def test_async_speech():
409 result = await async_speak("test")
410 assert result.success
411 ```
412
413 ## Getting Help
414
415 - **Pytest Documentation**: https://docs.pytest.org/
416 - **Fenrir Issues**: https://github.com/chrys87/fenrir/issues
417 - **Test Coverage**: Run with `--cov-report=html` and inspect `htmlcov/index.html`
418
419 ## Contributing Tests
420
421 When contributing tests:
422
423 1. **Follow naming conventions**: `test_*.py` for files, `test_*` for functions
424 2. **Add docstrings**: Explain what each test verifies
425 3. **Use appropriate markers**: `@pytest.mark.unit`, `@pytest.mark.integration`, etc.
426 4. **Keep tests fast**: Unit tests should complete in <100ms
427 5. **Test edge cases**: Empty strings, None, negative numbers, etc.
428 6. **Update this guide**: If you add new test patterns or fixtures
429
430 Happy testing! 🧪