| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
""" |
| 18 |
plugins.fake_monitor |
| 19 |
==================== |
| 20 |
|
| 21 |
Provide a fake :class:`~pyudev.Monitor`. |
| 22 |
|
| 23 |
This fake monitor allows to trigger arbitrary events. Use this class to |
| 24 |
test class building upon monitor without the need to rely on real events |
| 25 |
generated by privileged operations. |
| 26 |
|
| 27 |
.. moduleauthor:: Sebastian Wiesner <[email protected]> |
| 28 |
""" |
| 29 |
|
| 30 |
|
| 31 |
import os |
| 32 |
from select import select |
| 33 |
|
| 34 |
|
| 35 |
import pytest |
| 36 |
|
| 37 |
|
| 38 |
class FakeMonitor: |
| 39 |
""" |
| 40 |
A fake :class:`~pyudev.Monitor` which allows you to trigger arbitrary |
| 41 |
events. |
| 42 |
|
| 43 |
This fake monitor implements the complete :class:`~pyudev.Monitor` |
| 44 |
interface and works on real file descriptors so that you can |
| 45 |
:func:`~select.select()` the monitor. |
| 46 |
""" |
| 47 |
|
| 48 |
def __init__(self, device_to_emit): |
| 49 |
self._event_source, self._event_sink = os.pipe() |
| 50 |
self.device_to_emit = device_to_emit |
| 51 |
self.started = False |
| 52 |
|
| 53 |
def trigger_event(self): |
| 54 |
""" |
| 55 |
Trigger an event on clients of this monitor. |
| 56 |
""" |
| 57 |
os.write(self._event_sink, b"\x01") |
| 58 |
|
| 59 |
def fileno(self): |
| 60 |
return self._event_source |
| 61 |
|
| 62 |
def filter_by(self, *args): |
| 63 |
pass |
| 64 |
|
| 65 |
def start(self): |
| 66 |
self.started = True |
| 67 |
|
| 68 |
def poll(self, timeout=None): |
| 69 |
rlist, _, _ = select([self._event_source], [], [], timeout) |
| 70 |
if self._event_source in rlist: |
| 71 |
os.read(self._event_source, 1) |
| 72 |
return self.device_to_emit |
| 73 |
|
| 74 |
def close(self): |
| 75 |
""" |
| 76 |
Close sockets acquired by this monitor. |
| 77 |
""" |
| 78 |
try: |
| 79 |
os.close(self._event_source) |
| 80 |
finally: |
| 81 |
os.close(self._event_sink) |
| 82 |
|
| 83 |
|
| 84 |
@pytest.fixture |
| 85 |
def fake_monitor(request): |
| 86 |
""" |
| 87 |
Return a FakeMonitor, which emits the platform device as returned by |
| 88 |
the ``fake_monitor_device`` funcarg on all triggered actions. |
| 89 |
|
| 90 |
.. warning:: |
| 91 |
|
| 92 |
To use this funcarg, you have to provide the ``fake_monitor_device`` |
| 93 |
funcarg! |
| 94 |
""" |
| 95 |
return FakeMonitor(request.getfixturevalue("fake_monitor_device")) |