| 1 |
"""The warm-session client, and the frames it speaks. |
| 2 |
|
| 3 |
What is asserted here is the client's half of the contract: which invocations |
| 4 |
belong to a session, what it does when none is running, and that a response it |
| 5 |
is handed arrives on the caller's streams byte for byte. The stub server below |
| 6 |
is built on `protocol` rather than on a copy of it, so the frames these tests |
| 7 |
pin are the ones the real server sends. |
| 8 |
""" |
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
import importlib.util |
| 13 |
import io |
| 14 |
import os |
| 15 |
import shutil |
| 16 |
import socket |
| 17 |
import subprocess |
| 18 |
import sys |
| 19 |
import tempfile |
| 20 |
import threading |
| 21 |
from importlib.metadata import version |
| 22 |
from pathlib import Path |
| 23 |
from types import ModuleType |
| 24 |
from typing import Any, Callable, Iterator, Sequence |
| 25 |
|
| 26 |
import pytest |
| 27 |
|
| 28 |
from harlequin.hsql import client, protocol, session |
| 29 |
from harlequin.hsql.diagnostics import ExitCode |
| 30 |
|
| 31 |
HAS_UNIX_SOCKETS = hasattr(socket, "AF_UNIX") |
| 32 |
|
| 33 |
needs_unix_sockets = pytest.mark.skipif( |
| 34 |
not HAS_UNIX_SOCKETS, reason="hsql sessions are POSIX-only" |
| 35 |
) |
| 36 |
|
| 37 |
|
| 38 |
# --- which invocations belong to a session ----------------------------------- |
| 39 |
|
| 40 |
|
| 41 |
@pytest.mark.parametrize( |
| 42 |
"argv,environ,expected", |
| 43 |
[ |
| 44 |
([], {}, None), |
| 45 |
(["-c", "select 1"], {}, None), |
| 46 |
(["-c", "select 1"], {"HSQL_SESSION": ""}, None), |
| 47 |
(["-c", "select 1"], {"HSQL_SESSION": "prod"}, ("prod", False)), |
| 48 |
(["--session", "prod", "-c", "x"], {}, ("prod", True)), |
| 49 |
(["--session=prod", "-c", "x"], {}, ("prod", True)), |
| 50 |
# a typed name beats an ambient one: it is the more specific of the two |
| 51 |
(["--session", "here"], {"HSQL_SESSION": "there"}, ("here", True)), |
| 52 |
# last wins, as it does for every option click parses |
| 53 |
(["--session", "first", "--session", "last"], {}, ("last", True)), |
| 54 |
(["--session=first", "--session=last"], {}, ("last", True)), |
| 55 |
# no value: the client refuses it by name rather than click, which |
| 56 |
# does not know the option yet |
| 57 |
(["--session"], {}, ("", True)), |
| 58 |
# after `--` everything is an argument, so this is a connection string |
| 59 |
(["--", "--session", "prod"], {}, None), |
| 60 |
# the other role: a server is never a client, whatever the shell says |
| 61 |
(["--serve", "prod"], {"HSQL_SESSION": "prod"}, None), |
| 62 |
(["--serve=prod", "-a", "sqlite"], {"HSQL_SESSION": "other"}, None), |
| 63 |
# and a typed `--session` beside it is left for the command to refuse |
| 64 |
(["--session", "a", "--serve", "b"], {}, None), |
| 65 |
(["--", "--serve", "prod"], {"HSQL_SESSION": "prod"}, ("prod", False)), |
| 66 |
], |
| 67 |
) |
| 68 |
def test_the_session_an_invocation_names( |
| 69 |
argv: list[str], |
| 70 |
environ: dict[str, str], |
| 71 |
expected: tuple[str, bool] | None, |
| 72 |
) -> None: |
| 73 |
named = session.requested_session(argv, environ) |
| 74 |
if expected is None: |
| 75 |
assert named is None |
| 76 |
else: |
| 77 |
assert named is not None |
| 78 |
assert (named.name, named.explicit) == expected |
| 79 |
|
| 80 |
|
| 81 |
@pytest.mark.parametrize( |
| 82 |
"argv,expected", |
| 83 |
[ |
| 84 |
([], []), |
| 85 |
(["-c", "select 1"], ["-c", "select 1"]), |
| 86 |
(["--session", "prod", "-c", "x"], ["-c", "x"]), |
| 87 |
(["-c", "x", "--session=prod"], ["-c", "x"]), |
| 88 |
(["--session", "prod", "--", "db"], ["--", "db"]), |
| 89 |
(["--", "--session", "prod"], ["--", "--session", "prod"]), |
| 90 |
], |
| 91 |
) |
| 92 |
def test_the_clients_own_flag_does_not_reach_the_server( |
| 93 |
argv: list[str], expected: list[str] |
| 94 |
) -> None: |
| 95 |
"""Everything else is forwarded opaquely, so that one parser sees it.""" |
| 96 |
assert session.without_session_option(argv) == expected |
| 97 |
|
| 98 |
|
| 99 |
@pytest.mark.parametrize( |
| 100 |
"name,valid", |
| 101 |
[ |
| 102 |
("prod", True), |
| 103 |
("a", True), |
| 104 |
("A_b-2", True), |
| 105 |
("x" * session.MAX_NAME_LENGTH, True), |
| 106 |
("", False), |
| 107 |
("x" * (session.MAX_NAME_LENGTH + 1), False), |
| 108 |
("../../etc/passwd", False), |
| 109 |
("with space", False), |
| 110 |
("dot.name", False), |
| 111 |
], |
| 112 |
) |
| 113 |
def test_a_name_that_cannot_escape_the_directory(name: str, valid: bool) -> None: |
| 114 |
assert session.is_valid_name(name) is valid |
| 115 |
|
| 116 |
|
| 117 |
@needs_unix_sockets |
| 118 |
def test_the_socket_lives_under_the_runtime_dir() -> None: |
| 119 |
assert session.socket_path("prod", {"XDG_RUNTIME_DIR": "/run/user/7"}) == ( |
| 120 |
"/run/user/7/hsql/prod.sock" |
| 121 |
) |
| 122 |
|
| 123 |
|
| 124 |
@needs_unix_sockets |
| 125 |
def test_the_fallback_runtime_dir_is_per_user() -> None: |
| 126 |
"""The common path, not the exotic one: macOS, WSL2 without systemd, and a |
| 127 |
container all arrive here.""" |
| 128 |
assert session.runtime_dir({"TMPDIR": "/tmp/x"}) == f"/tmp/x/hsql-{os.getuid()}" |
| 129 |
assert session.runtime_dir({}) == f"/tmp/hsql-{os.getuid()}" |
| 130 |
|
| 131 |
|
| 132 |
@needs_unix_sockets |
| 133 |
def test_a_directory_only_this_user_can_reach_is_accepted(tmp_path: Path) -> None: |
| 134 |
private = tmp_path / "run" |
| 135 |
private.mkdir() |
| 136 |
os.chmod(private, 0o700) |
| 137 |
session.check_runtime_dir(str(private)) |
| 138 |
|
| 139 |
|
| 140 |
@needs_unix_sockets |
| 141 |
@pytest.mark.parametrize("mode", [0o777, 0o750, 0o701]) |
| 142 |
def test_a_directory_someone_else_can_reach_is_refused( |
| 143 |
mode: int, tmp_path: Path |
| 144 |
) -> None: |
| 145 |
"""What a client sends is argv, the cwd and piped stdin, and argv can carry |
| 146 |
a password. Under the TMPDIR fallback nothing guarantees the directory, so |
| 147 |
both halves check it rather than trusting their own mkdir.""" |
| 148 |
shared = tmp_path / "run" |
| 149 |
shared.mkdir() |
| 150 |
# after mkdir, so that the umask does not decide what this tests |
| 151 |
os.chmod(shared, mode) |
| 152 |
with pytest.raises(session.UnsafeRuntimeDir): |
| 153 |
session.check_runtime_dir(str(shared)) |
| 154 |
|
| 155 |
|
| 156 |
@needs_unix_sockets |
| 157 |
def test_a_runtime_dir_that_is_not_a_directory_is_refused(tmp_path: Path) -> None: |
| 158 |
impostor = tmp_path / "run" |
| 159 |
impostor.write_text("") |
| 160 |
with pytest.raises(session.UnsafeRuntimeDir): |
| 161 |
session.check_runtime_dir(str(impostor)) |
| 162 |
|
| 163 |
|
| 164 |
@needs_unix_sockets |
| 165 |
def test_a_symlink_to_a_private_directory_is_refused(tmp_path: Path) -> None: |
| 166 |
"""A following check can be passed with a link at a directory the user does |
| 167 |
own privately, and repointed before the connect. The link owner controls it |
| 168 |
in a sticky `/tmp`; a real directory there they cannot touch.""" |
| 169 |
private = tmp_path / "private" |
| 170 |
private.mkdir() |
| 171 |
os.chmod(private, 0o700) |
| 172 |
link = tmp_path / "link" |
| 173 |
link.symlink_to(private) |
| 174 |
with pytest.raises(session.UnsafeRuntimeDir): |
| 175 |
session.check_runtime_dir(str(link)) |
| 176 |
|
| 177 |
|
| 178 |
# --- the frames -------------------------------------------------------------- |
| 179 |
|
| 180 |
|
| 181 |
@pytest.mark.parametrize( |
| 182 |
"items", |
| 183 |
[[], [b""], [b"one"], [b"", b"two", b""], [b"\xff\xfe", b"\x00" * 100]], |
| 184 |
) |
| 185 |
def test_a_sequence_survives_the_round_trip(items: list[bytes]) -> None: |
| 186 |
assert protocol.unpack_strings(protocol.pack_strings(items)) == items |
| 187 |
|
| 188 |
|
| 189 |
@pytest.mark.parametrize( |
| 190 |
"payload", |
| 191 |
[b"", b"\x00\x00\x00\x01", b"\x00\x00\x00\x01\x00\x00\x00\x09ab", b"\x00" * 8], |
| 192 |
) |
| 193 |
def test_a_sequence_this_cannot_read_is_an_error(payload: bytes) -> None: |
| 194 |
with pytest.raises(protocol.ProtocolError): |
| 195 |
protocol.unpack_strings(payload) |
| 196 |
|
| 197 |
|
| 198 |
@pytest.mark.parametrize("stdin", [None, b"", b"select 1;\n", b"\xff\xfe"]) |
| 199 |
def test_a_request_survives_the_round_trip(stdin: bytes | None) -> None: |
| 200 |
packed = protocol.pack_request( |
| 201 |
argv=["-c", "select 'ü'", "\udcff"], |
| 202 |
cwd="/some/where", |
| 203 |
environ={"NO_COLOR": ""}, |
| 204 |
stdin=stdin, |
| 205 |
request_id=b"\x00\xff seven", |
| 206 |
) |
| 207 |
request = protocol.unpack_request(packed) |
| 208 |
# the surrogate is a file name the filesystem accepts and UTF-8 does not, |
| 209 |
# which `os.fsencode` carries and a plain encode would refuse |
| 210 |
assert request.argv == ["-c", "select 'ü'", "\udcff"] |
| 211 |
assert request.cwd == "/some/where" |
| 212 |
assert request.environ == {"NO_COLOR": ""} |
| 213 |
assert request.stdin == stdin |
| 214 |
assert request.request_id == b"\x00\xff seven" |
| 215 |
|
| 216 |
|
| 217 |
@pytest.mark.parametrize("request_id", [b"", b"short", b"far too long an id"]) |
| 218 |
def test_a_request_whose_id_could_not_name_it_is_refused(request_id: bytes) -> None: |
| 219 |
"""A cancel names a request by its id, and the server keys what it holds |
| 220 |
by one: an id-less request would be uncancellable, and two of them would |
| 221 |
cross-wire in its bookkeeping.""" |
| 222 |
packed = protocol.pack_request( |
| 223 |
argv=[], cwd="/", environ={}, stdin=None, request_id=request_id |
| 224 |
) |
| 225 |
with pytest.raises(protocol.ProtocolError, match="8-byte id"): |
| 226 |
protocol.unpack_request(packed) |
| 227 |
|
| 228 |
|
| 229 |
def test_every_request_names_itself_differently() -> None: |
| 230 |
"""A cancel names one request, so two live at once may not share an id.""" |
| 231 |
ids = {protocol.new_request_id() for _ in range(1000)} |
| 232 |
assert len(ids) == 1000 |
| 233 |
assert all(len(one) == protocol.REQUEST_ID_BYTES for one in ids) |
| 234 |
|
| 235 |
|
| 236 |
@pytest.mark.parametrize( |
| 237 |
"stdout_isatty,stderr_isatty", |
| 238 |
[(False, False), (True, False), (False, True), (True, True)], |
| 239 |
) |
| 240 |
def test_a_request_carries_which_streams_are_terminals( |
| 241 |
stdout_isatty: bool, stderr_isatty: bool |
| 242 |
) -> None: |
| 243 |
"""`--color auto` reads `sys.stdout.isatty()`, and on the server every |
| 244 |
stream is a buffer, so only the client can answer this.""" |
| 245 |
request = protocol.unpack_request( |
| 246 |
protocol.pack_request( |
| 247 |
argv=[], |
| 248 |
cwd="/", |
| 249 |
environ={}, |
| 250 |
stdin=None, |
| 251 |
request_id=protocol.new_request_id(), |
| 252 |
stdout_isatty=stdout_isatty, |
| 253 |
stderr_isatty=stderr_isatty, |
| 254 |
) |
| 255 |
) |
| 256 |
assert request.stdout_isatty is stdout_isatty |
| 257 |
assert request.stderr_isatty is stderr_isatty |
| 258 |
|
| 259 |
|
| 260 |
def test_a_request_carries_only_the_environment_it_declares() -> None: |
| 261 |
"""Not the caller's whole environment: an adapter option's `envvar` |
| 262 |
resolves against the server's, and forwarding one is a credential leak. |
| 263 |
|
| 264 |
`TERM` is not on the list: nothing in the output path reads it.""" |
| 265 |
forwarded = protocol.forwarded_environ( |
| 266 |
{"TERM": "dumb", "PGPASSWORD": "hunter2", "NO_COLOR": ""} |
| 267 |
) |
| 268 |
assert forwarded == {"NO_COLOR": ""} |
| 269 |
|
| 270 |
|
| 271 |
def test_a_request_carries_the_config_file_the_caller_named() -> None: |
| 272 |
"""`HARLEQUIN_CONFIG_PATH` is `--config-path` spelled as an environment |
| 273 |
variable, and a session that honored one and ignored the other would read |
| 274 |
a config file neither of them asked for.""" |
| 275 |
forwarded = protocol.forwarded_environ( |
| 276 |
{"HARLEQUIN_CONFIG_PATH": "/p/hsql.toml", "HOME": "/home/ted"} |
| 277 |
) |
| 278 |
assert forwarded == {"HARLEQUIN_CONFIG_PATH": "/p/hsql.toml"} |
| 279 |
|
| 280 |
|
| 281 |
@pytest.mark.parametrize( |
| 282 |
"argv,asks", |
| 283 |
[ |
| 284 |
(["--session-status"], True), |
| 285 |
# click refuses the `=` form either way; one this missed would reach |
| 286 |
# the session as a request and wait for a running query to say so |
| 287 |
(["--session-status=1"], True), |
| 288 |
(["--session", "prod", "--session-status"], True), |
| 289 |
(["-c", "select 1"], False), |
| 290 |
(["--", "--session-status"], False), |
| 291 |
(["-c", "--session-status"], True), |
| 292 |
], |
| 293 |
) |
| 294 |
def test_which_invocations_request_the_servers_status( |
| 295 |
argv: list[str], asks: bool |
| 296 |
) -> None: |
| 297 |
"""A scan, as everywhere else the client reads argv before click exists. |
| 298 |
A `--session-status` that is really an option's value reaches the server |
| 299 |
instead of the parser, and the server refuses it by name.""" |
| 300 |
assert session.requests_status(argv) is asks |
| 301 |
|
| 302 |
|
| 303 |
def test_an_absent_no_color_arrives_absent() -> None: |
| 304 |
"""It is read for its presence, so an empty one is not the same as none.""" |
| 305 |
assert protocol.forwarded_environ({"TERM": "dumb"}) == {} |
| 306 |
|
| 307 |
|
| 308 |
def test_frames_survive_a_socket() -> None: |
| 309 |
left, right = socket.socketpair() |
| 310 |
with left, right: |
| 311 |
protocol.send_frame(left, protocol.STDOUT, b"one") |
| 312 |
protocol.send_frame(left, protocol.EXIT) |
| 313 |
left.close() |
| 314 |
assert protocol.recv_frame(right) == (protocol.STDOUT, b"one") |
| 315 |
assert protocol.recv_frame(right) == (protocol.EXIT, b"") |
| 316 |
assert protocol.recv_frame(right) is None |
| 317 |
|
| 318 |
|
| 319 |
def test_a_connection_that_ends_mid_frame_is_an_error() -> None: |
| 320 |
left, right = socket.socketpair() |
| 321 |
with left, right: |
| 322 |
left.sendall(protocol.HEADER.pack(protocol.STDOUT, 10) + b"abc") |
| 323 |
left.close() |
| 324 |
with pytest.raises(protocol.ProtocolError): |
| 325 |
protocol.recv_frame(right) |
| 326 |
|
| 327 |
|
| 328 |
def test_a_frame_too_large_to_be_real_is_refused() -> None: |
| 329 |
"""A length is four bytes from a peer, so it may not become an allocation.""" |
| 330 |
left, right = socket.socketpair() |
| 331 |
with left, right: |
| 332 |
left.sendall(protocol.HEADER.pack(protocol.STDOUT, protocol.MAX_PAYLOAD + 1)) |
| 333 |
with pytest.raises(protocol.ProtocolError): |
| 334 |
protocol.recv_frame(right) |
| 335 |
|
| 336 |
|
| 337 |
# --- the client, against a stub server --------------------------------------- |
| 338 |
|
| 339 |
|
| 340 |
class StubServer: |
| 341 |
"""A session's connections, built on the real frames. |
| 342 |
|
| 343 |
Records what each one carried -- a request, a status ask, or a cancel -- |
| 344 |
so a test can assert what the client forwarded as well as what it printed. |
| 345 |
Every connection is answered rather than one, because a client that |
| 346 |
interrupts its query opens a second one to cancel it. |
| 347 |
""" |
| 348 |
|
| 349 |
def __init__( |
| 350 |
self, |
| 351 |
path: str, |
| 352 |
*, |
| 353 |
advertises: str, |
| 354 |
frames: Sequence[tuple[int, bytes]], |
| 355 |
cancel_frames: Sequence[tuple[int, bytes]] = (), |
| 356 |
) -> None: |
| 357 |
self.path = path |
| 358 |
self.request: protocol.Request | None = None |
| 359 |
self.status_ask: list[str] | None = None |
| 360 |
self.cancelled: bytes | None = None |
| 361 |
self._version = advertises |
| 362 |
self._frames = list(frames) |
| 363 |
self._cancel_frames = list(cancel_frames) or [ |
| 364 |
(protocol.EXIT, bytes([ExitCode.INTERRUPT])) |
| 365 |
] |
| 366 |
self._closing = False |
| 367 |
self._listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 368 |
self._listener.bind(path) |
| 369 |
self._listener.listen(2) |
| 370 |
# so that `close()` is prompt whether or not anyone ever connected |
| 371 |
self._listener.settimeout(0.05) |
| 372 |
self._thread = threading.Thread(target=self._serve, daemon=True) |
| 373 |
self._thread.start() |
| 374 |
|
| 375 |
def _serve(self) -> None: |
| 376 |
while not self._closing: |
| 377 |
try: |
| 378 |
connection, _ = self._listener.accept() |
| 379 |
except TimeoutError: |
| 380 |
continue |
| 381 |
except OSError: |
| 382 |
return |
| 383 |
with connection: |
| 384 |
self._answer(connection) |
| 385 |
|
| 386 |
def _answer(self, connection: socket.socket) -> None: |
| 387 |
try: |
| 388 |
protocol.send_frame( |
| 389 |
connection, protocol.HELLO, self._version.encode("utf-8") |
| 390 |
) |
| 391 |
frame = protocol.recv_frame(connection) |
| 392 |
answer = self._frames |
| 393 |
if frame is not None and frame[0] == protocol.REQUEST: |
| 394 |
self.request = protocol.unpack_request(frame[1]) |
| 395 |
elif frame is not None and frame[0] == protocol.STATUS: |
| 396 |
self.status_ask = protocol.unpack_status(frame[1]) |
| 397 |
elif frame is not None and frame[0] == protocol.CANCEL: |
| 398 |
self.cancelled = frame[1] |
| 399 |
answer = self._cancel_frames |
| 400 |
for kind, payload in answer: |
| 401 |
protocol.send_frame(connection, kind, payload) |
| 402 |
except OSError: |
| 403 |
# a client that stopped reading -- a version it refused to be |
| 404 |
# served by, or one that died -- which the real server also drops |
| 405 |
return |
| 406 |
|
| 407 |
def close(self) -> None: |
| 408 |
self._closing = True |
| 409 |
self._thread.join(timeout=5) |
| 410 |
self._listener.close() |
| 411 |
|
| 412 |
|
| 413 |
Serve = Callable[..., StubServer] |
| 414 |
|
| 415 |
|
| 416 |
@pytest.fixture |
| 417 |
def short_tmp_path() -> Iterator[Path]: |
| 418 |
"""A temp directory a socket path still fits under. |
| 419 |
|
| 420 |
`sun_path` holds 104 bytes on macOS and pytest's `tmp_path` is longer than |
| 421 |
that there before a socket name is added, so every test that binds or |
| 422 |
connects one needs a shorter base than the built-in fixture. |
| 423 |
""" |
| 424 |
base = tempfile.mkdtemp(prefix="hsql-", dir="/tmp") |
| 425 |
yield Path(base) |
| 426 |
shutil.rmtree(base, ignore_errors=True) |
| 427 |
|
| 428 |
|
| 429 |
@pytest.fixture |
| 430 |
def runtime_dir(short_tmp_path: Path) -> str: |
| 431 |
base = str(short_tmp_path) |
| 432 |
os.mkdir(os.path.join(base, "hsql"), mode=0o700) |
| 433 |
return base |
| 434 |
|
| 435 |
|
| 436 |
@pytest.fixture |
| 437 |
def environ(runtime_dir: str) -> dict[str, str]: |
| 438 |
return {"XDG_RUNTIME_DIR": runtime_dir} |
| 439 |
|
| 440 |
|
| 441 |
@pytest.fixture |
| 442 |
def serve(environ: dict[str, str]) -> Iterator[Serve]: |
| 443 |
servers: list[StubServer] = [] |
| 444 |
|
| 445 |
def _serve( |
| 446 |
name: str = "prod", |
| 447 |
*, |
| 448 |
advertises: str = protocol.VERSION, |
| 449 |
frames: Sequence[tuple[int, bytes]] = (), |
| 450 |
cancel_frames: Sequence[tuple[int, bytes]] = (), |
| 451 |
) -> StubServer: |
| 452 |
server = StubServer( |
| 453 |
session.socket_path(name, environ), |
| 454 |
advertises=advertises, |
| 455 |
frames=frames, |
| 456 |
cancel_frames=cancel_frames, |
| 457 |
) |
| 458 |
servers.append(server) |
| 459 |
return server |
| 460 |
|
| 461 |
yield _serve |
| 462 |
for server in servers: |
| 463 |
server.close() |
| 464 |
|
| 465 |
|
| 466 |
def ambient(name: str = "prod") -> session.Session: |
| 467 |
return session.Session(name, explicit=False) |
| 468 |
|
| 469 |
|
| 470 |
def typed(name: str = "prod") -> session.Session: |
| 471 |
return session.Session(name, explicit=True) |
| 472 |
|
| 473 |
|
| 474 |
@needs_unix_sockets |
| 475 |
def test_a_response_reaches_the_caller_byte_for_byte( |
| 476 |
serve: Serve, environ: dict[str, str], capsysbinary: pytest.CaptureFixture[bytes] |
| 477 |
) -> None: |
| 478 |
"""The whole reason bytes cross the wire rather than rows: the client |
| 479 |
cannot format anything, so it cannot disagree with a cold invocation.""" |
| 480 |
server = serve( |
| 481 |
frames=[ |
| 482 |
(protocol.STDOUT, b" a \n---\n"), |
| 483 |
(protocol.STDERR, b"note: something\n"), |
| 484 |
(protocol.STDOUT, b" 1 \n"), |
| 485 |
(protocol.EXIT, bytes([ExitCode.QUERY])), |
| 486 |
] |
| 487 |
) |
| 488 |
assert client.run(typed(), ["-c", "select 1"], environ) == ExitCode.QUERY |
| 489 |
captured = capsysbinary.readouterr() |
| 490 |
assert captured.out == b" a \n---\n 1 \n" |
| 491 |
assert captured.err == b"note: something\n" |
| 492 |
# the server got a request it could read, rather than nothing at all |
| 493 |
assert server.request is not None |
| 494 |
assert server.request.argv == ["-c", "select 1"] |
| 495 |
|
| 496 |
|
| 497 |
@needs_unix_sockets |
| 498 |
def test_the_server_is_sent_the_invocation_and_not_the_clients_flag( |
| 499 |
serve: Serve, environ: dict[str, str] |
| 500 |
) -> None: |
| 501 |
server = serve(frames=[(protocol.EXIT, b"\x00")]) |
| 502 |
assert ( |
| 503 |
client.run( |
| 504 |
typed(), |
| 505 |
["--session", "prod", "-c", "select 1"], |
| 506 |
{**environ, "NO_COLOR": "1", "PGPASSWORD": "hunter2"}, |
| 507 |
) |
| 508 |
== ExitCode.OK |
| 509 |
) |
| 510 |
assert server.request is not None |
| 511 |
assert server.request.argv == ["-c", "select 1"] |
| 512 |
assert server.request.cwd == os.getcwd() |
| 513 |
assert server.request.environ == {"NO_COLOR": "1"} |
| 514 |
assert server.request.stdin is None |
| 515 |
|
| 516 |
|
| 517 |
@needs_unix_sockets |
| 518 |
def test_a_status_ask_is_not_a_request( |
| 519 |
serve: Serve, environ: dict[str, str], capsysbinary: pytest.CaptureFixture[bytes] |
| 520 |
) -> None: |
| 521 |
"""It takes no turn at the session's connection, so it is its own frame |
| 522 |
rather than an invocation the session parses -- and it carries the argv, |
| 523 |
so the session can refuse anything typed beside it.""" |
| 524 |
server = serve( |
| 525 |
frames=[(protocol.STDOUT, b'{"state":"busy"}\n'), (protocol.EXIT, b"\x00")] |
| 526 |
) |
| 527 |
assert ( |
| 528 |
client.run(typed(), ["--session", "prod", "--session-status"], environ) |
| 529 |
== ExitCode.OK |
| 530 |
) |
| 531 |
assert capsysbinary.readouterr().out == b'{"state":"busy"}\n' |
| 532 |
assert server.request is None |
| 533 |
assert server.status_ask == ["--session-status"] |
| 534 |
|
| 535 |
|
| 536 |
@needs_unix_sockets |
| 537 |
def test_a_dash_f_sends_the_bytes_the_server_has_no_stdin_for( |
| 538 |
serve: Serve, environ: dict[str, str], monkeypatch: pytest.MonkeyPatch |
| 539 |
) -> None: |
| 540 |
server = serve(frames=[(protocol.EXIT, b"\x00")]) |
| 541 |
monkeypatch.setattr(sys, "stdin", io.TextIOWrapper(io.BytesIO(b"select 2;\n"))) |
| 542 |
assert client.run(typed(), ["-f", "-"], environ) == ExitCode.OK |
| 543 |
assert server.request is not None |
| 544 |
assert server.request.stdin == b"select 2;\n" |
| 545 |
|
| 546 |
|
| 547 |
@pytest.mark.parametrize( |
| 548 |
"argv,reads", |
| 549 |
[ |
| 550 |
(["-c", "select 1"], False), |
| 551 |
(["-f", "-"], True), |
| 552 |
(["-f-"], True), |
| 553 |
(["--file", "-"], True), |
| 554 |
(["--file=-"], True), |
| 555 |
(["-f", "script.sql"], False), |
| 556 |
# a short cluster, which is the `-tAc` idiom the skill teaches |
| 557 |
(["-tAf", "-"], True), |
| 558 |
(["-tf", "-"], True), |
| 559 |
(["-Af", "-"], True), |
| 560 |
(["-tf-"], True), |
| 561 |
(["-xrtAf", "-"], True), |
| 562 |
(["-tAf", "script.sql"], False), |
| 563 |
# click gives a short option no `=` form: this is a file named `=-` |
| 564 |
(["-f=-"], False), |
| 565 |
# `-c` takes a value, so the `f` after it is part of that value |
| 566 |
(["-cf", "-"], False), |
| 567 |
(["-of", "-"], False), |
| 568 |
# a connection string called `-` is not a file, and comes after `--` |
| 569 |
(["--", "-"], False), |
| 570 |
(["--", "-f", "-"], False), |
| 571 |
], |
| 572 |
) |
| 573 |
def test_which_invocations_need_the_callers_stdin(argv: list[str], reads: bool) -> None: |
| 574 |
assert client._reads_stdin(argv) is reads |
| 575 |
|
| 576 |
|
| 577 |
@needs_unix_sockets |
| 578 |
def test_a_server_from_another_release_is_never_served( |
| 579 |
serve: Serve, environ: dict[str, str], capsys: pytest.CaptureFixture[str] |
| 580 |
) -> None: |
| 581 |
"""Output bytes are hsql's API, and two releases may not agree about them, |
| 582 |
so this refuses rather than falling back -- ambient or not.""" |
| 583 |
serve(advertises="0.0.1", frames=[(protocol.STDOUT, b"nope")]) |
| 584 |
assert client.run(ambient(), ["-c", "select 1"], environ) == ExitCode.USAGE |
| 585 |
captured = capsys.readouterr() |
| 586 |
assert not captured.out |
| 587 |
assert "hsql 0.0.1" in captured.err |
| 588 |
assert "Restart the session" in captured.err |
| 589 |
|
| 590 |
|
| 591 |
@needs_unix_sockets |
| 592 |
def test_a_typed_session_that_is_not_running_fails( |
| 593 |
environ: dict[str, str], capsys: pytest.CaptureFixture[str] |
| 594 |
) -> None: |
| 595 |
"""A name the caller typed is an assertion; running cold against one would |
| 596 |
silently lose the state they were counting on.""" |
| 597 |
assert client.run(typed(), ["-c", "select 1"], environ) == ExitCode.CONNECTION |
| 598 |
assert "no session named 'prod' is running" in capsys.readouterr().err |
| 599 |
|
| 600 |
|
| 601 |
@needs_unix_sockets |
| 602 |
def test_an_ambient_session_that_is_not_running_runs_cold( |
| 603 |
environ: dict[str, str], capsys: pytest.CaptureFixture[str] |
| 604 |
) -> None: |
| 605 |
assert client.run(ambient(), ["-c", "select 1"], environ) is None |
| 606 |
err = capsys.readouterr().err |
| 607 |
assert "running cold" in err |
| 608 |
assert "hsql --serve prod" in err |
| 609 |
|
| 610 |
|
| 611 |
@needs_unix_sockets |
| 612 |
def test_a_name_that_could_name_no_session_is_refused( |
| 613 |
environ: dict[str, str], capsys: pytest.CaptureFixture[str] |
| 614 |
) -> None: |
| 615 |
assert client.run(typed("../etc"), [], environ) == ExitCode.USAGE |
| 616 |
assert "is not a session name" in capsys.readouterr().err |
| 617 |
|
| 618 |
|
| 619 |
def test_a_platform_without_unix_sockets_has_no_sessions( |
| 620 |
monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] |
| 621 |
) -> None: |
| 622 |
"""Native Windows, exercised wherever the tests run. |
| 623 |
|
| 624 |
A typed session is a *usage* error there rather than a connection one: |
| 625 |
nothing is down, and a caller who answers an exit 3 by starting the server |
| 626 |
would answer it forever. An ambient one warns and runs cold, like any other. |
| 627 |
""" |
| 628 |
monkeypatch.delattr(socket, "AF_UNIX", raising=False) |
| 629 |
assert client.run(typed(), ["-c", "select 1"], {}) == ExitCode.USAGE |
| 630 |
assert "native Windows" in capsys.readouterr().err |
| 631 |
assert client.run(ambient(), ["-c", "select 1"], {}) is None |
| 632 |
assert "running cold" in capsys.readouterr().err |
| 633 |
|
| 634 |
|
| 635 |
@needs_unix_sockets |
| 636 |
def test_a_refused_socket_is_reported_and_left_alone( |
| 637 |
environ: dict[str, str], capsys: pytest.CaptureFixture[str] |
| 638 |
) -> None: |
| 639 |
"""A running server also refuses between its `bind()` and its `listen()`, |
| 640 |
and on the BSDs whenever its backlog is full, so a client that deleted the |
| 641 |
file on one refusal would take a live session away from everyone after it. |
| 642 |
The server unlinks a stale socket when it starts.""" |
| 643 |
path = session.socket_path("prod", environ) |
| 644 |
bound = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 645 |
bound.bind(path) |
| 646 |
bound.close() |
| 647 |
assert os.path.exists(path) |
| 648 |
assert client.run(ambient(), [], environ) is None |
| 649 |
assert "no session named 'prod' is running" in capsys.readouterr().err |
| 650 |
assert os.path.exists(path) |
| 651 |
|
| 652 |
|
| 653 |
@needs_unix_sockets |
| 654 |
def test_a_runtime_dir_that_cannot_hold_a_socket_is_a_diagnostic( |
| 655 |
short_tmp_path: Path, capsys: pytest.CaptureFixture[str] |
| 656 |
) -> None: |
| 657 |
"""Any errno from `connect()` other than nothing-is-listening is a |
| 658 |
diagnostic and exit 3, not a traceback.""" |
| 659 |
not_a_directory = short_tmp_path / "file" |
| 660 |
not_a_directory.write_text("") |
| 661 |
environ = {"XDG_RUNTIME_DIR": str(not_a_directory)} |
| 662 |
assert client.run(typed(), ["-c", "select 1"], environ) == ExitCode.CONNECTION |
| 663 |
assert "is unreachable" in capsys.readouterr().err |
| 664 |
|
| 665 |
|
| 666 |
@needs_unix_sockets |
| 667 |
def test_a_socket_path_too_long_to_bind_is_refused_by_name( |
| 668 |
capsys: pytest.CaptureFixture[str], |
| 669 |
) -> None: |
| 670 |
"""`sun_path` is 104 bytes on macOS, and the TMPDIR it supplies is ~50 of |
| 671 |
them, so a name well inside MAX_NAME_LENGTH can still be unreachable.""" |
| 672 |
environ = {"XDG_RUNTIME_DIR": "/tmp/" + "d" * 100} |
| 673 |
assert client.run(typed("x" * 40), ["-c", "select 1"], environ) == ExitCode.USAGE |
| 674 |
message = capsys.readouterr().err |
| 675 |
assert "over the" in message and str(session.MAX_SOCKET_PATH) in message |
| 676 |
|
| 677 |
|
| 678 |
@needs_unix_sockets |
| 679 |
def test_a_directory_someone_else_could_reach_is_never_connected_to( |
| 680 |
short_tmp_path: Path, capsys: pytest.CaptureFixture[str] |
| 681 |
) -> None: |
| 682 |
"""argv can carry a password, so a socket in a directory another user can |
| 683 |
write is one this must not send a request to.""" |
| 684 |
shared = short_tmp_path / "hsql" |
| 685 |
shared.mkdir() |
| 686 |
# after mkdir, so that the umask does not decide what this tests |
| 687 |
os.chmod(shared, 0o777) |
| 688 |
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 689 |
listener.bind(str(shared / "prod.sock")) |
| 690 |
listener.listen(1) |
| 691 |
try: |
| 692 |
assert ( |
| 693 |
client.run( |
| 694 |
typed(), |
| 695 |
["-c", "select 1"], |
| 696 |
{"XDG_RUNTIME_DIR": str(short_tmp_path)}, |
| 697 |
) |
| 698 |
== ExitCode.CONNECTION |
| 699 |
) |
| 700 |
finally: |
| 701 |
listener.close() |
| 702 |
assert "is unreachable" in capsys.readouterr().err |
| 703 |
|
| 704 |
|
| 705 |
def interrupt_once(monkeypatch: pytest.MonkeyPatch) -> None: |
| 706 |
"""Make the first relay raise `KeyboardInterrupt`, as a `Ctrl-C` would. |
| 707 |
|
| 708 |
The second is the cancel's own answer, which the client copies through |
| 709 |
like any other, so the whole exchange runs against the stub. |
| 710 |
""" |
| 711 |
relaying = client._relay |
| 712 |
relayed: list[object] = [] |
| 713 |
|
| 714 |
def relay(connection: Any) -> int: |
| 715 |
relayed.append(connection) |
| 716 |
if len(relayed) == 1: |
| 717 |
raise KeyboardInterrupt |
| 718 |
return relaying(connection) |
| 719 |
|
| 720 |
monkeypatch.setattr(client, "_relay", relay) |
| 721 |
|
| 722 |
|
| 723 |
@needs_unix_sockets |
| 724 |
def test_an_interrupt_stops_the_query_and_exits_the_way_the_cold_path_does( |
| 725 |
serve: Serve, |
| 726 |
environ: dict[str, str], |
| 727 |
monkeypatch: pytest.MonkeyPatch, |
| 728 |
capsys: pytest.CaptureFixture[str], |
| 729 |
) -> None: |
| 730 |
"""A `Ctrl-C` is a cancel naming the request that sent it, on a second |
| 731 |
connection, and then the code the cold path exits with -- silently, since |
| 732 |
this session had something to stop and stopped it.""" |
| 733 |
stub = serve(frames=[(protocol.EXIT, b"\x00")]) |
| 734 |
interrupt_once(monkeypatch) |
| 735 |
assert client.run(typed(), ["-c", "select 1"], environ) == ExitCode.INTERRUPT |
| 736 |
assert stub.request is not None |
| 737 |
assert stub.cancelled == stub.request.request_id |
| 738 |
assert capsys.readouterr().err == "" |
| 739 |
|
| 740 |
|
| 741 |
@needs_unix_sockets |
| 742 |
def test_an_interrupt_while_the_request_is_going_out_still_cancels( |
| 743 |
serve: Serve, environ: dict[str, str], monkeypatch: pytest.MonkeyPatch |
| 744 |
) -> None: |
| 745 |
"""The window between the request leaving and the relay starting: a client |
| 746 |
that exited there would leave the query it had just sent running.""" |
| 747 |
stub = serve(frames=[(protocol.EXIT, b"\x00")]) |
| 748 |
sending = protocol.send_frame |
| 749 |
|
| 750 |
def send_frame(connection: Any, kind: int, payload: bytes = b"") -> None: |
| 751 |
sending(connection, kind, payload) |
| 752 |
if kind == protocol.REQUEST: |
| 753 |
raise KeyboardInterrupt |
| 754 |
|
| 755 |
monkeypatch.setattr(protocol, "send_frame", send_frame) |
| 756 |
assert client.run(typed(), ["-c", "select 1"], environ) == ExitCode.INTERRUPT |
| 757 |
assert stub.request is not None |
| 758 |
assert stub.cancelled == stub.request.request_id |
| 759 |
|
| 760 |
|
| 761 |
@needs_unix_sockets |
| 762 |
def test_a_session_that_could_not_stop_the_query_says_so( |
| 763 |
serve: Serve, |
| 764 |
environ: dict[str, str], |
| 765 |
monkeypatch: pytest.MonkeyPatch, |
| 766 |
capsysbinary: pytest.CaptureFixture[bytes], |
| 767 |
) -> None: |
| 768 |
"""The cancel's answer is copied to the caller like any other, so an |
| 769 |
adapter that cannot stop a query reaches the person who interrupted it.""" |
| 770 |
serve( |
| 771 |
frames=[(protocol.EXIT, b"\x00")], |
| 772 |
cancel_frames=[ |
| 773 |
(protocol.STDERR, b"note: still running\n"), |
| 774 |
(protocol.EXIT, bytes([ExitCode.INTERRUPT])), |
| 775 |
], |
| 776 |
) |
| 777 |
interrupt_once(monkeypatch) |
| 778 |
assert client.run(typed(), ["-c", "select 1"], environ) == ExitCode.INTERRUPT |
| 779 |
assert capsysbinary.readouterr().err == b"note: still running\n" |
| 780 |
|
| 781 |
|
| 782 |
@needs_unix_sockets |
| 783 |
def test_an_interrupt_a_session_never_answers_is_still_exit_130( |
| 784 |
serve: Serve, environ: dict[str, str], monkeypatch: pytest.MonkeyPatch |
| 785 |
) -> None: |
| 786 |
"""A session that went away between the two connections leaves the run |
| 787 |
given up on either way: there is nothing left to cancel and nothing to |
| 788 |
report.""" |
| 789 |
stub = serve(frames=[(protocol.EXIT, b"\x00")]) |
| 790 |
interrupt_once(monkeypatch) |
| 791 |
connecting = client._connect |
| 792 |
connected: list[object] = [] |
| 793 |
|
| 794 |
def connect(path: str) -> Any: |
| 795 |
connected.append(path) |
| 796 |
# the second is the cancel's, by which time the session is gone |
| 797 |
return None if len(connected) > 1 else connecting(path) |
| 798 |
|
| 799 |
monkeypatch.setattr(client, "_connect", connect) |
| 800 |
assert client.run(typed(), ["-c", "select 1"], environ) == ExitCode.INTERRUPT |
| 801 |
assert stub.cancelled is None |
| 802 |
|
| 803 |
|
| 804 |
@needs_unix_sockets |
| 805 |
def test_an_interrupt_before_the_request_cancels_nothing( |
| 806 |
serve: Serve, environ: dict[str, str], monkeypatch: pytest.MonkeyPatch |
| 807 |
) -> None: |
| 808 |
"""Nothing has an id until the request is built, so an interrupt while the |
| 809 |
caller's stdin is still being read has nothing to name.""" |
| 810 |
stub = serve(frames=[(protocol.EXIT, b"\x00")]) |
| 811 |
|
| 812 |
def interrupt(_: object) -> bytes: |
| 813 |
raise KeyboardInterrupt |
| 814 |
|
| 815 |
monkeypatch.setattr(client, "_stdin_for", interrupt) |
| 816 |
assert client.run(typed(), ["-f", "-"], environ) == ExitCode.INTERRUPT |
| 817 |
assert stub.cancelled is None |
| 818 |
|
| 819 |
|
| 820 |
@needs_unix_sockets |
| 821 |
def test_a_server_that_stops_mid_response_is_a_connection_failure( |
| 822 |
serve: Serve, environ: dict[str, str], capsys: pytest.CaptureFixture[str] |
| 823 |
) -> None: |
| 824 |
"""No `EXIT` frame is a run whose outcome nobody knows, which is not a |
| 825 |
query that succeeded.""" |
| 826 |
serve(frames=[(protocol.STDOUT, b"partial")]) |
| 827 |
assert client.run(typed(), [], environ) == ExitCode.CONNECTION |
| 828 |
assert "did not answer" in capsys.readouterr().err |
| 829 |
|
| 830 |
|
| 831 |
# --- the copies, and what pins them ------------------------------------------ |
| 832 |
|
| 833 |
|
| 834 |
def test_the_clients_exit_codes_are_hsqls() -> None: |
| 835 |
"""Copied rather than imported, because reaching `diagnostics` costs more |
| 836 |
than the round trip they report on.""" |
| 837 |
assert client.USAGE == ExitCode.USAGE |
| 838 |
assert client.CONNECTION == ExitCode.CONNECTION |
| 839 |
assert client.INTERRUPT == ExitCode.INTERRUPT |
| 840 |
|
| 841 |
|
| 842 |
def test_the_clients_boolean_short_flags_are_the_commands() -> None: |
| 843 |
"""The client has to know which short options take no value, because those |
| 844 |
are the ones a `-f` can follow in a cluster. Copied for the same reason as |
| 845 |
the exit codes, and pinned here against the real command.""" |
| 846 |
from harlequin.hsql.cli import bare_command |
| 847 |
|
| 848 |
boolean_shorts = { |
| 849 |
spelling.lstrip("-") |
| 850 |
for param in bare_command().params |
| 851 |
for spelling in param.opts |
| 852 |
if getattr(param, "is_flag", False) |
| 853 |
and len(spelling) == 2 |
| 854 |
and not spelling.startswith("--") |
| 855 |
} |
| 856 |
assert set(client.BOOLEAN_SHORT_FLAGS) == boolean_shorts |
| 857 |
|
| 858 |
|
| 859 |
def test_the_protocol_version_is_the_release_it_ships_with() -> None: |
| 860 |
"""A literal because reading the package metadata costs more than the round |
| 861 |
trip; `scripts/bump_versions.py` is what keeps it true.""" |
| 862 |
assert protocol.VERSION == version("harlequin") |
| 863 |
|
| 864 |
|
| 865 |
def test_a_release_bumps_the_protocol_version_and_rewrites_nothing_else( |
| 866 |
tmp_path: Path, |
| 867 |
) -> None: |
| 868 |
source = Path(protocol.__file__) |
| 869 |
copied = tmp_path / "protocol.py" |
| 870 |
copied.write_bytes(source.read_bytes()) |
| 871 |
_release_script().write_protocol_version("9.9.9", copied) |
| 872 |
assert copied.read_bytes() == source.read_bytes().replace( |
| 873 |
f'VERSION = "{version("harlequin")}"'.encode(), b'VERSION = "9.9.9"' |
| 874 |
) |
| 875 |
|
| 876 |
|
| 877 |
@pytest.mark.parametrize("ending", [b"\n", b"\r\n"]) |
| 878 |
def test_a_release_leaves_the_files_line_endings_alone( |
| 879 |
ending: bytes, tmp_path: Path |
| 880 |
) -> None: |
| 881 |
"""A Windows checkout has CRLF here -- `.gitattributes` pins only the |
| 882 |
artifacts whose bytes are a contract -- and a release that normalized them |
| 883 |
would rewrite every line of the file to change one. |
| 884 |
|
| 885 |
Parametrized rather than left to the platform, so the ending this file does |
| 886 |
*not* have in the checkout running the test is covered too. |
| 887 |
""" |
| 888 |
source = Path(protocol.__file__).read_bytes().replace(b"\r\n", b"\n") |
| 889 |
copied = tmp_path / "protocol.py" |
| 890 |
copied.write_bytes(source.replace(b"\n", ending)) |
| 891 |
_release_script().write_protocol_version("9.9.9", copied) |
| 892 |
written = copied.read_bytes() |
| 893 |
assert b'VERSION = "9.9.9"' in written |
| 894 |
assert written == source.replace( |
| 895 |
f'VERSION = "{version("harlequin")}"'.encode(), b'VERSION = "9.9.9"' |
| 896 |
).replace(b"\n", ending) |
| 897 |
|
| 898 |
|
| 899 |
def _release_script() -> ModuleType: |
| 900 |
"""The release script, loaded from `scripts/`, which is not a package.""" |
| 901 |
path = Path(__file__).resolve().parents[2] / "scripts" / "bump_versions.py" |
| 902 |
spec = importlib.util.spec_from_file_location("bump_versions", path) |
| 903 |
assert spec is not None and spec.loader is not None |
| 904 |
module = importlib.util.module_from_spec(spec) |
| 905 |
spec.loader.exec_module(module) |
| 906 |
return module |
| 907 |
|
| 908 |
|
| 909 |
# --- the whole thing, from the console script -------------------------------- |
| 910 |
|
| 911 |
HsqlProcess = Callable[..., "subprocess.CompletedProcess[str]"] |
| 912 |
|
| 913 |
|
| 914 |
@pytest.fixture |
| 915 |
def hsql_process(tmp_path: Path) -> HsqlProcess: |
| 916 |
"""Run `main()` the way the console script does, in a fresh interpreter. |
| 917 |
|
| 918 |
A clean machine, too: the child gets an empty directory as its cwd, its |
| 919 |
home and its config dir, so it reads no config file of whoever is running |
| 920 |
the tests -- and no `HSQL_SESSION` they happen to have set. |
| 921 |
""" |
| 922 |
|
| 923 |
def _run(argv: Sequence[str], **environ: str) -> subprocess.CompletedProcess[str]: |
| 924 |
return subprocess.run( |
| 925 |
[ |
| 926 |
sys.executable, |
| 927 |
"-c", |
| 928 |
"import sys\n" |
| 929 |
f"sys.argv = ['hsql', *{list(argv)!r}]\n" |
| 930 |
"from harlequin.hsql import main\n" |
| 931 |
"main()\n", |
| 932 |
], |
| 933 |
capture_output=True, |
| 934 |
text=True, |
| 935 |
cwd=tmp_path, |
| 936 |
env={ |
| 937 |
**{k: v for k, v in os.environ.items() if k != "HSQL_SESSION"}, |
| 938 |
"HOME": str(tmp_path), |
| 939 |
"USERPROFILE": str(tmp_path), |
| 940 |
"XDG_CONFIG_HOME": str(tmp_path / "xdg"), |
| 941 |
"APPDATA": str(tmp_path / "appdata"), |
| 942 |
"LOCALAPPDATA": str(tmp_path / "localappdata"), |
| 943 |
**environ, |
| 944 |
}, |
| 945 |
) |
| 946 |
|
| 947 |
return _run |
| 948 |
|
| 949 |
|
| 950 |
def test_an_ambient_session_that_is_down_still_runs_the_query( |
| 951 |
hsql_process: HsqlProcess, |
| 952 |
) -> None: |
| 953 |
"""The fallback is the one behavior that must not break a script.""" |
| 954 |
proc = hsql_process( |
| 955 |
["-c", "select 1", "--no-init", ":memory:"], |
| 956 |
HSQL_SESSION="nobody-started-this", |
| 957 |
) |
| 958 |
assert proc.returncode == ExitCode.OK |
| 959 |
assert "1" in proc.stdout |
| 960 |
assert "running cold" in proc.stderr |
| 961 |
|
| 962 |
|
| 963 |
def test_a_typed_session_that_is_down_runs_nothing(hsql_process: HsqlProcess) -> None: |
| 964 |
proc = hsql_process(["--session", "nobody", "-c", "select 1"]) |
| 965 |
# a platform that has no sessions at all is a usage error, not a server that |
| 966 |
# happens to be down |
| 967 |
assert proc.returncode == ( |
| 968 |
ExitCode.CONNECTION if HAS_UNIX_SOCKETS else ExitCode.USAGE |
| 969 |
) |
| 970 |
assert not proc.stdout |
| 971 |
|
| 972 |
|
| 973 |
def test_a_session_flag_with_no_value_names_itself( |
| 974 |
hsql_process: HsqlProcess, |
| 975 |
) -> None: |
| 976 |
"""The client refuses it; click does not declare the option, so its own |
| 977 |
answer would be "No such option".""" |
| 978 |
proc = hsql_process(["--session"]) |
| 979 |
assert proc.returncode == ExitCode.USAGE |
| 980 |
assert "--session needs a name" in proc.stderr |
| 981 |
assert not proc.stdout |