Connection subclass that can intercept outgoing packets. By interfacing with this connection, we simulate network conditions affecting what the component being tested receives during a test.
| 5 | |
| 6 | |
| 7 | class InterceptingConnection(Connection): |
| 8 | """ |
| 9 | Connection subclass that can intercept outgoing packets. |
| 10 | |
| 11 | By interfacing with this connection, we simulate network conditions |
| 12 | affecting what the component being tested receives during a test. |
| 13 | |
| 14 | """ |
| 15 | |
| 16 | def __init__(self, *args, **kwargs): |
| 17 | super().__init__(*args, **kwargs) |
| 18 | self.socket = InterceptingSocket(self.socket) |
| 19 | |
| 20 | @contextlib.contextmanager |
| 21 | def delay_frames_sent(self, delay): |
| 22 | """ |
| 23 | Add a delay before sending frames. |
| 24 | |
| 25 | Delays cumulate: they're added before every frame or before EOF. |
| 26 | |
| 27 | """ |
| 28 | assert self.socket.delay_sendall is None |
| 29 | self.socket.delay_sendall = delay |
| 30 | try: |
| 31 | yield |
| 32 | finally: |
| 33 | self.socket.delay_sendall = None |
| 34 | |
| 35 | @contextlib.contextmanager |
| 36 | def delay_eof_sent(self, delay): |
| 37 | """ |
| 38 | Add a delay before sending EOF. |
| 39 | |
| 40 | Delays cumulate: they're added before every frame or before EOF. |
| 41 | |
| 42 | """ |
| 43 | assert self.socket.delay_shutdown is None |
| 44 | self.socket.delay_shutdown = delay |
| 45 | try: |
| 46 | yield |
| 47 | finally: |
| 48 | self.socket.delay_shutdown = None |
| 49 | |
| 50 | @contextlib.contextmanager |
| 51 | def drop_frames_sent(self): |
| 52 | """ |
| 53 | Prevent frames from being sent. |
| 54 | |
| 55 | Since TCP is reliable, sending frames or EOF afterwards is unrealistic. |
| 56 | |
| 57 | """ |
| 58 | assert not self.socket.drop_sendall |
| 59 | self.socket.drop_sendall = True |
| 60 | try: |
| 61 | yield |
| 62 | finally: |
| 63 | self.socket.drop_sendall = False |
| 64 |