|
3 | 3 |
|
4 | 4 | """Tests for `channel.FileWatcher`.""" |
5 | 5 |
|
6 | | -import os |
| 6 | +from __future__ import annotations |
| 7 | + |
7 | 8 | import pathlib |
8 | | -from datetime import timedelta |
| 9 | +from collections.abc import AsyncGenerator, Iterator, Sequence |
| 10 | +from typing import Any |
| 11 | +from unittest import mock |
9 | 12 |
|
10 | | -from frequenz.channels.util import FileWatcher, Select, Timer |
| 13 | +import hypothesis |
| 14 | +import hypothesis.strategies as st |
| 15 | +import pytest |
| 16 | +from watchfiles import Change |
| 17 | +from watchfiles.main import FileChange |
11 | 18 |
|
| 19 | +from frequenz.channels.util import FileWatcher |
12 | 20 |
|
13 | | -async def test_file_watcher(tmp_path: pathlib.Path) -> None: |
14 | | - """Ensure file watcher is returning paths on file events. |
15 | 21 |
|
16 | | - Args: |
17 | | - tmp_path (pathlib.Path): A tmp directory to run the file watcher on. |
18 | | - Created by pytest. |
19 | | - """ |
20 | | - filename = tmp_path / "test-file" |
21 | | - file_watcher = FileWatcher(paths=[str(tmp_path)]) |
| 22 | +class _FakeAwatch: |
| 23 | + """Fake awatch class to mock the awatch function.""" |
22 | 24 |
|
23 | | - number_of_writes = 0 |
24 | | - expected_number_of_writes = 3 |
| 25 | + def __init__(self, changes: Sequence[FileChange] = ()) -> None: |
| 26 | + """Create a `_FakeAwatch` instance. |
25 | 27 |
|
26 | | - select = Select( |
27 | | - timer=Timer.timeout(timedelta(seconds=0.1)), |
28 | | - file_watcher=file_watcher, |
29 | | - ) |
30 | | - while await select.ready(): |
31 | | - if msg := select.timer: |
32 | | - filename.write_text(f"{msg.inner}") |
33 | | - elif msg := select.file_watcher: |
34 | | - assert msg.inner == filename |
35 | | - number_of_writes += 1 |
36 | | - # After receiving a write 3 times, unsubscribe from the writes channel |
37 | | - if number_of_writes == expected_number_of_writes: |
38 | | - break |
39 | | - |
40 | | - assert number_of_writes == expected_number_of_writes |
41 | | - |
42 | | - |
43 | | -async def test_file_watcher_change_types(tmp_path: pathlib.Path) -> None: |
44 | | - """Ensure file watcher is returning paths only on the DELETE change. |
45 | | -
|
46 | | - Args: |
47 | | - tmp_path (pathlib.Path): A tmp directory to run the file watcher on. |
48 | | - Created by pytest. |
49 | | - """ |
50 | | - filename = tmp_path / "test-file" |
51 | | - file_watcher = FileWatcher( |
52 | | - paths=[str(tmp_path)], event_types={FileWatcher.EventType.DELETE} |
53 | | - ) |
| 28 | + Args: |
| 29 | + changes: A sequence of file changes to be returned by the fake awatch |
| 30 | + function. |
| 31 | + """ |
| 32 | + self.changes: Sequence[FileChange] = changes |
| 33 | + |
| 34 | + async def fake_awatch( |
| 35 | + self, *paths: str, **kwargs: Any # pylint: disable=unused-argument |
| 36 | + ) -> AsyncGenerator[set[FileChange], None]: |
| 37 | + """Fake awatch function. |
| 38 | +
|
| 39 | + Args: |
| 40 | + paths: Paths to watch. |
| 41 | + kwargs: Keyword arguments to pass to the awatch function. |
| 42 | + """ |
| 43 | + for change in self.changes: |
| 44 | + yield {change} |
| 45 | + |
| 46 | + |
| 47 | +@pytest.fixture |
| 48 | +def fake_awatch() -> Iterator[_FakeAwatch]: |
| 49 | + """Fixture to mock the awatch function.""" |
| 50 | + fake = _FakeAwatch() |
| 51 | + with mock.patch( |
| 52 | + "frequenz.channels.util._file_watcher.awatch", |
| 53 | + autospec=True, |
| 54 | + side_effect=fake.fake_awatch, |
| 55 | + ): |
| 56 | + yield fake |
54 | 57 |
|
55 | | - select = Select( |
56 | | - write_timer=Timer.timeout(timedelta(seconds=0.1)), |
57 | | - deletion_timer=Timer.timeout(timedelta(seconds=0.25)), |
58 | | - watcher=file_watcher, |
| 58 | + |
| 59 | +async def test_file_watcher_receive_updates( |
| 60 | + fake_awatch: _FakeAwatch, # pylint: disable=redefined-outer-name |
| 61 | +) -> None: |
| 62 | + """Test the file watcher receive the expected events.""" |
| 63 | + filename = "test-file" |
| 64 | + changes = ( |
| 65 | + (Change.added, filename), |
| 66 | + (Change.deleted, filename), |
| 67 | + (Change.modified, filename), |
59 | 68 | ) |
60 | | - number_of_deletes = 0 |
61 | | - number_of_write = 0 |
62 | | - while await select.ready(): |
63 | | - if msg := select.write_timer: |
64 | | - filename.write_text(f"{msg.inner}") |
65 | | - number_of_write += 1 |
66 | | - elif _ := select.deletion_timer: |
67 | | - os.remove(filename) |
68 | | - elif _ := select.watcher: |
69 | | - number_of_deletes += 1 |
70 | | - break |
71 | | - |
72 | | - assert number_of_deletes == 1 |
73 | | - # Can be more because the watcher could take some time to trigger |
74 | | - assert number_of_write >= 2 |
| 69 | + fake_awatch.changes = changes |
| 70 | + file_watcher = FileWatcher(paths=[filename]) |
| 71 | + |
| 72 | + for change in changes: |
| 73 | + recv_changes = await file_watcher.receive() |
| 74 | + assert recv_changes == pathlib.Path(change[1]) |
| 75 | + |
| 76 | + |
| 77 | +@hypothesis.given(event_types=st.sets(st.sampled_from(FileWatcher.EventType))) |
| 78 | +async def test_file_watcher_filter_events( |
| 79 | + event_types: set[FileWatcher.EventType], |
| 80 | +) -> None: |
| 81 | + """Test the file watcher events filtering.""" |
| 82 | + good_path = "good-file" |
| 83 | + |
| 84 | + # We need to reset the mock explicitly because hypothesis runs all the produced |
| 85 | + # inputs in the same context. |
| 86 | + with mock.patch( |
| 87 | + "frequenz.channels.util._file_watcher.awatch", autospec=True |
| 88 | + ) as awatch_mock: |
| 89 | + file_watcher = FileWatcher(paths=[good_path], event_types=event_types) |
| 90 | + |
| 91 | + filter_events = file_watcher._filter_events # pylint: disable=protected-access |
| 92 | + |
| 93 | + assert awatch_mock.mock_calls == [ |
| 94 | + mock.call( |
| 95 | + pathlib.Path(good_path), stop_event=mock.ANY, watch_filter=filter_events |
| 96 | + ) |
| 97 | + ] |
| 98 | + for event_type in FileWatcher.EventType: |
| 99 | + assert filter_events(event_type.value, good_path) == ( |
| 100 | + event_type in event_types |
| 101 | + ) |
0 commit comments