Debian Codegraph @

tests/plugins/fake_monitor.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2012 Sebastian Wiesner <[email protected]>
3
4 # This library is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU Lesser General Public License as published by the
6 # Free Software Foundation; either version 2.1 of the License, or (at your
7 # option) any later version.
8
9 # This library is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 # for more details.
13
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with this library; if not, write to the Free Software Foundation,
16 # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
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 # isort: STDLIB
31 import os
32 from select import select
33
34 # isort: THIRDPARTY
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"))