Coverage for tests/cli/conftest.py: 92%

107 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1import os 

2import select 

3import signal 

4import subprocess 

5import threading 

6import time 

7from collections.abc import Generator 

8from contextlib import contextmanager, suppress 

9from pathlib import Path 

10from textwrap import dedent 

11from typing import Any 

12 

13import httpx2 

14import pytest 

15 

16from faststream import FastStream 

17from faststream._internal._compat import IS_WINDOWS 

18from tests.cli import interfaces 

19 

20 

21@pytest.fixture() 

22def broker() -> Any: 

23 # separate import from e2e tests 

24 from faststream.rabbit import RabbitBroker 

25 

26 return RabbitBroker() 

27 

28 

29@pytest.fixture() 

30def app_without_logger(broker: Any) -> FastStream: 

31 return FastStream(broker, logger=None) 

32 

33 

34@pytest.fixture() 

35def app_without_broker() -> FastStream: 

36 return FastStream() 

37 

38 

39@pytest.fixture() 

40def app(broker: Any) -> FastStream: 

41 return FastStream(broker) 

42 

43 

44@pytest.fixture() 

45def faststream_tmp_path(tmp_path: "Path") -> Any: 

46 faststream_tmp = tmp_path / "faststream_templates" 

47 faststream_tmp.mkdir(exist_ok=True) 

48 return faststream_tmp 

49 

50 

51@pytest.fixture() 

52def generate_template( 

53 faststream_tmp_path: "Path", 

54) -> interfaces.GenerateTemplateFactory: 

55 @contextmanager 

56 def factory( 

57 code: str, 

58 filename: str = "temp_app.py", 

59 ) -> Generator["Path", None, None]: 

60 file_path: Path = faststream_tmp_path / filename 

61 cleaned_code = dedent(code).strip() 

62 

63 file_path.write_text(cleaned_code, encoding="utf-8") 

64 

65 try: 

66 yield file_path 

67 finally: 

68 file_path.unlink(missing_ok=True) 

69 

70 return factory 

71 

72 

73class CLIThread: 

74 def __init__( 

75 self, 

76 command: tuple[str, ...], 

77 env: dict[str, str], 

78 ) -> None: 

79 self.process = subprocess.Popen( 

80 command, 

81 stderr=subprocess.PIPE, 

82 text=True, 

83 shell=False, 

84 env=env, 

85 ) 

86 self.running = True 

87 self.started = False 

88 

89 self.stderr = "" 

90 

91 self.__std_poll_thread = threading.Thread(target=self._poll_std) 

92 self.__std_poll_thread.start() 

93 

94 def _poll_std(self) -> None: 

95 assert self.process.stderr 

96 

97 if IS_WINDOWS: 

98 return 

99 

100 while self.running: 

101 # sampled before select: an exit seen only after its timeout would end the 

102 # loop while readline still buffers lines that select cannot see 

103 exited = self.process.poll() is not None 

104 rlist, _, _ = select.select([self.process.stderr], [], [], 0.1) 

105 if rlist: 

106 self.started = True 

107 

108 if line := self.process.stderr.readline(): 

109 self.stderr += line.strip() 

110 

111 else: 

112 break 

113 

114 elif exited: 114 ↛ 115line 114 didn't jump to line 115 because the condition on line 114 was never true

115 break 

116 

117 def wait_for_stderr(self, message: str, timeout: float = 2.0) -> bool: 

118 assert self.process.stderr 

119 

120 if message in self.stderr: 

121 return True 

122 

123 expiration_time = time.time() + timeout 

124 

125 while time.time() < expiration_time: 

126 time.sleep(0.1) 

127 if message in self.stderr: 

128 return True 

129 

130 if self.process.returncode is not None: 

131 return message in self.process.stderr.read() 

132 

133 return False 

134 

135 def wait(self, timeout: float) -> None: 

136 self.process.wait(timeout) 

137 # the process can exit before the poll thread drains its stderr pipe 

138 self.__std_poll_thread.join(timeout) 

139 

140 def wait_for_http(self, url: str, timeout: float = 10.0) -> None: 

141 deadline = time.monotonic() + timeout 

142 

143 with httpx2.Client(timeout=0.5, trust_env=False) as client: 

144 while time.monotonic() < deadline: 144 ↛ 152line 144 didn't jump to line 152

145 with suppress(httpx2.ConnectError, httpx2.TimeoutException): 

146 client.get(url).raise_for_status() 

147 return 

148 if self.process.poll() is not None: 148 ↛ 149line 148 didn't jump to line 149 because the condition on line 148 was never true

149 break 

150 time.sleep(0.05) 

151 

152 pytest.fail( 

153 f"CLI did not serve {url} within {timeout}s " 

154 f"(exit code: {self.process.poll()}). Stderr:\n{self.stderr}", 

155 ) 

156 

157 def signint(self) -> None: 

158 if IS_WINDOWS: 

159 self.process.terminate() 

160 else: 

161 self.process.send_signal(signal.SIGINT) 

162 

163 def stop(self) -> None: 

164 self.process.terminate() 

165 

166 self.running = False 

167 with suppress(Exception): 

168 self.__std_poll_thread.join() 

169 

170 try: 

171 self.wait(5) 

172 

173 except subprocess.TimeoutExpired: 

174 self.process.kill() 

175 self.process.wait() 

176 

177 assert self.process.stderr 

178 self.process.stderr.close() 

179 

180 

181@pytest.fixture() 

182def faststream_cli( 

183 faststream_tmp_path: Path, 

184) -> interfaces.FastStreamCLIFactory: 

185 @contextmanager 

186 def cli_factory( 

187 *cmd: str, 

188 wait_time: float = 2.0, 

189 extra_env: dict[str, str] | None = None, 

190 readiness_url: str | None = None, 

191 ) -> Generator[CLIThread, None, None]: 

192 env = ( 

193 os.environ.copy() 

194 | { 

195 "PATH": f"{faststream_tmp_path}:{os.environ['PATH']}", 

196 "PYTHONPATH": str(faststream_tmp_path), 

197 } 

198 | (extra_env or {}) 

199 ) 

200 

201 cli = CLIThread(cmd, env) 

202 

203 wait_for_startup(cli, wait_time) 

204 

205 try: 

206 if readiness_url is not None: 

207 cli.wait_for_http(readiness_url) 

208 yield cli 

209 finally: 

210 cli.stop() 

211 

212 return cli_factory 

213 

214 

215def wait_for_startup( 

216 cli: CLIThread, 

217 timeout: float = 10, 

218 check_interval: float = 0.1, 

219) -> None: 

220 start_time = time.time() 

221 

222 while time.time() - start_time < timeout: 

223 if cli.started: 

224 return 

225 

226 if cli.process.poll() is not None: 226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true

227 return 

228 

229 time.sleep(check_interval) 

230 

231 return