Coverage for tests/utils/fake_rpc_server.py: 99%

67 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 19:49 +0000

1import json 

2import logging 

3import threading 

4 

5from time import sleep 

6 

7from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer 

8from typing import Any 

9from typing_extensions import override 

10 

11logger: logging.Logger = logging.getLogger("FakeRpcServer") 

12 

13 

14class FakeRpcHandler(BaseHTTPRequestHandler): 

15 """Answers the json rpc requests of a poller. A subclass gives the result of the response.""" 

16 

17 server: "FakeRpcServer" # type: ignore[assignment] 

18 

19 def build_result(self, height: int, method: str) -> dict[str, Any]: 

20 """Build the result of a response. 

21 

22 :param int height: height of the response, a new one at each request. 

23 :param str method: json rpc method that was called. 

24 :returns dict[str, Any]: result of the json rpc response. 

25 """ 

26 raise NotImplementedError 

27 

28 def do_POST(self) -> None: 

29 """Answer a request with the result of the subclass.""" 

30 try: 

31 length: int = int(self.headers.get("Content-Length", "0")) 

32 body: dict[str, Any] = json.loads(self.rfile.read(length) or b"{}") 

33 method: str = str(body.get("method", "")) 

34 height: int = self.server.next_height(method) 

35 if self.server.response_delay > 0: 

36 sleep(self.server.response_delay) 

37 response: dict[str, Any] = {"jsonrpc": "2.0", "id": body.get("id", "0"), "result": self.build_result(height, method)} 

38 data: bytes = json.dumps(response).encode() 

39 self.send_response(200) 

40 self.send_header("Content-Type", "application/json") 

41 self.send_header("Content-Length", str(len(data))) 

42 # the handler answers in HTTP/1.0 and closes the connection after the response: the http client of monero keeps a connection 

43 # open unless the response says "close", and the next request could go to the socket that the server closed, which ends in 

44 # "no response" 

45 self.send_header("Connection", "close") 

46 self.end_headers() 

47 self.wfile.write(data) 

48 except Exception as e: 

49 # a request that is not json (the connection probes the server too) 

50 logger.debug(f"Request not answered: {e}") 

51 self.send_error(404) 

52 

53 @override 

54 def log_message(self, format: str, *args: Any) -> None: 

55 pass 

56 

57 

58class FakeRpcServer(ThreadingHTTPServer): 

59 """A rpc server for unit tests, that needs no node or wallet: every request gets a new height, so the poller of what is tested 

60 has always something to notify. 

61 

62 Use it as a context manager. 

63 """ 

64 

65 def __init__(self, handler: type[FakeRpcHandler], first_height: int = 100, response_delay: float = 0.0) -> None: 

66 """Initialize a new FakeRpcServer. 

67 

68 :param type[FakeRpcHandler] handler: handler that answers the requests. 

69 :param int first_height: height of the first response. 

70 :param float response_delay: seconds that the server takes to answer a request, to have requests in flight. 

71 """ 

72 super().__init__(("127.0.0.1", 0), handler) 

73 self._first_height: int = first_height 

74 self._height: int = first_height 

75 self.response_delay: float = response_delay 

76 self._lock: threading.Lock = threading.Lock() 

77 self._methods: list[str] = [] 

78 self._thread: threading.Thread = threading.Thread(target=self.serve_forever, daemon=True) 

79 

80 @property 

81 def uri(self) -> str: 

82 """Uri of the server. 

83 

84 :returns str: uri to give to the rpc client. 

85 """ 

86 return f"http://127.0.0.1:{self.server_address[1]}" 

87 

88 @property 

89 def num_requests(self) -> int: 

90 """Number of requests received so far. 

91 

92 :returns int: number of requests received. 

93 """ 

94 return self._height - self._first_height 

95 

96 @property 

97 def methods(self) -> list[str]: 

98 """Json rpc methods that were called so far, in the order of the requests. 

99 

100 :returns list[str]: the methods. 

101 """ 

102 with self._lock: 

103 return list(self._methods) 

104 

105 def next_height(self, method: str = "") -> int: 

106 """Get the height of the next response, and take note of the method that asked for it. 

107 

108 :param str method: json rpc method of the request. 

109 :returns int: new height. 

110 """ 

111 with self._lock: 

112 self._height += 1 

113 self._methods.append(method) 

114 return self._height 

115 

116 @override 

117 def __enter__(self) -> "FakeRpcServer": 

118 self._thread.start() 

119 return self 

120 

121 @override 

122 def __exit__(self, *args: Any) -> None: 

123 self.shutdown() 

124 self.server_close() 

125 self._thread.join(timeout=5)