|
1 | 1 | """Test suite for the sample_data module.""" |
2 | 2 |
|
| 3 | +import logging |
3 | 4 | from pathlib import Path |
4 | 5 | from unittest.mock import MagicMock, patch |
5 | 6 |
|
|
14 | 15 | _fetch_metadata, |
15 | 16 | fetch_dataset, |
16 | 17 | fetch_dataset_paths, |
| 18 | + hide_pooch_hash_logs, |
17 | 19 | list_datasets, |
18 | 20 | ) |
19 | 21 |
|
@@ -273,3 +275,61 @@ def test_fetch_and_unzip_exceptions( |
273 | 275 | assert result == tmp_path / "poses" / "test" |
274 | 276 | assert ".DS_Store" not in result_names |
275 | 277 | assert expected_warning in caplog.records[-1].getMessage() |
| 278 | + |
| 279 | + |
| 280 | +@pytest.mark.parametrize( |
| 281 | + "message, should_block", |
| 282 | + [ |
| 283 | + ("SHA256 hash of downloaded file: abc123", True), |
| 284 | + ("Use this value as the 'known_hash' argument", True), |
| 285 | + ("Downloading file from ", False), |
| 286 | + ], |
| 287 | +) |
| 288 | +def test_hide_pooch_hash_logs(message, should_block): |
| 289 | + """Test that ``HashFilter`` blocks only hash-related messages.""" |
| 290 | + with hide_pooch_hash_logs(): |
| 291 | + logger = pooch.get_logger() |
| 292 | + hash_filter = logger.filters[-1] |
| 293 | + |
| 294 | + # Create a mock log record |
| 295 | + record = logging.LogRecord( |
| 296 | + name="pooch", |
| 297 | + level=logging.INFO, |
| 298 | + pathname="", |
| 299 | + lineno=0, |
| 300 | + msg=message, |
| 301 | + args=(), |
| 302 | + exc_info=None, |
| 303 | + ) |
| 304 | + |
| 305 | + # The filter returns False to block, True to allow |
| 306 | + message_allowed = hash_filter.filter(record) |
| 307 | + |
| 308 | + if should_block: |
| 309 | + assert not message_allowed, ( |
| 310 | + f"Expected message to be blocked but was allowed: '{message}'" |
| 311 | + ) |
| 312 | + else: |
| 313 | + assert message_allowed, ( |
| 314 | + f"Expected message to be allowed but was blocked: '{message}'" |
| 315 | + ) |
| 316 | + |
| 317 | + |
| 318 | +@pytest.mark.parametrize("raise_exception", [True, False]) |
| 319 | +def test_hash_filter_removed_after_context(raise_exception): |
| 320 | + """Test that the hash filter applied by ``hide_pooch_hash_logs`` |
| 321 | + is properly removed after exiting context, even when an exception occurs. |
| 322 | + """ |
| 323 | + logger = pooch.get_logger() |
| 324 | + initial_filter_count = len(logger.filters) |
| 325 | + |
| 326 | + if raise_exception: |
| 327 | + with pytest.raises(ValueError), hide_pooch_hash_logs(): |
| 328 | + assert len(logger.filters) == initial_filter_count + 1 |
| 329 | + raise ValueError("Test exception") |
| 330 | + else: |
| 331 | + with hide_pooch_hash_logs(): |
| 332 | + assert len(logger.filters) == initial_filter_count + 1 |
| 333 | + |
| 334 | + # Filter should be removed after context exits |
| 335 | + assert len(logger.filters) == initial_filter_count |
0 commit comments