|
| 1 | +# Copyright 2024 Hathor Labs |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from collections.abc import Mapping, Sequence |
| 16 | +from typing import AnyStr |
| 17 | + |
| 18 | +from twisted.internet.interfaces import IProcessProtocol, IProcessTransport |
| 19 | +from twisted.internet.task import Clock |
| 20 | +from twisted.internet.testing import MemoryReactor as TwistedMemoryReactor |
| 21 | + |
| 22 | + |
| 23 | +class MemoryReactor(TwistedMemoryReactor): |
| 24 | + """A drop-in replacement for Twisted's own MemoryReactor that adds support for IReactorProcess.""" |
| 25 | + |
| 26 | + def run(self) -> None: |
| 27 | + """ |
| 28 | + We have to override TwistedMemoryReactor.run() because the original Twisted implementation weirdly calls stop() |
| 29 | + inside run(), and we need the reactor running during our tests. |
| 30 | + """ |
| 31 | + self.running = True |
| 32 | + |
| 33 | + def spawnProcess( |
| 34 | + self, |
| 35 | + processProtocol: IProcessProtocol, |
| 36 | + executable: bytes | str, |
| 37 | + args: Sequence[bytes | str], |
| 38 | + env: Mapping[AnyStr, AnyStr] | None = None, |
| 39 | + path: bytes | str | None = None, |
| 40 | + uid: int | None = None, |
| 41 | + gid: int | None = None, |
| 42 | + usePTY: bool = False, |
| 43 | + childFDs: Mapping[int, int | str] | None = None, |
| 44 | + ) -> IProcessTransport: |
| 45 | + raise NotImplementedError |
| 46 | + |
| 47 | + |
| 48 | +class MemoryReactorClock(MemoryReactor, Clock): |
| 49 | + """A drop-in replacement for Twisted's own MemoryReactorClock that adds support for IReactorProcess.""" |
| 50 | + |
| 51 | + def __init__(self) -> None: |
| 52 | + MemoryReactor.__init__(self) |
| 53 | + Clock.__init__(self) |
0 commit comments