suite.py (201723B)
1 # This file is part of GNU Taler 2 # (C) 2026 Taler Systems S.A. 3 # 4 # GNU Taler is free software; you can redistribute it and/or modify it under the 5 # terms of the GNU General Public License as published by the Free Software 6 # Foundation; either version 3, or (at your option) any later version. 7 # 8 # GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY 9 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 10 # A PARTICULAR PURPOSE. See the GNU General Public License for more details. 11 # 12 # You should have received a copy of the GNU General Public License along with 13 # GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 14 """The scenarios: one feature each, walked deliberately. 15 16 A scenario that cannot reach its feature fails loudly (`Ctx.require`) rather 17 than reporting a green row for having done nothing. That is the whole 18 discipline here: a passing row has to mean the terminal was actually put 19 through the thing the row is named after. 20 21 python3 suite.py --list 22 python3 suite.py login_demo_credentials order_amount_pay 23 python3 suite.py --all 24 python3 suite.py --tag mock only the ones that need the mock 25 python3 suite.py --all --skip-tag pay leave the slow ones out 26 27 Tags say what a scenario needs: 28 29 demo the public demo backend and its `sandbox` instance 30 mock a merchant backend of the harness's own, on TLS (backend/mockd.py) 31 pay a funded customer wallet, so the scenario can settle a payment 32 fault `taler-twister` in front of a real backend, breaking its replies 33 slow minutes rather than seconds 34 """ 35 36 from __future__ import annotations 37 38 import argparse 39 import json 40 import os 41 import re 42 import sys 43 import threading 44 import time 45 import urllib.parse 46 import traceback 47 from dataclasses import dataclass, field 48 from pathlib import Path 49 from typing import Callable, Iterable, Optional 50 51 sys.path.insert(0, str(Path(__file__).resolve().parent)) 52 sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "backend")) 53 54 import counterparty 55 import faults 56 import merchant 57 import mockd 58 import oracles 59 from device import Device, serial_for 60 from episode import Action, Episode 61 from pos import ( 62 MARK_AMOUNT, MARK_CHECKOUT, MARK_CHECKOUT_PAD, MARK_CONFIG, MARK_FETCHING, 63 MARK_HISTORY, MARK_ORDER, MARK_PAYMENT, MARK_REFUND_FORM, MARK_REFUND_URI, 64 MARK_SUCCESS, APPROVE_REFUND, BILL_BUTTON, 65 Dialog, Pos, PosError, 66 ) 67 68 # "Merchant portal URL" is the login form's field label -- and also a row in 69 # the Settings screen's About block, which reads "Merchant portal URL: 70 # https://...". So it cannot stand for "the terminal is back on the login 71 # form": Settings matches it too, and a scenario checking that logging out was 72 # cancelled reported that it had not been. The Connect button is only on the 73 # login form. 74 AT_LOGIN = r"^Connect$|^Manual config$" 75 76 SIM_ROOT = Path(os.environ.get("POS_SIM_ROOT", "/tmp/taler-pos-sim")) 77 WORKER = int(os.environ.get("POS_WORKER", "0")) 78 SERIAL = serial_for(WORKER) 79 MOCK_PORT = int(os.environ.get("POS_MOCK_PORT", str(19443 + WORKER))) 80 # twister's own HTTP port is never reached from the device: the terminal talks 81 # to the TLS front, which relays to it. Only the front is reversed into the 82 # emulator. 83 TWISTER_PORT = int(os.environ.get("POS_TWISTER_PORT", str(18880 + WORKER))) 84 FRONT_PORT = int(os.environ.get("POS_FRONT_PORT", str(19473 + WORKER))) 85 # Whether this process is the only one using the shared `sandbox` instance. 86 # Two workers on it at once each see the other's orders, which is harmless for 87 # most scenarios and fatal for the few that count what the backend gained 88 # while they ran: those say so and skip the count rather than report the other 89 # worker's orders as the app's fault. The campaign sets it. 90 EXCLUSIVE_DEMO = os.environ.get("POS_EXCLUSIVE_DEMO", "1") != "0" 91 92 93 class ScenarioFailure(AssertionError): 94 """The scenario could not establish what it set out to test.""" 95 96 97 @dataclass 98 class Mock: 99 """A mock merchant backend running for one scenario.""" 100 101 state: mockd.MockState 102 port: int 103 instance: str 104 105 @property 106 def host(self) -> str: 107 return f"localhost:{self.port}" 108 109 @property 110 def merchant_url(self) -> str: 111 return f"https://{self.host}/instances/{self.instance}" 112 113 114 @dataclass 115 class Ctx: 116 """Everything a scenario is handed.""" 117 118 dev: Device 119 app: Pos 120 ep: Episode 121 name: str 122 _demo: Optional[merchant.Instance] = None 123 _customer: Optional[tuple[counterparty.Wallet, counterparty.BankAccount]] = None 124 mock: Optional[Mock] = None 125 tw: Optional[faults.Twister] = None 126 checks: list[str] = field(default_factory=list) 127 128 # -- assertions ------------------------------------------------------- 129 130 def require(self, condition: bool, message: str) -> None: 131 """What the scenario needed to be true to have tested anything.""" 132 if not condition: 133 raise ScenarioFailure(message) 134 self.checks.append(message) 135 136 def expect(self, condition: bool, kind: str, detail: str, 137 evidence: str = "") -> bool: 138 """What the terminal was supposed to do. A failure is a finding. 139 140 The difference from `require` matters: `require` guards the harness 141 ("I could not get to the payment screen, so I have tested nothing"), 142 `expect` judges the app ("I got there and it was wrong"). 143 """ 144 if condition: 145 self.checks.append(f"{kind}: ok") 146 return True 147 self.ep.judge([oracles.Finding(kind, detail, evidence)]) 148 return False 149 150 # -- lazily acquired counterparties ----------------------------------- 151 152 def demo(self, seconds: Optional[int] = None) -> merchant.Instance: 153 """The demo backend, with a token of the requested lifetime.""" 154 if seconds is not None or self._demo is None: 155 self._demo = merchant.demo(seconds=seconds) 156 self.ep.note(f"demo token: {self._demo.token}") 157 return self._demo 158 159 def customer(self) -> tuple[counterparty.Wallet, counterparty.BankAccount]: 160 """This worker's customer: one wallet and one bank account per worker. 161 162 Not one shared between them. Three workers paying from the same 163 `taler-wallet-cli` database take turns at an sqlite file none of them 164 locks, and they spend each other's coins: the symptom is one worker 165 topping the wallet up to 60 and another failing the next payment with 166 "insufficient balance", reported as a harness error in whichever 167 scenario happened to be next. 168 """ 169 if self._customer is None: 170 # "possim1" is already somebody else's account on the public 171 # demo bank, and the password derived from the name does not open 172 # it; the per-worker names are spelt out so they do not collide 173 # with whatever short name a passer-by has taken. 174 self._customer = counterparty.customer( 175 name="possim" if not WORKER else f"possim-w{WORKER}", 176 db_dir=str(SIM_ROOT / "run" / f"wallets-w{WORKER}")) 177 return self._customer 178 179 def funded_customer(self, currency: str, amount: str = "60" 180 ) -> counterparty.Wallet: 181 """A wallet with money in it, topped up before it runs dry. 182 183 The threshold is generous on purpose. A wallet that still holds 184 slightly more than the next order costs a withdrawal every scenario, 185 and a wallet that holds slightly less fails the payment with 186 "insufficient balance" -- which is reported as a harness error several 187 steps after the scenario it actually spoils. 188 """ 189 wallet, account = self.customer() 190 want = f"{currency}:15" 191 if not wallet.has_at_least(want): 192 self.ep.note(f"topping the customer wallet up to {currency}:{amount}") 193 wallet.withdraw(account, f"{currency}:{amount}") 194 self.require(wallet.has_at_least(want), 195 f"the customer has at least {want} to spend") 196 return wallet 197 198 # -- convenience ------------------------------------------------------ 199 200 def observe(self) -> None: 201 self.ep.observe() 202 203 def provision_demo(self, style: str = "path", 204 seconds: Optional[int] = None) -> merchant.Instance: 205 """A terminal bound to the demo instance, ready to take an order.""" 206 inst = self.demo(seconds=seconds) 207 self.app.fresh_start() 208 self.app.provision_by_uri(inst.setup_uri(style=style)) 209 self.ep.observe() 210 return inst 211 212 def provision_mock(self, profile: str, instance: str = "mockshop", 213 expect_success: bool = True, need_form: bool = False): 214 """Start a mock backend with the given profile and point the terminal at it. 215 216 `need_form` is for the scenarios that are *about* the login form -- 217 the two-factor challenges and the token-prefix retry both live in 218 `POST /private/token`, which a setup URI never sends. Those cannot be 219 routed around the broken phone form, so on a phone they say so and 220 stop rather than quietly testing a different code path and reporting 221 the difference as the app's fault. 222 """ 223 self.mock = start_mock(profile, MOCK_PORT, instance) 224 self.dev.adb("reverse", f"tcp:{self.mock.port}", f"tcp:{self.mock.port}", 225 check=False) 226 self.ep.note(f"mock backend profile {profile!r} on {self.mock.merchant_url}") 227 self.app.fresh_start() 228 # On a phone the login form is unusable -- the keyboard takes the 229 # whole form with it, fields and Connect and all, and nothing 230 # scrolls (see findings/login-form-collapses-under-the-keyboard.md). 231 # A setup URI carries the port now that master preserves it, so the 232 # rest of the mock set is testable there; the form itself is judged 233 # by a scenario of its own rather than quietly worked around. 234 if self.dev.is_phone_layout() and need_form: 235 raise ScenarioFailure( 236 "this scenario needs the login form, and the form is unusable " 237 "on a phone -- see findings/login-form-collapses-under-the-" 238 "keyboard.md; run it on a tablet-sized worker") 239 if self.dev.is_phone_layout(): 240 uri = (f"taler-pos://{self.mock.host}/instances/{instance}" 241 f"#mock-secret") 242 self.ep.note(f"provisioning by setup URI instead: {uri}") 243 return self.app.provision_by_uri( 244 uri, expect_success=expect_success) 245 return self.app.provision_by_form( 246 self.mock.host, instance, "mock-secret", 247 expect_success=expect_success) 248 249 def provision_twister(self, chaos: int = 0, expect_success: bool = True, 250 arm_during_login: tuple = ()) -> faults.Twister: 251 """A terminal bound to the demo instance *through* twister. 252 253 The login form rather than a setup URI, for two reasons: the form is 254 the only path that mints the terminal's own token through 255 `POST /private/token`, and a `taler-pos://` URI loses the port (round 256 one, finding 7) which a proxy on a non-default port cannot survive. 257 258 `arm_during_login` is for faults that have to be in place before the 259 terminal has a session at all; everything after login is better armed 260 one request at a time, because a post-login action makes exactly one 261 request and the mutation lands on it. 262 """ 263 if not faults.available(): 264 raise ScenarioFailure( 265 f"no taler-twister at {faults.SERVICE}; see README (it is built " 266 f"on the emulator host against the system GNUnet)") 267 self.tw = start_twister(merchant.DEMO_BASE.rstrip("/"), TWISTER_PORT, FRONT_PORT, 268 chaos=chaos, run_dir=SIM_ROOT / "run") 269 self.dev.adb("reverse", f"tcp:{FRONT_PORT}", f"tcp:{FRONT_PORT}", check=False) 270 self.ep.note(f"twister in front of {merchant.DEMO_BASE} on {self.tw.host}" 271 + (f", chaos {chaos}%" if chaos else "")) 272 self.app.fresh_start() 273 if arm_during_login: 274 with self.tw.sustain(*arm_during_login): 275 self.app.provision_by_form( 276 self.tw.host, merchant.DEMO_INSTANCE, merchant.DEMO_SECRET, 277 expect_success=expect_success) 278 else: 279 self.app.provision_by_form( 280 self.tw.host, merchant.DEMO_INSTANCE, merchant.DEMO_SECRET, 281 expect_success=expect_success) 282 return self.tw 283 284 @property 285 def front(self) -> faults.TlsFront: 286 """The TLS front, for faults that happen below HTTP.""" 287 assert self.tw is not None, "no twister in this scenario" 288 return faults.front_of(self.tw) 289 290 291 # -- the mock, started in-process ---------------------------------------- 292 293 _running_mocks: list[tuple[object, threading.Thread]] = [] 294 295 296 def start_mock(profile: str, port: int, instance: str) -> Mock: 297 """Run a mock backend in a thread for the duration of one scenario. 298 299 The previous one is shut down first. A suite process runs several mock 300 scenarios in a row and each wants its own profile, so leaving the last 301 server listening would take the port with it and the next scenario would 302 talk to the wrong backend -- or fail to bind and look like a harness 303 error. 304 """ 305 stop_mocks() 306 server, state = mockd.build_server(profile, port, instance, 307 f"localhost:{port}") 308 thread = threading.Thread(target=server.serve_forever, daemon=True) 309 thread.start() 310 _running_mocks.append((server, thread)) 311 # Wait for it to actually answer, rather than for the thread to exist. 312 import socket 313 import ssl as _ssl 314 deadline = time.monotonic() + 20 315 while time.monotonic() < deadline: 316 try: 317 ctx = _ssl.create_default_context( 318 cafile=str(Path(__file__).resolve().parent.parent / "tls" / "ca.crt")) 319 with socket.create_connection(("127.0.0.1", port), timeout=2) as raw: 320 with ctx.wrap_socket(raw, server_hostname="localhost"): 321 return Mock(state=state, port=port, instance=instance) 322 except OSError: 323 time.sleep(0.5) 324 raise ScenarioFailure(f"the mock backend did not come up on port {port}") 325 326 327 _running_twisters: list[faults.Twister] = [] 328 329 330 def start_twister(destination: str, port: int, front_port: int, chaos: int, 331 run_dir: Path) -> faults.Twister: 332 """Run twister and its TLS front for the duration of one scenario.""" 333 stop_twisters() 334 tw = faults.Twister(destination=destination, port=port, front_port=front_port, 335 run_dir=run_dir, chaos=chaos) 336 tw.start() 337 _running_twisters.append(tw) 338 return tw 339 340 341 def stop_twisters() -> None: 342 while _running_twisters: 343 try: 344 _running_twisters.pop().stop() 345 except Exception: 346 pass 347 348 349 def stop_mocks() -> None: 350 while _running_mocks: 351 server, thread = _running_mocks.pop() 352 try: 353 server.shutdown() # type: ignore[attr-defined] 354 server.server_close() # type: ignore[attr-defined] 355 except Exception: 356 pass 357 thread.join(timeout=5) 358 359 360 # -- the registry --------------------------------------------------------- 361 362 SCENARIOS: dict[str, tuple[Callable[[Ctx], None], tuple[str, ...], str]] = {} 363 364 365 def scenario(*tags: str): 366 def wrap(fn: Callable[[Ctx], None]): 367 doc = (fn.__doc__ or "").strip().splitlines()[0] if fn.__doc__ else "" 368 SCENARIOS[fn.__name__] = (fn, tags, doc) 369 return fn 370 return wrap 371 372 373 # ========================================================================= 374 # provisioning 375 # ========================================================================= 376 377 378 @scenario("demo") 379 def login_demo_credentials(c: Ctx) -> None: 380 """The terminal's own "Fill demo credentials" button, end to end.""" 381 c.app.fresh_start() 382 screen = c.app.fill_demo_credentials() 383 c.require(screen.find(r"backend\.demo\.taler\.net"), 384 "the demo button filled in the demo host") 385 c.observe() 386 c.app.tap_button(r"^Connect$") 387 screen = c.app.wait_for_order_entry() 388 c.observe() 389 instance, url = c.app.bound_instance() 390 c.expect(instance == "sandbox", 391 "demo-credentials-wrong-instance", 392 f"the demo credentials button bound the terminal to {instance!r}") 393 c.require(bool(url and "backend.demo.taler.net" in url), 394 f"the terminal is bound to the demo backend ({url})") 395 396 397 @scenario("demo") 398 def login_manual_form(c: Ctx) -> None: 399 """Typing the merchant URL, instance and password into the login form.""" 400 inst = c.demo() 401 c.app.fresh_start() 402 c.app.provision_by_form("backend.demo.taler.net", inst.merchant.instance, 403 merchant.DEMO_SECRET) 404 c.observe() 405 instance, url = c.app.bound_instance() 406 c.require(instance == inst.merchant.instance, 407 f"the form bound the terminal to {instance!r}") 408 409 410 @scenario("demo") 411 def login_wrong_password(c: Ctx) -> None: 412 """A wrong password has to be refused, and say which thing was wrong.""" 413 c.app.fresh_start() 414 screen = c.app.provision_by_form( 415 "backend.demo.taler.net", "sandbox", "definitely-not-the-password", 416 expect_success=False) 417 c.observe() 418 dialog = c.app.read_dialog(screen) 419 c.require(dialog is not None, 420 "the terminal said something about the wrong password") 421 c.ep.note(f"dialog: {dialog}") 422 c.expect(bool(re.search(r"(?i)username or password|invalid", dialog.message 423 or dialog.title)), 424 "wrong-password-message-unhelpful", 425 f"a wrong password produced {dialog}", 426 str(dialog)) 427 c.app.dismiss_dialog() 428 c.observe() 429 screen = c.dev.dump() 430 c.expect(bool(screen.find(AT_LOGIN)), 431 "stuck-after-auth-error", 432 "after refusing the password the terminal is not back on the " 433 "login form", 434 " | ".join(screen.texts())) 435 436 437 @scenario("demo") 438 def login_unknown_host(c: Ctx) -> None: 439 """A host that does not resolve: the terminal must not leak the exception.""" 440 c.app.fresh_start() 441 screen = c.app.provision_by_form( 442 "not-a-real-merchant.invalid", "sandbox", "sandbox", 443 expect_success=False) 444 time.sleep(6) 445 c.observe() 446 dialog = c.app.read_dialog() 447 c.require(dialog is not None, "the terminal reported the unreachable host") 448 c.ep.note(f"dialog: {dialog}") 449 c.expect(not re.search(r"(?i)exception|java\.|ktor|unknownhost", 450 f"{dialog.title} {dialog.message}"), 451 "exception-in-dialog", 452 f"the unreachable-host dialog quotes an exception: {dialog}", 453 str(dialog)) 454 455 456 @scenario("demo") 457 def login_url_shapes(c: Ctx) -> None: 458 """URLs a merchant might plausibly paste, and what the terminal makes of them. 459 460 The form normalises what it is given -- it prepends https, strips a path, 461 keeps a port and lifts an instance out of `/instances/<id>` -- so each 462 shape should end up at the same place. What is checked is that it does, 463 and that nothing in between is shown to the user raw. 464 """ 465 shapes = [ 466 ("backend.demo.taler.net", "sandbox"), 467 ("https://backend.demo.taler.net", "sandbox"), 468 ("backend.demo.taler.net/", "sandbox"), 469 ("https://backend.demo.taler.net/instances/sandbox", None), 470 ("BACKEND.DEMO.TALER.NET", "sandbox"), 471 (" backend.demo.taler.net ", "sandbox"), 472 ] 473 reached = 0 474 for host, instance in shapes: 475 c.app.fresh_start() 476 c.ep.note(f"url shape {host!r}, instance {instance!r}") 477 try: 478 c.app.provision_by_form(host, instance or "", merchant.DEMO_SECRET) 479 except (PosError, TimeoutError) as e: 480 screen = c.dev.dump() 481 dialog = c.app.read_dialog(screen) 482 c.ep.judge([oracles.Finding( 483 "url-shape-rejected", 484 f"the form could not log in with the merchant URL {host!r} " 485 f"(instance {instance!r}): {dialog or str(e)[:200]}", 486 " | ".join(screen.texts())[:600])]) 487 continue 488 reached += 1 489 bound_instance, url = c.app.bound_instance() 490 c.expect(bound_instance == "sandbox", 491 "url-shape-wrong-instance", 492 f"{host!r} bound the terminal to instance {bound_instance!r}") 493 c.observe() 494 c.require(reached > 0, "at least one URL shape logged in") 495 496 497 @scenario("demo") 498 def provision_setup_uri_styles(c: Ctx) -> None: 499 """Both shapes of `taler-pos://` setup URI, which are parsed by different code.""" 500 inst = c.demo() 501 for style in ("path", "params"): 502 c.app.fresh_start() 503 uri = inst.setup_uri(style=style) 504 c.ep.note(f"{style} style: {uri[:80]}...") 505 c.app.provision_by_uri(uri) 506 c.observe() 507 bound, url = c.app.bound_instance() 508 c.expect(bound == inst.merchant.instance, 509 "setup-uri-wrong-instance", 510 f"the {style}-style setup URI bound the terminal to {bound!r}") 511 c.require(bool(url), f"the {style}-style setup URI configured the terminal") 512 513 514 @scenario("demo") 515 def provision_setup_uri_malformed(c: Ctx) -> None: 516 """Setup URIs that are wrong in one way each. 517 518 None of them should configure anything, and none should crash: the parser 519 returns early on a missing piece, so what is being checked is that every 520 early return leaves a usable screen behind. 521 """ 522 inst = c.demo() 523 host = "backend.demo.taler.net" 524 token = inst.token.value 525 cases = { 526 "no token": f"taler-pos://{host}/instances/sandbox", 527 "no instance": f"taler-pos://{host}#{token}", 528 "empty instance": f"taler-pos://{host}/instances/#{token}", 529 "blank token": f"taler-pos://{host}/instances/sandbox#", 530 "no host": f"taler-pos:///instances/sandbox#{token}", 531 "wrong scheme": f"taler-pos-x://{host}/instances/sandbox#{token}", 532 "params, no password": f"taler-pos://{host}#username=sandbox", 533 "params, no username": f"taler-pos://{host}#password={token}", 534 "path but no segments": f"taler-pos://{host}/#{token}", 535 } 536 c.app.fresh_start() 537 for label, uri in cases.items(): 538 c.ep.note(f"malformed setup URI ({label}): {uri[:90]}") 539 c.ep.perform(Action("setup_uri", uri)) 540 time.sleep(3) 541 screen, _ = c.ep.observe() 542 if not screen.activity.startswith("net.taler.merchantpos"): 543 c.ep.judge([oracles.Finding( 544 "setup-uri-left-the-app", 545 f"a setup URI with {label} left the terminal showing " 546 f"{screen.activity}", 547 uri)]) 548 c.dev.launch() 549 time.sleep(3) 550 continue 551 # A dialog is its own window and dumps alone, so the login form behind 552 # it is not in the hierarchy: read the dialog, close it, and judge 553 # what is left rather than what the dialog hid. 554 dialog = c.app.read_dialog(screen) 555 if dialog is not None: 556 c.ep.note(f"{label}: {dialog}") 557 c.app.dismiss_dialog() 558 screen, _ = c.ep.observe() 559 c.expect(bool(screen.find(AT_LOGIN)) or 560 bool(screen.find(r"Fetching configuration")), 561 "setup-uri-dead-end", 562 f"a setup URI with {label} left the terminal on a screen with " 563 f"no way back: {screen.texts()[:10]}", 564 uri) 565 if screen.find(r"Fetching configuration"): 566 # A URI that got as far as fetching with half a credential; give it 567 # time to fail and make sure it says so rather than spinning. 568 time.sleep(12) 569 screen, _ = c.ep.observe() 570 c.expect(not screen.find(r"Fetching configuration"), 571 "stuck-fetching-after-bad-uri", 572 f"a setup URI with {label} left the terminal fetching " 573 f"configuration forever", 574 uri) 575 c.app.dismiss_dialog() 576 c.require(True, "every malformed setup URI was delivered") 577 578 579 @scenario("demo", "slow") 580 def provision_port_is_dropped(c: Ctx) -> None: 581 """A setup URI for a backend on a non-default port. 582 583 `MainActivity.handleSetupIntent` rebuilds the merchant URL from 584 `data.host`, which is the host *without* the port, so a merchant whose 585 backend does not listen on 443 cannot be provisioned by QR code at all. 586 The login form keeps the port, so the two paths disagree -- which is what 587 this checks. 588 """ 589 uri = f"taler-pos://backend.demo.taler.net:443/instances/sandbox#{c.demo().token.value}" 590 c.app.fresh_start() 591 c.ep.note(f"setup URI with an explicit port: {uri[:90]}") 592 try: 593 c.app.provision_by_uri(uri) 594 _, url = c.app.bound_instance() 595 c.ep.note(f"bound to {url}") 596 c.expect(bool(url and ":443" in url), 597 "setup-uri-drops-the-port", 598 f"a setup URI naming port 443 configured the terminal as " 599 f"{url}, with the port dropped; a backend on any other port " 600 f"cannot be provisioned this way at all", 601 uri) 602 except (PosError, TimeoutError): 603 screen = c.dev.dump() 604 c.ep.judge([oracles.Finding( 605 "setup-uri-drops-the-port", 606 "a setup URI naming a port did not configure the terminal at all", 607 " | ".join(screen.texts())[:400])]) 608 c.require(True, "a setup URI with a port was delivered") 609 610 611 @scenario("demo", "phone") 612 def config_qr_tab(c: Ctx) -> None: 613 """Selecting the QR tab on the login screen, which starts the camera.""" 614 c.app.fresh_start() 615 screen = c.app.wait_for_config_screen() 616 c.require(bool(screen.find(r"^QR config$")), "the login screen offers a QR tab") 617 c.ep.perform(Action("tap_label", "QR config")) 618 time.sleep(6) 619 screen, _ = c.ep.observe() 620 alive = screen.activity.startswith("net.taler.merchantpos") 621 c.expect(alive, "qr-tab-crash", 622 f"selecting the QR configuration tab left the terminal showing " 623 f"{screen.activity or 'nothing'}: {screen.texts()[:8]}", 624 " | ".join(screen.texts())[:600]) 625 c.require(True, "the QR tab was selected") 626 if alive: 627 c.expect(bool(screen.find(r"Scan the QR code|Camera permission")), 628 "qr-tab-blank", 629 f"the QR tab shows neither a hint nor a permission message: " 630 f"{screen.texts()[:8]}") 631 632 633 @scenario("demo") 634 def config_qr_without_camera_permission(c: Ctx) -> None: 635 """The QR tab with the camera permission denied.""" 636 c.app.fresh_start(grant_camera=False) 637 c.dev.revoke_camera() 638 c.app.relaunch() 639 c.app.wait_for_config_screen() 640 c.ep.perform(Action("tap_label", "QR config")) 641 time.sleep(6) 642 screen, _ = c.ep.observe() 643 # Asking for the permission is the right thing to do, and the system's 644 # permission dialog is its own activity -- so being there is not a crash. 645 asking = "permissioncontroller" in screen.activity.lower() 646 if asking: 647 c.ep.note(f"the terminal asked for the camera permission: " 648 f"{screen.texts()[:6]}") 649 deny = screen.find(r"(?i)^Don.t allow$|^Deny$") 650 if deny is not None: 651 c.dev.tap_node(deny, screen) 652 time.sleep(4) 653 screen, _ = c.ep.observe() 654 c.expect(screen.activity.startswith("net.taler.merchantpos") or asking, 655 "qr-tab-crash-without-permission", 656 f"the QR tab with no camera permission left the terminal showing " 657 f"{screen.activity or 'nothing'}", 658 " | ".join(screen.texts())[:500]) 659 c.require(True, "the QR tab was selected without the camera permission") 660 661 662 # ========================================================================= 663 # sessions and credentials 664 # ========================================================================= 665 666 667 @scenario("demo", "slow") 668 def token_expires_while_idle(c: Ctx) -> None: 669 """A session that ends while the terminal is sitting on the order screen. 670 671 The login form can only ask for a token that never expires, so the only 672 way to see this is to mint a short-lived one outside and provision with 673 it. What should happen is the "session expired" toast and a return to the 674 login screen; what must not happen is an unexplained failure on the next 675 thing the cashier touches. 676 """ 677 inst = c.provision_demo(seconds=75) 678 left = inst.token.seconds_left or 0 679 c.require(left > 20, f"the token has {left:.0f}s left to run") 680 c.ep.note(f"waiting out a token with {left:.0f}s left") 681 time.sleep(max(0, left) + 10) 682 c.ep.note("the token has now expired") 683 # Something has to talk to the backend for the terminal to notice. 684 c.app.goto("history") 685 c.app.tap_button(r"Refresh history") 686 time.sleep(12) 687 screen, _ = c.ep.observe() 688 back_at_login = bool(screen.find(AT_LOGIN)) 689 c.expect(back_at_login, 690 "expired-session-not-noticed", 691 f"the terminal kept working after its token expired instead of " 692 f"asking for credentials: {screen.texts()[:10]}", 693 " | ".join(screen.texts())[:600]) 694 c.require(True, "the terminal was used after its token expired") 695 696 697 @scenario("demo", "slow") 698 def token_revoked_mid_payment(c: Ctx) -> None: 699 """The session ends while the payment screen is polling. 700 701 This is the sharpest version of the question, because `PaymentManager` 702 asserts its configuration: `configManager.merchantConfig!!` appears in 703 five of its methods, and the 401 interceptor sets that field to null the 704 moment a request comes back unauthorised. Cancelling the payment after 705 that is a null dereference on a non-null type. 706 """ 707 inst = c.provision_demo() 708 c.app.goto("amount") 709 c.app.enter_amount("1.00") 710 c.app.charge() 711 screen, _ = c.ep.observe() 712 c.require(bool(screen.find(r"scan QR Code|Cancel payment")), 713 "the terminal is on the payment screen, polling") 714 inst.merchant.revoke_token(inst.token.value) 715 c.ep.note("the terminal's token has been revoked server side") 716 # The payment screen polls once a second, so the next poll gets a 401. 717 time.sleep(8) 718 screen, _ = c.ep.observe() 719 c.ep.note(f"after revocation the screen shows: {screen.texts()[:8]}") 720 if screen.find(r"Cancel payment"): 721 c.ep.perform(Action("tap_label", "Cancel payment")) 722 time.sleep(6) 723 screen, _ = c.ep.observe() 724 crashed = not screen.activity.startswith("net.taler.merchantpos") 725 c.expect(not crashed, 726 "crash-after-session-lost", 727 f"cancelling a payment after the session was revoked left the " 728 f"terminal showing {screen.activity or 'nothing'}", 729 " | ".join(screen.texts())[:500]) 730 c.require(True, "the session was revoked while a payment was in flight") 731 732 733 @scenario("mock") 734 def token_expires_mid_session_mock(c: Ctx) -> None: 735 """A backend that stops accepting the token after a few requests. 736 737 The same question as `token_expires_while_idle`, but without the waiting 738 and at a moment the harness picks exactly: the mock answers 401 from the 739 fourth authorised request on. 740 """ 741 screen = c.provision_mock("expire-after-3", expect_success=False) 742 time.sleep(8) 743 screen, _ = c.ep.observe() 744 c.ep.note(f"after provisioning: {screen.texts()[:10]}") 745 for _ in range(3): 746 if screen.find(r"Charge|Bill|Create order"): 747 break 748 time.sleep(4) 749 screen, _ = c.ep.observe() 750 if screen.find(r"Charge|Bill|Create order"): 751 c.app.goto("history") 752 c.app.tap_button(r"Refresh history") 753 time.sleep(8) 754 screen, _ = c.ep.observe() 755 c.require(bool(c.mock.state.paths()), "the terminal talked to the mock backend") 756 dialog = c.app.read_dialog(screen) 757 c.ep.note(f"screen: {screen.texts()[:10]}; dialog: {dialog}") 758 c.expect(bool(screen.find(AT_LOGIN) or dialog), 759 "expired-token-silent", 760 f"the token stopped working and the terminal neither said so nor " 761 f"went back to the login screen: {screen.texts()[:10]}", 762 " | ".join(screen.texts())[:600]) 763 764 765 @scenario("demo") 766 def settings_logout_and_back(c: Ctx) -> None: 767 """Logging out, and logging in again afterwards.""" 768 inst = c.provision_demo() 769 c.app.settings_logout() 770 screen, _ = c.ep.observe() 771 c.require(bool(screen.find(AT_LOGIN)), 772 "logging out returned the terminal to the login screen") 773 c.app.provision_by_uri(inst.setup_uri()) 774 c.observe() 775 bound, _ = c.app.bound_instance() 776 c.require(bound == inst.merchant.instance, 777 "the terminal could be provisioned again after a logout") 778 779 780 @scenario("demo") 781 def settings_logout_cancelled(c: Ctx) -> None: 782 """Backing out of the logout confirmation must not log out.""" 783 inst = c.provision_demo() 784 c.app.goto("settings") 785 c.app.tap_button(r"^Log out$") 786 time.sleep(1.5) 787 screen, _ = c.ep.observe() 788 dialog = c.app.read_dialog(screen) 789 c.require(dialog is not None, "logging out asks for confirmation") 790 c.ep.note(f"first logout dialog: {dialog}") 791 c.app.tap_button(r"^Cancel$") 792 time.sleep(2) 793 screen, _ = c.ep.observe() 794 c.expect(not screen.find(AT_LOGIN), 795 "cancelled-logout-logged-out", 796 "cancelling the logout dialog logged the terminal out anyway", 797 " | ".join(screen.texts())[:400]) 798 bound, _ = c.app.bound_instance() 799 c.require(bound == inst.merchant.instance, 800 "the terminal is still bound to its instance") 801 802 803 # ========================================================================= 804 # taking payment 805 # ========================================================================= 806 807 808 @scenario("demo", "pay", "slow") 809 def order_amount_pay(c: Ctx) -> None: 810 """Charge an amount on the keypad and have a real wallet pay it.""" 811 inst = c.provision_demo() 812 wallet = c.funded_customer(inst.currency) 813 before = inst.merchant.history(inst.token.value, limit=-5) 814 c.app.goto("amount") 815 c.app.enter_amount("1.00") 816 c.ep.observe() 817 c.app.charge() 818 screen, _ = c.ep.observe() 819 uri = c.app.displayed_pay_uri() 820 c.require(bool(uri), "the terminal showed a pay URI the customer can use") 821 c.ep.note(f"pay URI: {uri}") 822 order_id = _order_id_from(uri) 823 c.require(bool(order_id), f"the pay URI names an order ({uri})") 824 backend_uri = inst.merchant.pay_uri(inst.token.value, order_id) 825 c.ep.judge(oracles.payment_code_usable(screen, uri, backend_uri)) 826 c.expect(bool(c.app.published_nfc_uri()) is False, 827 "nfc-claimed-without-hardware", 828 "the terminal published an NFC payload on a device with no NFC " 829 "adapter") 830 wallet.pay(uri) 831 c.app.wait_for_success() 832 screen, _ = c.ep.observe() 833 c.require(bool(screen.find(MARK_SUCCESS)), 834 "the terminal showed the payment as received") 835 status = inst.merchant.order_status(inst.token.value, order_id) 836 c.expect(status.get("order_status") == "paid", 837 "success-without-payment", 838 f"the terminal showed 'Payment received' while the backend says " 839 f"the order is {status.get('order_status')!r}", 840 json.dumps(status)[:600]) 841 c.app.continue_from_success() 842 c.ep.observe() 843 after = inst.merchant.history(inst.token.value, limit=-5) 844 # Only when this process has the instance to itself: another worker's 845 # orders appear in this window as orders nobody collected, and the oracle 846 # would report them as the terminal's doing. 847 if EXCLUSIVE_DEMO: 848 c.ep.judge(oracles.orphaned_orders(before, after, allowed=[order_id])) 849 else: 850 c.ep.note("another worker shares this instance; not counting what it " 851 "gained") 852 853 854 @scenario("demo", "pay", "slow") 855 def order_inventory_pay(c: Ctx) -> None: 856 """Build an order from the product grid and have it paid.""" 857 inst = c.provision_demo() 858 wallet = c.funded_customer(inst.currency) 859 screen = c.app.goto("inventory") 860 c.ep.observe() 861 c.require(bool(screen.find(r"^Bill( .*)?$")), 862 "the inventory screen offers a Bill button") 863 added = c.app.add_products(2) 864 c.ep.note(f"added products: {added}") 865 screen, _ = c.ep.observe() 866 c.app.bill() 867 screen, _ = c.ep.observe() 868 uri = c.app.displayed_pay_uri() 869 c.require(bool(uri), "the terminal showed a pay URI for the inventory order") 870 order_id = _order_id_from(uri) 871 wallet.pay(uri) 872 c.app.wait_for_success() 873 screen, _ = c.ep.observe() 874 c.require(bool(screen.find(MARK_SUCCESS)), 875 "an inventory order was paid and acknowledged") 876 status = inst.merchant.order_status(inst.token.value, order_id) 877 c.expect(status.get("order_status") == "paid", 878 "success-without-payment", 879 f"the inventory order shows as received while the backend says " 880 f"{status.get('order_status')!r}") 881 882 883 @scenario("demo") 884 def order_custom_product(c: Ctx) -> None: 885 """The inventory screen's "Add custom product" dialog.""" 886 inst = c.provision_demo() 887 c.app.goto("inventory") 888 c.ep.observe() 889 c.app.add_custom_product("Tip", "2.00") 890 screen, _ = c.ep.observe() 891 c.require(bool(screen.find(r"Tip")), 892 "the custom product appears in the order") 893 c.app.bill() 894 screen, _ = c.ep.observe() 895 uri = c.app.displayed_pay_uri() 896 c.require(bool(uri), "an order with a custom product reached the payment screen") 897 order_id = _order_id_from(uri) 898 status = inst.merchant.order_status(inst.token.value, order_id) 899 c.ep.note(f"backend order: {json.dumps(status)[:300]}") 900 c.app.cancel_payment() 901 c.ep.observe() 902 903 904 @scenario("demo", "phone") 905 def amount_keypad_edges(c: Ctx) -> None: 906 """What the keypad does with nothing, with too much, and with corrections.""" 907 c.provision_demo() 908 c.app.goto("amount") 909 # Charging nothing has to be refused. Saying so in a dialog is one way; 910 # disabling the button is a better one, and it is what the terminal does 911 # -- so a scenario that insists on a message reports a nicer design as a 912 # defect. What matters is that no order is opened. 913 c.app.tap_button(r"^Clear$") 914 screen = c.app._stable_dump() 915 charge = screen.find(r"Create order \(charge amount\)") 916 charge_enabled = charge is None or screen.tap_target(charge).enabled 917 c.ep.note(f"at 0.00 the charge button is " 918 f"{'enabled' if charge_enabled else 'disabled'}") 919 c.ep.perform(Action("tap_label", "Create order (charge amount)")) 920 time.sleep(3) 921 screen, _ = c.ep.observe() 922 dialog = c.app.read_dialog(screen) 923 c.expect(not charge_enabled or dialog is not None 924 or bool(screen.find(r"Enter an amount")), 925 "zero-amount-accepted-silently", 926 f"the charge button was live at 0.00 and charging neither opened " 927 f"an order nor said why not: {screen.texts()[:10]}", 928 " | ".join(screen.texts())[:400]) 929 c.expect(not bool(screen.find(MARK_PAYMENT)), 930 "zero-amount-order-opened", 931 "charging 0.00 opened a payment screen", 932 " | ".join(screen.texts())[:400]) 933 if dialog: 934 c.ep.note(f"zero amount: {dialog}") 935 c.app.dismiss_dialog() 936 # Backspace and clear. 937 c.app.enter_digits("C12345") 938 before = c.app.displayed_amount() 939 c.app.enter_digits("<<") 940 after = c.app.displayed_amount() 941 c.ep.note(f"after 12345 the keypad shows {before}, after two backspaces {after}") 942 c.require(before != after, "backspace changed the amount on the keypad") 943 # Far more digits than any price: the keypad must not render nonsense. 944 c.app.enter_digits("C" + "9" * 14) 945 screen, _ = c.ep.observe() 946 shown = c.app.displayed_amount(screen) 947 c.ep.note(f"fourteen nines gives {shown}") 948 c.expect(shown is not None, 949 "keypad-overflow-blank", 950 "typing fourteen digits left the keypad showing no amount at all", 951 " | ".join(screen.texts())[:400]) 952 c.app.tap_button(r"^Clear$") 953 c.require(True, "the keypad's edges were exercised") 954 955 956 @scenario("demo", "pay", "slow") 957 def payment_cancel_after_claim(c: Ctx) -> None: 958 """A customer who looks at the contract and does not pay. 959 960 An order that has been claimed cannot be deleted the ordinary way, and the 961 terminal has a force-delete dialog for exactly that -- so this is the only 962 route to it. 963 """ 964 inst = c.provision_demo() 965 # Claiming without paying still makes wallet-core choose a 966 # contract choice, and choosing one needs the balance to cover 967 # it -- so this wants a funded wallet even though it never pays. 968 wallet = c.funded_customer(inst.currency) 969 c.app.goto("amount") 970 c.app.enter_amount("1.00") 971 c.app.charge() 972 uri = c.app.displayed_pay_uri() 973 c.require(bool(uri), "the payment screen offered a pay URI") 974 order_id = _order_id_from(uri) 975 wallet.claim_only(uri) 976 c.ep.note(f"the customer claimed order {order_id} without paying") 977 status = inst.merchant.order_status(inst.token.value, order_id) 978 c.require(status.get("order_status") == "claimed", 979 f"the backend considers the order claimed ({status.get('order_status')})") 980 screen = c.app.wait_for_claimed(timeout=60) 981 c.ep.observe() 982 c.require(bool(screen.find(r"confirm payment")), 983 "the terminal switched to 'waiting for the customer to confirm'") 984 c.ep.perform(Action("tap_label", "Cancel payment")) 985 time.sleep(5) 986 screen, _ = c.ep.observe() 987 dialog = c.app.read_dialog(screen) 988 c.ep.note(f"after cancelling a claimed order: {dialog or screen.texts()[:10]}") 989 c.expect(bool(screen.find(r"Force delete") or (dialog and "Force" in str(dialog))), 990 "no-force-delete-prompt", 991 f"cancelling a claimed payment offered no way to force the " 992 f"delete: {screen.texts()[:10]}", 993 " | ".join(screen.texts())[:500]) 994 if screen.find(r"Force delete"): 995 c.ep.perform(Action("tap_label", "Force delete")) 996 time.sleep(6) 997 screen, _ = c.ep.observe() 998 remaining = [o for o in inst.merchant.history(inst.token.value, limit=-10) 999 if o.get("order_id") == order_id] 1000 c.expect(not remaining, 1001 "force-delete-left-the-order", 1002 f"force-deleting order {order_id} left it in the backend's " 1003 f"order list", 1004 str(remaining)[:400]) 1005 1006 1007 @scenario("demo", "slow") 1008 def payment_deadline_passes(c: Ctx) -> None: 1009 """An order nobody pays, past its pay deadline. 1010 1011 The terminal's own timeout is `Long.MAX_VALUE`, so the countdown never 1012 fires; what ends the wait is the backend refusing the order. Either way 1013 the cashier must not be left looking at a code that can no longer be used. 1014 """ 1015 inst = c.provision_demo() 1016 order = inst.merchant.create_order( 1017 inst.token.value, f"{inst.currency}:1", "pos-simulator deadline", 1018 pay_deadline_s=25) 1019 order_id = order["order_id"] 1020 c.ep.note(f"created order {order_id} with a 25s pay deadline") 1021 c.app.goto("history") 1022 c.app.tap_button(r"Refresh history") 1023 time.sleep(6) 1024 screen, _ = c.ep.observe() 1025 c.require(bool(screen.find(re.escape(order_id))) or 1026 bool(c.app.history_rows(screen)), 1027 "the history list shows orders") 1028 time.sleep(30) 1029 c.ep.note("the pay deadline has passed") 1030 c.app.tap_button(r"Refresh history") 1031 time.sleep(8) 1032 screen, _ = c.ep.observe() 1033 status = inst.merchant.order_status(inst.token.value, order_id) 1034 c.ep.note(f"backend says {status.get('order_status')!r}") 1035 c.require(True, "an order was left to expire and the list was refreshed") 1036 1037 1038 @scenario("mock") 1039 def payment_order_creation_fails(c: Ctx) -> None: 1040 """A merchant with no bank account: the order cannot be created. 1041 1042 The backend refuses with a specific reason. The terminal has a string for 1043 this -- "Error: Could not create order" -- plus a detail line, so what is 1044 being checked is that the detail is the backend's reason rather than 1045 nothing or a stack trace. 1046 """ 1047 c.provision_mock("no-bank-account") 1048 c.app.goto("amount") 1049 c.app.enter_amount("1.00") 1050 c.ep.perform(Action("tap_label", "Create order (charge amount)")) 1051 time.sleep(8) 1052 screen, _ = c.ep.observe() 1053 dialog = c.app.read_dialog(screen) 1054 c.require(dialog is not None or bool(screen.find(r"(?i)could not create")), 1055 f"the terminal reported the refused order " 1056 f"(screen: {screen.texts()[:10]})") 1057 c.ep.note(f"refused order: {dialog}") 1058 body = f"{dialog.title} {dialog.message}" if dialog else " ".join(screen.texts()) 1059 c.expect(bool(re.search(r"(?i)wire|account|bank", body)), 1060 "order-refusal-loses-the-reason", 1061 f"the backend refused the order because the instance has no bank " 1062 f"account, and the terminal said only: {body[:200]!r}", 1063 body[:600]) 1064 c.expect(not re.search(r"(?i)exception|java\.|ktor", body), 1065 "exception-in-dialog", 1066 f"the refused-order dialog quotes an exception: {body[:200]!r}", 1067 body[:600]) 1068 1069 1070 # ========================================================================= 1071 # history and refunds 1072 # ========================================================================= 1073 1074 1075 @scenario("demo", "slow") 1076 def history_browse_and_paginate(c: Ctx) -> None: 1077 """The history list on an instance with a long history behind it. 1078 1079 The sandbox instance is what makes this worth running: it has enough 1080 orders for the list's pagination to run several pages deep, which a stack 1081 the harness builds itself never would. 1082 """ 1083 inst = c.provision_demo() 1084 backend_orders = inst.merchant.history(inst.token.value, limit=-40) 1085 c.require(len(backend_orders) > 5, 1086 f"the instance has a history to browse ({len(backend_orders)} orders)") 1087 screen = c.app.goto("history") 1088 c.ep.observe() 1089 c.app.refresh_history() 1090 screen, _ = c.ep.observe() 1091 rows = c.app.history_rows(screen) 1092 c.require(bool(rows), f"the history list shows rows (screen: {screen.texts()[:10]})") 1093 c.ep.note(f"first page shows {len(rows)} rows") 1094 # The snapshot is taken once and judged against for the whole walk, which 1095 # is only sound while nothing else is paying these orders: another worker 1096 # settling one would make a correct "paid" chip disagree with a snapshot 1097 # that still says unpaid. 1098 if EXCLUSIVE_DEMO: 1099 c.ep.judge(oracles.history_matches_backend(screen, backend_orders)) 1100 seen = set(rows) 1101 for page in range(8): 1102 c.ep.perform(Action("scroll_down"), screen) 1103 screen, _ = c.ep.observe() 1104 rows = c.app.history_rows(screen) 1105 if EXCLUSIVE_DEMO: 1106 c.ep.judge(oracles.history_matches_backend(screen, backend_orders)) 1107 new = set(rows) - seen 1108 seen |= set(rows) 1109 if not new and page > 2: 1110 break 1111 c.ep.note(f"scrolled through {len(seen)} distinct order references") 1112 c.require(len(seen) >= len(set(c.app.history_rows())), 1113 "the list kept its rows while scrolling") 1114 1115 1116 @scenario("demo", "pay", "slow") 1117 def refund_full(c: Ctx) -> None: 1118 """Pay an order, then refund all of it, and have the customer accept.""" 1119 inst = c.provision_demo() 1120 wallet = c.funded_customer(inst.currency) 1121 c.app.goto("amount") 1122 c.app.enter_amount("1.00") 1123 c.app.charge() 1124 uri = c.app.displayed_pay_uri() 1125 c.require(bool(uri), "the payment screen offered a pay URI") 1126 order_id = _order_id_from(uri) 1127 wallet.pay(uri) 1128 c.app.wait_for_success() 1129 c.app.continue_from_success() 1130 c.ep.observe() 1131 screen = c.app.goto("history") 1132 c.app.refresh_history() 1133 screen, _ = c.ep.observe() 1134 c.require(bool(screen.find(r"^Refund$")), 1135 f"a paid order offers a Refund action " 1136 f"(screen: {screen.texts()[:12]})") 1137 c.app.start_refund() 1138 c.ep.observe() 1139 c.app.submit_refund("1.00", "pos-simulator full refund") 1140 screen, _ = c.ep.observe() 1141 c.require(bool(screen.find(MARK_REFUND_URI)), 1142 f"the terminal is showing the refund code " 1143 f"(screen: {screen.texts()[:10]})") 1144 host = urllib.parse.urlsplit(inst.merchant.base).netloc 1145 refund_uri = c.app.refund_uri_for(host, inst.merchant.instance, order_id) 1146 c.ep.note(f"refund URI: {refund_uri}") 1147 wallet.accept_refund(refund_uri) 1148 time.sleep(6) 1149 status = inst.merchant.order_status(inst.token.value, order_id) 1150 c.expect(bool(status.get("refunded")), 1151 "refund-not-recorded", 1152 f"the customer accepted the refund and the backend still reports " 1153 f"refunded={status.get('refunded')!r}", 1154 json.dumps(status)[:500]) 1155 screen, _ = c.ep.observe() 1156 c.ep.note(f"refund screen now: {screen.texts()[:10]}") 1157 1158 1159 @scenario("demo", "pay", "slow") 1160 def refund_amount_edges(c: Ctx) -> None: 1161 """Refund amounts the terminal has to refuse, and the reason it gives.""" 1162 inst = c.provision_demo() 1163 wallet = c.funded_customer(inst.currency) 1164 c.app.goto("amount") 1165 c.app.enter_amount("1.00") 1166 c.app.charge() 1167 uri = c.app.displayed_pay_uri() 1168 c.require(bool(uri), "the payment screen offered a pay URI") 1169 wallet.pay(uri) 1170 c.app.wait_for_success() 1171 c.app.continue_from_success() 1172 c.app.goto("history") 1173 c.app.refresh_history() 1174 screen, _ = c.ep.observe() 1175 c.require(bool(screen.find(r"^Refund$")), "a paid order offers a Refund action") 1176 c.app.start_refund() 1177 cases = { 1178 "more than the order": "99.00", 1179 "zero": "0.00", 1180 "not a number": "abc", 1181 "two separators": "1.0.0", 1182 "negative": "-1.00", 1183 } 1184 submitted = 0 1185 for label, amount in cases.items(): 1186 c.ep.note(f"refund amount ({label}): {amount!r}") 1187 try: 1188 c.app.fill_field(r"^Amount$", amount, verify=False) 1189 except PosError as e: 1190 c.ep.note(f"the field would not take {amount!r}: {e}") 1191 continue 1192 # Master renamed this button to "Refund Taler"; a raw tap_label on the 1193 # old wording pressed nothing at all, so the form never validated and 1194 # every bad amount looked like it had been refused in silence. 1195 c.app.tap_button(APPROVE_REFUND) 1196 time.sleep(4) 1197 screen, _ = c.ep.observe() 1198 submitted += 1 1199 if screen.find(r"offer refund"): 1200 c.ep.judge([oracles.Finding( 1201 "bad-refund-accepted", 1202 f"a refund of {amount!r} ({label}) was accepted", 1203 " | ".join(screen.texts())[:400])]) 1204 # An accepted refund leaves the refund-code screen, so the form 1205 # has to be reached again from the history list for the next case. 1206 # That walk can fail -- the terminal lands on whichever order 1207 # screen it was last on -- and when it does, the cases already 1208 # submitted still count: the scenario reports what it reached 1209 # rather than discarding it. 1210 try: 1211 c.app.tap_button(r"^Abort$") 1212 time.sleep(2) 1213 c.app.goto("history") 1214 c.app.refresh_history() 1215 c.app.start_refund() 1216 except (PosError, TimeoutError) as e: 1217 c.ep.note(f"could not reopen the refund form after {label}: {e}") 1218 break 1219 continue 1220 dialog = c.app.read_dialog(screen) 1221 said_something = bool(dialog) or bool(screen.find( 1222 r"(?i)invalid amount|positive amount|Greater than order amount")) 1223 c.expect(said_something, 1224 "bad-refund-refused-silently", 1225 f"a refund of {amount!r} ({label}) was neither accepted nor " 1226 f"explained: {screen.texts()[:10]}", 1227 " | ".join(screen.texts())[:500]) 1228 if dialog: 1229 c.ep.note(f"{label}: {dialog}") 1230 c.app.dismiss_dialog() 1231 c.require(submitted >= 3, 1232 f"{submitted} of {len(cases)} bad refund amounts were submitted") 1233 1234 1235 @scenario("demo", "pay", "slow") 1236 def refund_amount_swallows_extra_dots(c: Ctx) -> None: 1237 """A refund amount with two decimal points refunds a different number. 1238 1239 `Amount.fromString` splits on "." and reads only the first two pieces, so 1240 "1.000.50" is one unit and no fraction. The refund form parses the 1241 cashier's input with it and never calls `isValidAmountStr`, which does 1242 reject a second point -- so the terminal accepts the input, says nothing, 1243 and refunds an amount nobody typed. 1244 """ 1245 inst = c.provision_demo() 1246 wallet = c.funded_customer(inst.currency) 1247 c.app.goto("amount") 1248 c.app.enter_amount("10.00") 1249 c.app.charge() 1250 uri = c.app.displayed_pay_uri() 1251 c.require(bool(uri), "the payment screen offered a pay URI") 1252 order_id = _order_id_from(uri) 1253 wallet.pay(uri) 1254 c.app.wait_for_success() 1255 c.app.continue_from_success() 1256 c.app.goto("history") 1257 c.app.refresh_history() 1258 screen, _ = c.ep.observe() 1259 c.require(bool(screen.find(r"^Refund$")), "the paid order offers a Refund action") 1260 c.app.start_refund() 1261 typed = "1.000.50" 1262 c.ep.note(f"typing {typed!r} as the refund amount on a " 1263 f"{inst.currency}:10.00 order") 1264 c.app.fill_field(r"^Amount$", typed, verify=False) 1265 c.app.tap_button(APPROVE_REFUND) 1266 time.sleep(6) 1267 screen, _ = c.ep.observe() 1268 dialog = c.app.read_dialog(screen) 1269 accepted = bool(screen.find(MARK_REFUND_URI)) 1270 c.ep.note(f"after approving: accepted={accepted}, dialog={dialog}") 1271 c.require(accepted or dialog is not None, 1272 "the terminal either accepted the refund or explained itself") 1273 if not accepted: 1274 c.ep.note("the terminal refused the malformed amount, which is correct") 1275 return 1276 time.sleep(6) 1277 status = inst.merchant.order_status(inst.token.value, order_id) 1278 refunded = status.get("refund_amount") or status.get("refund_taken") or "" 1279 c.ep.note(f"the backend recorded a refund of {refunded!r}") 1280 c.ep.judge([oracles.Finding( 1281 "refund-amount-silently-reinterpreted", 1282 f"a refund typed as {typed!r} was accepted without comment and the " 1283 f"backend recorded {refunded or 'an amount the harness could not read'}" 1284 f"; everything after the second decimal point is discarded by " 1285 f"Amount.fromString, so the merchant refunds a number nobody typed", 1286 json.dumps(status)[:700])]) 1287 1288 1289 @scenario("demo", "slow") 1290 def refund_past_deadline(c: Ctx) -> None: 1291 """Refunding an order whose refund deadline has gone. 1292 1293 The backend refuses; the terminal has a string for it 1294 ("Refund deadline has passed"). Reaching this needs an order whose refund 1295 deadline has passed -- and the backend will not *create* one that is 1296 already in the past, so it has to be created a little ahead and waited 1297 out. 1298 """ 1299 inst = c.provision_demo() 1300 order = inst.merchant.create_order( 1301 inst.token.value, f"{inst.currency}:1", 1302 "pos-simulator refund deadline", refund_deadline_s=20) 1303 order_id = order["order_id"] 1304 c.ep.note(f"created order {order_id} with a refund deadline 20s out") 1305 time.sleep(25) 1306 c.ep.note("the refund deadline has passed") 1307 try: 1308 inst.merchant.refund(inst.token.value, order_id, f"{inst.currency}:1") 1309 c.ep.note("the backend accepted a refund on an unpaid order") 1310 except merchant.MerchantError as e: 1311 c.ep.note(f"the backend refuses to refund it: {e}") 1312 c.app.goto("history") 1313 c.app.refresh_history() 1314 screen, _ = c.ep.observe() 1315 c.require(bool(c.app.history_rows(screen)), 1316 "the history list came up with rows in it") 1317 1318 1319 @scenario("demo") 1320 def history_delete_unpaid_order(c: Ctx) -> None: 1321 """Deleting an unpaid order from the history list.""" 1322 inst = c.provision_demo() 1323 order = inst.merchant.create_order( 1324 inst.token.value, f"{inst.currency}:1", "pos-simulator to delete") 1325 order_id = order["order_id"] 1326 c.ep.note(f"created order {order_id} to delete through the UI") 1327 c.app.goto("history") 1328 c.app.refresh_history() 1329 screen, _ = c.ep.observe() 1330 c.require(bool(screen.find(r"Delete order")), 1331 f"the history list offers a delete action " 1332 f"(screen: {screen.texts()[:12]})") 1333 c.ep.perform(Action("tap_label", "Delete order")) 1334 time.sleep(6) 1335 screen, _ = c.ep.observe() 1336 dialog = c.app.read_dialog(screen) 1337 if dialog and "Force" in str(dialog): 1338 c.ep.note(f"delete needed force: {dialog}") 1339 c.ep.perform(Action("tap_label", "Force delete")) 1340 time.sleep(6) 1341 screen, _ = c.ep.observe() 1342 remaining = [o for o in inst.merchant.history(inst.token.value, limit=-20) 1343 if o.get("order_id") == order_id] 1344 c.ep.note(f"after the delete the order is {'gone' if not remaining else 'still there'}") 1345 c.require(True, "a delete was attempted from the history list") 1346 1347 1348 # ========================================================================= 1349 # settings 1350 # ========================================================================= 1351 1352 1353 @scenario("demo") 1354 def settings_initial_order_screen(c: Ctx) -> None: 1355 """Switching which order screen the terminal starts on.""" 1356 inst = c.provision_demo() 1357 screen = c.app.goto("settings") 1358 c.ep.observe() 1359 c.require(bool(screen.find(r"Default order mode|Initial order screen")), 1360 f"the settings screen offers the initial-order-screen choice " 1361 f"(screen: {screen.texts()[:12]})") 1362 c.ep.perform(Action("tap_label", "Default order mode")) 1363 time.sleep(2) 1364 screen, _ = c.ep.observe() 1365 options = [t for t in screen.texts() 1366 if t in ("Order by amount", "Order by inventory")] 1367 c.require(len(options) >= 2, 1368 f"both order modes are offered ({options})") 1369 c.ep.perform(Action("tap_label", "Order by inventory")) 1370 time.sleep(2) 1371 c.ep.observe() 1372 c.app.relaunch() 1373 time.sleep(4) 1374 screen, _ = c.ep.observe() 1375 c.expect(bool(screen.find(r"^Bill( .*)?$|Everything")), 1376 "initial-order-screen-not-applied", 1377 f"the terminal was set to start on the inventory screen and came " 1378 f"up on {screen.texts()[:8]}", 1379 " | ".join(screen.texts())[:400]) 1380 c.require(True, "the initial order screen was changed and the app restarted") 1381 1382 1383 @scenario("demo") 1384 def settings_language_sweep(c: Ctx) -> None: 1385 """Every language the terminal offers, looked at for rendering defects. 1386 1387 Not a translation review: what the oracles are looking for is an 1388 unsubstituted format string, a resource name leaking as a label and text 1389 that overflows into nothing -- defects that are invisible in English 1390 because English is what the layout was built around. 1391 """ 1392 c.provision_demo() 1393 if c.dev.sdk_int < 33: 1394 raise ScenarioFailure( 1395 f"per-app languages need API 33, this device is {c.dev.sdk_int}") 1396 locales = ["de", "fr", "es", "it", "ru", "sv", "tr", "uk", "fi", "iw"] 1397 swept = 0 1398 for tag in locales: 1399 c.dev.set_app_locale(tag) 1400 c.app.relaunch() 1401 time.sleep(4) 1402 screen, _ = c.ep.observe() 1403 if not screen.activity.startswith("net.taler.merchantpos"): 1404 c.ep.judge([oracles.Finding( 1405 "locale-crash", 1406 f"the terminal does not come up in {tag!r}", 1407 " | ".join(screen.texts())[:400])]) 1408 c.dev.launch() 1409 time.sleep(4) 1410 continue 1411 swept += 1 1412 c.ep.note(f"{tag}: {screen.texts()[:8]}") 1413 for destination in ("history", "settings"): 1414 try: 1415 c.app.goto(destination) 1416 except (PosError, TimeoutError): 1417 # The drawer rows are translated, so `goto` cannot find them; 1418 # that is expected, not a finding, and the screens seen so far 1419 # have already been judged. 1420 break 1421 c.ep.observe() 1422 c.dev.set_app_locale("en") 1423 c.app.relaunch() 1424 time.sleep(4) 1425 c.ep.observe() 1426 c.require(swept >= len(locales) // 2, 1427 f"the terminal came up in {swept} of {len(locales)} languages") 1428 1429 1430 # ========================================================================= 1431 # a merchant who is not set up 1432 # ========================================================================= 1433 1434 1435 @scenario("mock") 1436 def fresh_instance_no_inventory(c: Ctx) -> None: 1437 """A merchant who has provisioned an instance and stocked nothing. 1438 1439 This is what a new user sees, and it is the case the terminal handles 1440 worst: `OrderManager.onConfigurationReceived` returns 1441 `config_error_category` when the instance has no categories, and 1442 `ConfigManager` treats any receiver error as a configuration failure -- 1443 so the terminal refuses the instance outright rather than coming up on a 1444 screen that needs no inventory. The amount-entry screen needs none: a 1445 cashier who only ever charges amounts cannot use the terminal until 1446 somebody adds a product they will never sell. 1447 """ 1448 screen = c.provision_mock("fresh", expect_success=False) 1449 deadline = time.monotonic() + 60 1450 dialog = None 1451 while time.monotonic() < deadline: 1452 screen, _ = c.ep.observe() 1453 if screen.find(r"Charge|Create order|Bill|Everything"): 1454 break 1455 dialog = c.app.read_dialog(screen) 1456 if dialog: 1457 break 1458 time.sleep(2) 1459 c.require(bool(c.mock.state.paths()), 1460 "the terminal fetched the empty instance's configuration") 1461 if dialog: 1462 c.ep.note(f"empty instance refused with: {dialog}") 1463 body = f"{dialog.title} {dialog.message}" 1464 c.ep.judge([oracles.Finding( 1465 "fresh-instance-refused", 1466 f"an instance with no products and no categories is refused with " 1467 f"{body.strip()!r}, so a freshly provisioned terminal cannot be " 1468 f"used at all -- not even for charging an amount, which needs no " 1469 f"inventory", 1470 body[:600])]) 1471 c.app.dismiss_dialog() 1472 screen, _ = c.ep.observe() 1473 c.expect(bool(screen.find(AT_LOGIN)), 1474 "stuck-after-empty-instance", 1475 f"after refusing an empty instance the terminal is not back " 1476 f"on the login form: {screen.texts()[:10]}", 1477 " | ".join(screen.texts())[:400]) 1478 return 1479 1480 c.require(bool(screen.find(r"Charge|Create order|Bill|Everything")), 1481 f"a terminal on an empty instance reached an order screen " 1482 f"(screen: {screen.texts()[:10]})") 1483 c.app.goto("amount") 1484 c.app.enter_amount("1.50") 1485 screen, _ = c.ep.observe() 1486 c.require(c.app.displayed_amount(screen) is not None, 1487 "the keypad works on an instance with no products") 1488 try: 1489 screen = c.app.goto("inventory") 1490 except (PosError, TimeoutError) as e: 1491 c.ep.judge([oracles.Finding( 1492 "empty-inventory-unreachable", 1493 f"the inventory screen cannot be opened on an instance with no " 1494 f"products: {e}", 1495 " | ".join(c.dev.dump().texts())[:400])]) 1496 return 1497 screen, _ = c.ep.observe() 1498 c.ep.note(f"empty inventory screen: {screen.texts()[:12]}") 1499 c.expect(bool(screen.find(r"(?i)no products|nothing|empty|add")), 1500 "empty-inventory-unexplained", 1501 f"the inventory screen on an instance with no products says " 1502 f"nothing about why it is empty: {screen.texts()[:12]}", 1503 " | ".join(screen.texts())[:500]) 1504 1505 1506 @scenario("mock") 1507 def instance_wrong_currency(c: Ctx) -> None: 1508 """Products priced in a currency the instance does not use. 1509 1510 The terminal has a badge for this ("Wrong currency") and a configuration 1511 error for it, so one of the two should appear -- and whichever it is, the 1512 terminal should not offer such a product for sale. 1513 """ 1514 c.provision_mock("wrong-currency", expect_success=False) 1515 time.sleep(10) 1516 screen, _ = c.ep.observe() 1517 dialog = c.app.read_dialog(screen) 1518 c.ep.note(f"screen: {screen.texts()[:12]}; dialog: {dialog}") 1519 if dialog: 1520 body = f"{dialog.title} {dialog.message}" 1521 c.expect(bool(re.search(r"(?i)currency", body)), 1522 "wrong-currency-not-named", 1523 f"products in the wrong currency produced {body[:200]!r}, " 1524 f"which does not mention the currency", 1525 body[:500]) 1526 c.require(True, "the terminal refused the badly priced inventory") 1527 return 1528 c.require(bool(screen.find(r"Charge|Bill|Everything|Create order")), 1529 f"the terminal came up on an order screen " 1530 f"(screen: {screen.texts()[:10]})") 1531 try: 1532 screen = c.app.goto("inventory") 1533 except (PosError, TimeoutError): 1534 c.require(True, "the inventory screen is not reachable") 1535 return 1536 screen, _ = c.ep.observe() 1537 c.expect(bool(screen.find(r"Wrong currency")) or 1538 not screen.find(r"Coffee|Tea"), 1539 "wrong-currency-offered-for-sale", 1540 f"a product priced in another currency is offered without a " 1541 f"warning: {screen.texts()[:12]}", 1542 " | ".join(screen.texts())[:500]) 1543 1544 1545 @scenario("mock") 1546 def instance_bad_category_reference(c: Ctx) -> None: 1547 """A product in a category that does not exist. 1548 1549 `OrderManager` has a configuration error for exactly this 1550 ("Product %1$s references unknown category ID %2$d"), which makes it a 1551 good test of whether that message survives the trip to the screen with 1552 its arguments substituted. 1553 """ 1554 c.provision_mock("bad-category", expect_success=False) 1555 time.sleep(10) 1556 screen, _ = c.ep.observe() 1557 dialog = c.app.read_dialog(screen) 1558 c.ep.note(f"screen: {screen.texts()[:12]}; dialog: {dialog}") 1559 body = f"{dialog.title} {dialog.message}" if dialog else " ".join(screen.texts()) 1560 c.expect(not re.search(r"%\d*\$?[sd]", body), 1561 "placeholder-leak", 1562 f"the unknown-category message reached the screen with its " 1563 f"placeholders unsubstituted: {body[:200]!r}", 1564 body[:500]) 1565 c.require(bool(dialog) or bool(screen.find(r"Charge|Bill|Everything")), 1566 f"the terminal either refused the inventory or came up anyway " 1567 f"(screen: {screen.texts()[:10]})") 1568 1569 1570 @scenario("mock") 1571 def instance_malformed_pos_config(c: Ctx) -> None: 1572 """`/private/pos` that is not the shape the terminal expects.""" 1573 c.provision_mock("malformed", expect_success=False) 1574 time.sleep(10) 1575 screen, _ = c.ep.observe() 1576 dialog = c.app.read_dialog(screen) 1577 c.ep.note(f"screen: {screen.texts()[:12]}; dialog: {dialog}") 1578 c.require(dialog is not None or bool(screen.find(r"Merchant portal URL")), 1579 f"the terminal reported the malformed configuration " 1580 f"(screen: {screen.texts()[:10]})") 1581 if dialog: 1582 body = f"{dialog.title} {dialog.message}" 1583 c.expect(not re.search(r"(?i)exception|kotlinx\.serialization|java\.", 1584 body), 1585 "exception-in-dialog", 1586 f"the malformed-config dialog quotes an exception: " 1587 f"{body[:200]!r}", 1588 body[:500]) 1589 c.app.dismiss_dialog() 1590 screen, _ = c.ep.observe() 1591 c.expect(bool(screen.find(AT_LOGIN)), 1592 "stuck-after-malformed-config", 1593 f"after a malformed configuration the terminal is not back on " 1594 f"the login form: {screen.texts()[:10]}", 1595 " | ".join(screen.texts())[:400]) 1596 1597 1598 @scenario("mock") 1599 def instance_empty_pos_reply(c: Ctx) -> None: 1600 """`/private/pos` that answers 200 with an empty body.""" 1601 c.provision_mock("empty-reply", expect_success=False) 1602 time.sleep(10) 1603 screen, _ = c.ep.observe() 1604 c.ep.note(f"screen: {screen.texts()[:12]}") 1605 dialog = c.app.read_dialog(screen) 1606 c.require(dialog is not None or bool(screen.find(r"Merchant portal URL")), 1607 f"the terminal reported the empty reply " 1608 f"(screen: {screen.texts()[:10]})") 1609 if dialog: 1610 c.ep.note(f"dialog: {dialog}") 1611 c.app.dismiss_dialog() 1612 1613 1614 @scenario("mock") 1615 def backend_version_mismatch(c: Ctx) -> None: 1616 """Backends too old and too new for the terminal to talk to.""" 1617 for profile in ("version-old", "version-new"): 1618 c.ep.note(f"backend version profile {profile}") 1619 screen = c.provision_mock(profile, instance=f"mock-{profile}", 1620 expect_success=False) 1621 time.sleep(10) 1622 screen, _ = c.ep.observe() 1623 dialog = c.app.read_dialog(screen) 1624 c.ep.note(f"{profile}: {dialog or screen.texts()[:10]}") 1625 body = f"{dialog.title} {dialog.message}" if dialog else " ".join(screen.texts()) 1626 c.expect(bool(dialog) or bool(screen.find(r"Merchant portal URL")), 1627 "version-mismatch-silent", 1628 f"a backend with an incompatible version ({profile}) was " 1629 f"accepted without comment: {screen.texts()[:10]}", 1630 " | ".join(screen.texts())[:500]) 1631 c.expect(not re.search(r"%\d*\$?[sd]", body), 1632 "placeholder-leak", 1633 f"the version-mismatch message has unsubstituted " 1634 f"placeholders: {body[:200]!r}", 1635 body[:400]) 1636 if dialog: 1637 c.app.dismiss_dialog() 1638 c.require(True, "both version mismatches were presented to the terminal") 1639 1640 1641 @scenario("mock", "slow") 1642 def backend_too_slow(c: Ctx) -> None: 1643 """A backend that never answers in time. 1644 1645 `ConfigFetcherFragment` shows a spinner and waits for a result; the 1646 question is whether anything ever ends that wait. 1647 """ 1648 c.provision_mock("slow", expect_success=False) 1649 for _ in range(9): 1650 time.sleep(10) 1651 screen, _ = c.ep.observe() 1652 if not screen.find(r"Fetching configuration"): 1653 break 1654 screen, _ = c.ep.observe() 1655 c.require(bool(c.mock.state.paths()), 1656 "the terminal did reach the slow backend") 1657 c.expect(not screen.find(r"Fetching configuration"), 1658 "stuck-progress", 1659 "the terminal was still fetching configuration after 90 seconds " 1660 "against a backend that does not answer, with no way out", 1661 " | ".join(screen.texts())[:400]) 1662 1663 1664 @scenario("mock", "slow") 1665 def backend_never_answers(c: Ctx) -> None: 1666 """A backend that accepts the connection and then says nothing, ever. 1667 1668 The terminal's HTTP client is built with `requestTimeoutMillis`, 1669 `socketTimeoutMillis` and `connectTimeoutMillis` all set to 1670 `INFINITE_TIMEOUT_MS` (`taler-kotlin-android`'s `createDefaultHttpClient`), 1671 so nothing on the client side ever gives up -- and the login form covers 1672 itself with a modal spinner while `isSubmitting` is true. The question is 1673 whether the cashier is ever offered a way out. 1674 """ 1675 c.provision_mock("hang", expect_success=False) 1676 c.require(True, "the login form was submitted against a backend that hangs") 1677 waited = 0 1678 for _ in range(12): 1679 time.sleep(15) 1680 waited += 15 1681 screen, _ = c.ep.observe() 1682 dialog = c.app.read_dialog(screen) 1683 if dialog or screen.find(r"Charge|Bill|Create order"): 1684 c.ep.note(f"the terminal gave up after about {waited}s: " 1685 f"{dialog or screen.texts()[:8]}") 1686 break 1687 else: 1688 screen, _ = c.ep.observe() 1689 c.ep.judge([oracles.Finding( 1690 "hung-request-never-gives-up", 1691 f"the login form was still covered by its modal spinner {waited}s " 1692 f"after submitting to a backend that never answers, with nothing " 1693 f"to cancel and nothing to read; the HTTP client is configured " 1694 f"with infinite request, socket and connect timeouts", 1695 " | ".join(screen.texts())[:400] or 1696 f"{len(screen.nodes)} nodes, none labelled or tappable")]) 1697 c.require(bool(c.mock.state.paths()), 1698 "the terminal did reach the backend that hangs") 1699 # Back must not get out of it either, or there would be a way out. 1700 c.ep.perform(Action("back")) 1701 time.sleep(3) 1702 screen, _ = c.ep.observe() 1703 c.ep.note(f"after a back press: {screen.texts()[:8] or 'nothing readable'}") 1704 1705 1706 @scenario("mock") 1707 def pos_config_url_encodes_the_separator(c: Ctx) -> None: 1708 """The path the terminal asks for its configuration on. 1709 1710 `ConfigManager` builds it with `Uri.Builder.appendPath("private/pos")`, 1711 which percent-encodes the separator because a path segment may contain 1712 one -- so the request goes to `/instances/<id>/private%2Fpos`. The GNU 1713 Taler backend decodes the path before routing and answers anyway, which is 1714 why this has never shown up; a reverse proxy need not, and Apache with its 1715 default `AllowEncodedSlashes Off` rejects such a request outright. 1716 """ 1717 c.provision_mock("healthy", expect_success=False) 1718 deadline = time.monotonic() + 40 1719 while time.monotonic() < deadline: 1720 if any("private" in p for p in c.mock.state.paths()): 1721 break 1722 time.sleep(2) 1723 c.ep.observe() 1724 asked = [p for p in c.mock.state.paths() if "private" in p] 1725 c.require(bool(asked), 1726 f"the terminal asked the mock backend for its configuration " 1727 f"(paths seen: {c.mock.state.paths()[:8]})") 1728 c.ep.note(f"configuration paths requested: {asked[:5]}") 1729 encoded = c.mock.state.encoded_slash_requests() 1730 c.expect(not encoded, 1731 "encoded-path-separator", 1732 f"the terminal asks for its configuration at " 1733 f"{encoded[0] if encoded else ''!r}, with the path separator " 1734 f"percent-encoded; a backend behind a proxy that does not decode " 1735 f"encoded slashes answers 404 and the terminal cannot be " 1736 f"configured at all", 1737 "\n".join(encoded[:5])) 1738 1739 1740 @scenario("mock", "slow") 1741 def huge_inventory(c: Ctx) -> None: 1742 """Four hundred products in the grid.""" 1743 c.provision_mock("huge-inventory") 1744 screen, _ = c.ep.observe() 1745 try: 1746 screen = c.app.goto("inventory") 1747 except (PosError, TimeoutError) as e: 1748 raise ScenarioFailure(f"the inventory screen never came up: {e}") 1749 c.ep.observe() 1750 c.require(bool(screen.find(r"Product \d|Everything")), 1751 f"the grid is showing products (screen: {screen.texts()[:10]})") 1752 for _ in range(6): 1753 c.ep.perform(Action("scroll_down"), screen) 1754 screen, _ = c.ep.observe() 1755 added = c.app.add_products(3) 1756 c.ep.note(f"added {added} from a 400-product grid") 1757 screen, _ = c.ep.observe() 1758 c.require(bool(screen.find(r"^Bill( .*)?$")), 1759 "an order can still be billed from a large grid") 1760 1761 1762 @scenario("mock") 1763 def unicode_product_names(c: Ctx) -> None: 1764 """Product names in scripts the layout was not designed around.""" 1765 c.provision_mock("unicode") 1766 c.ep.observe() 1767 try: 1768 screen = c.app.goto("inventory") 1769 except (PosError, TimeoutError) as e: 1770 raise ScenarioFailure(f"the inventory screen never came up: {e}") 1771 screen, _ = c.ep.observe() 1772 c.ep.note(f"grid shows: {screen.texts()[:16]}") 1773 c.require(len(screen.texts()) > 3, 1774 "the grid rendered something for the unicode products") 1775 added = c.app.add_products(2) 1776 c.ep.note(f"added: {added}") 1777 screen, _ = c.ep.observe() 1778 c.app.bill() 1779 screen, _ = c.ep.observe() 1780 c.require(bool(screen.find(r"scan QR Code|Cancel payment")), 1781 "an order of unicode-named products reached the payment screen") 1782 c.app.cancel_payment() 1783 c.ep.observe() 1784 1785 1786 # ========================================================================= 1787 # the environment turning against it 1788 # ========================================================================= 1789 1790 1791 @scenario("demo", "slow") 1792 def offline_during_payment(c: Ctx) -> None: 1793 """The network goes away while the payment screen is polling.""" 1794 inst = c.provision_demo() 1795 c.app.goto("amount") 1796 c.app.enter_amount("1.00") 1797 c.app.charge() 1798 screen, _ = c.ep.observe() 1799 c.require(bool(screen.find(r"scan QR Code|Cancel payment")), 1800 "the terminal is on the payment screen") 1801 uri = c.app.displayed_pay_uri() 1802 c.ep.note(f"pay URI before going offline: {uri}") 1803 c.ep.perform(Action("offline", True)) 1804 time.sleep(15) 1805 screen, _ = c.ep.observe() 1806 c.ep.note(f"offline, the payment screen shows: {screen.texts()[:10]}") 1807 c.ep.perform(Action("offline", False)) 1808 time.sleep(15) 1809 screen, _ = c.ep.observe() 1810 c.expect(screen.activity.startswith("net.taler.merchantpos"), 1811 "crash-when-network-returns", 1812 f"the terminal did not survive the network coming back: " 1813 f"{screen.activity}", 1814 " | ".join(screen.texts())[:400]) 1815 c.require(True, "the network was taken away and given back mid-payment") 1816 1817 1818 @scenario("demo") 1819 def offline_at_startup(c: Ctx) -> None: 1820 """Starting a configured terminal with no network at all.""" 1821 inst = c.provision_demo() 1822 c.ep.perform(Action("offline", True)) 1823 c.app.relaunch() 1824 time.sleep(12) 1825 screen, _ = c.ep.observe() 1826 c.ep.note(f"offline start shows: {screen.texts()[:12]}") 1827 dialog = c.app.read_dialog(screen) 1828 if dialog: 1829 c.ep.note(f"dialog: {dialog}") 1830 c.expect(not screen.find(r"Fetching configuration"), 1831 "stuck-progress", 1832 "a terminal started with no network is still fetching " 1833 "configuration", 1834 " | ".join(screen.texts())[:400]) 1835 c.expect(bool(screen.find(r"Charge|Bill|Create order|Everything")) or 1836 bool(dialog) or bool(screen.find(r"Merchant portal URL")), 1837 "offline-start-dead-end", 1838 f"a terminal started with no network shows neither its cached " 1839 f"configuration nor an explanation: {screen.texts()[:10]}", 1840 " | ".join(screen.texts())[:500]) 1841 c.ep.perform(Action("offline", False)) 1842 time.sleep(8) 1843 c.ep.observe() 1844 c.require(True, "the terminal was started offline") 1845 1846 1847 @scenario("demo") 1848 def process_death_mid_payment(c: Ctx) -> None: 1849 """The process is killed while an order is waiting to be paid.""" 1850 inst = c.provision_demo() 1851 c.app.goto("amount") 1852 c.app.enter_amount("1.00") 1853 c.app.charge() 1854 screen, _ = c.ep.observe() 1855 c.require(bool(screen.find(r"scan QR Code|Cancel payment")), 1856 "the terminal is on the payment screen") 1857 uri = c.app.displayed_pay_uri() 1858 order_id = _order_id_from(uri) if uri else None 1859 c.ep.note(f"order {order_id} was open when the process was killed") 1860 c.ep.perform(Action("process_death")) 1861 time.sleep(10) 1862 screen, _ = c.ep.observe() 1863 c.require(screen.activity.startswith("net.taler.merchantpos"), 1864 f"the terminal came back after being killed " 1865 f"(showing {screen.activity})") 1866 c.ep.note(f"after process death: {screen.texts()[:12]}") 1867 if order_id: 1868 status = inst.merchant.order_status(inst.token.value, order_id) 1869 c.ep.note(f"the open order is now {status.get('order_status')!r} at the backend") 1870 remaining = [o for o in inst.merchant.history(inst.token.value, limit=-10) 1871 if o.get("order_id") == order_id and not o.get("paid")] 1872 if remaining: 1873 c.ep.judge([oracles.Finding( 1874 "orphaned-order", 1875 f"killing the terminal mid-payment left unpaid order " 1876 f"{order_id} behind at the backend", 1877 str(remaining)[:400])]) 1878 1879 1880 @scenario("demo") 1881 def back_button_sweep(c: Ctx) -> None: 1882 """Pressing back from every screen, which is the cheapest way out of each. 1883 1884 The terminal's back handling is hand-written: two presses to exit from an 1885 order screen, home from the login screen, pop otherwise. What is checked 1886 is that none of those paths ends somewhere with nothing on it. 1887 """ 1888 c.provision_demo() 1889 for destination in ("amount", "inventory", "history", "settings"): 1890 try: 1891 c.app.goto(destination) 1892 except (PosError, TimeoutError) as e: 1893 c.ep.note(f"could not reach {destination}: {e}") 1894 continue 1895 screen, _ = c.ep.observe() 1896 c.ep.perform(Action("back")) 1897 time.sleep(2) 1898 screen, _ = c.ep.observe() 1899 if not screen.activity.startswith("net.taler.merchantpos"): 1900 c.ep.note(f"back from {destination} left the app") 1901 c.dev.launch() 1902 time.sleep(4) 1903 continue 1904 c.expect(bool(screen.labelled()), 1905 "blank-after-back", 1906 f"pressing back from the {destination} screen left a screen " 1907 f"with no labels on it", 1908 screen.signature()[:400]) 1909 c.require(True, "back was pressed from every destination") 1910 1911 1912 @scenario("demo") 1913 def drawer_locked_without_config(c: Ctx) -> None: 1914 """The navigation drawer must stay shut while there is no configuration. 1915 1916 `gesturesEnabled` is switched off and the hamburger replaced by a spacer 1917 while the config is invalid, so an unconfigured terminal cannot be 1918 navigated away from its login screen -- which is deliberate, and worth 1919 confirming rather than assuming. 1920 """ 1921 c.app.fresh_start() 1922 screen, _ = c.ep.observe() 1923 c.require(bool(screen.find(r"Merchant portal URL")), 1924 "the terminal is unconfigured and on the login screen") 1925 c.ep.perform(Action("drawer_gesture")) 1926 time.sleep(2) 1927 screen, _ = c.ep.observe() 1928 c.expect(not (screen.find(r"^History$") and screen.find(r"^Settings$")), 1929 "drawer-opens-without-config", 1930 "the navigation drawer opens on an unconfigured terminal, which " 1931 "leads to screens that have no backend to talk to", 1932 " | ".join(screen.texts())[:400]) 1933 c.require(True, "the drawer gesture was tried without a configuration") 1934 1935 1936 @scenario("demo") 1937 def accessibility_names(c: Ctx) -> None: 1938 """Every screen, checked for controls a screen reader cannot announce.""" 1939 c.provision_demo() 1940 screens = ["amount", "inventory", "history", "settings"] 1941 for destination in screens: 1942 try: 1943 c.app.goto(destination) 1944 except (PosError, TimeoutError) as e: 1945 c.ep.note(f"could not reach {destination}: {e}") 1946 continue 1947 screen, _ = c.ep.observe() 1948 anonymous = screen.unnamed_clickables() 1949 c.ep.note(f"{destination}: {len(anonymous)} unnamed control(s)") 1950 c.app.goto("amount") 1951 c.app.enter_amount("1.00") 1952 c.app.charge() 1953 c.ep.observe() 1954 c.app.cancel_payment() 1955 c.ep.observe() 1956 c.require(True, "every screen was inspected for accessible names") 1957 1958 1959 @scenario("mock") 1960 def order_sold_out_between_taps(c: Ctx) -> None: 1961 """The product sells out between ringing it up and billing it. 1962 1963 A 410 carrying `product_id`, `requested_quantity` and 1964 `available_quantity` is the one backend error the terminal translates 1965 rather than quotes: `Response.parseInventoryAvailabilityError` builds a 1966 sentence from it and `PaymentManager.looksLikeInventoryError` recognises 1967 that sentence and reloads the inventory. Neither can be reached by 1968 anything a healthy backend says. 1969 """ 1970 c.provision_mock("inventory-gone") 1971 c.app.goto("inventory") 1972 added = c.app.add_products(1) 1973 c.require(bool(added), f"a product was added to the order ({added})") 1974 c.ep.observe() 1975 c.ep.perform(Action("tap_label", "Bill")) 1976 time.sleep(8) 1977 screen, _ = c.ep.observe() 1978 dialog = c.app.read_dialog(screen) 1979 body = (f"{dialog.title} {dialog.message}" if dialog 1980 else " ".join(screen.texts())) 1981 c.ep.note(f"sold-out order: {body[:300]}") 1982 c.require(dialog is not None or bool(screen.find(r"(?i)stock|inventory|unavailable")), 1983 f"the terminal reported the sold-out product " 1984 f"(screen: {screen.texts()[:12]})") 1985 c.expect(bool(re.search(r"(?i)stock|inventor|unavailable|sold", body)), 1986 "sold-out-reported-as-a-generic-error", 1987 f"a product that had sold out produced: {body[:200]!r} -- the " 1988 f"backend said which product and how many were left", 1989 body[:600]) 1990 c.expect(not re.search(r"(?i)exception|io\.ktor|kotlinx\.", body), 1991 "exception-in-dialog", 1992 f"the sold-out dialog quotes an exception: {body[:200]!r}", 1993 body[:600]) 1994 1995 1996 @scenario("mock") 1997 def insecure_pay_uri_offered_upgrade(c: Ctx) -> None: 1998 """A backend behind plain HTTP hands out a taler+http:// pay URI. 1999 2000 The twister scenarios reach the same dialog on the real backend; this one 2001 is here because the mock can hold the URI insecure for as long as the 2002 terminal keeps polling, with no re-arming and no race -- so it is the 2003 scenario that tells a broken dialog from a flaky one. 2004 """ 2005 c.provision_mock("insecure-pay-uri") 2006 c.app.goto("amount") 2007 c.app.enter_amount("1.00") 2008 # Not `Pos.charge`: that waits for the payment screen, and the whole point 2009 # here is that a dialog comes up over it instead. 2010 c.ep.perform(Action("tap_label", "Create order (charge amount)")) 2011 deadline = time.monotonic() + 60 2012 screen = c.app._stable_dump() 2013 while time.monotonic() < deadline: 2014 screen = c.app._stable_dump() 2015 if _insecure_dialog_on(screen): 2016 break 2017 time.sleep(1.5) 2018 c.ep.observe() 2019 c.require(_insecure_dialog_on(screen), 2020 f"the terminal objected to the taler+http:// pay URI " 2021 f"(screen: {screen.texts()[:12]})") 2022 dialog = c.app.read_dialog(screen) 2023 c.ep.note(f"insecure-URI dialog: {dialog or screen.texts()[:6]}") 2024 body = (f"{dialog.title} {dialog.message}" if dialog 2025 else " ".join(screen.texts())) 2026 # Not "does it say http": the terminal deliberately says "payment link" 2027 # rather than naming a scheme, which is better wording for a cashier and 2028 # which an oracle looking for the jargon called a defect. What has to be 2029 # true is that the problem is named and all three ways out are offered. 2030 c.expect(bool(re.search(r"(?i)payment link|link", body)), 2031 "insecure-uri-dialog-says-nothing", 2032 f"the dialog about an insecure pay URI does not mention the " 2033 f"payment link at all: {body[:200]!r}", 2034 body[:600]) 2035 offered = [label for label in ("Try fixed link", "Continue as is", 2036 "Cancel order") 2037 if screen.find(f"^{re.escape(label)}$")] 2038 c.expect(len(offered) == 3, 2039 "insecure-uri-dialog-missing-a-way-out", 2040 f"the dialog offered {offered} and not all three of upgrading, " 2041 f"continuing and cancelling", 2042 " | ".join(screen.texts())[:400]) 2043 c.ep.perform(Action("tap_label", "Try fixed link")) 2044 time.sleep(5) 2045 screen, _ = c.ep.observe() 2046 uri = c.app.displayed_pay_uri() 2047 c.ep.note(f"after the upgrade the terminal shows {uri!r}") 2048 c.expect(uri is None or uri.startswith("taler://"), 2049 "https-upgrade-did-not-upgrade", 2050 f"upgrading a taler+http:// URI left the terminal showing {uri!r}", 2051 " | ".join(screen.texts())[:500]) 2052 2053 2054 @scenario("demo", "pay", "slow") 2055 def history_force_delete_claimed_order(c: Ctx) -> None: 2056 """Deleting, from the history list, an order a customer has claimed. 2057 2058 An ordinary delete is refused once an order is claimed, and the history 2059 list has its own force-delete confirmation for that -- separate code from 2060 the payment screen's, and the one path to `HistoryManager.forceDeleteOrder`. 2061 """ 2062 inst = c.provision_demo() 2063 # Claiming without paying still makes wallet-core choose a 2064 # contract choice, and choosing one needs the balance to cover 2065 # it -- so this wants a funded wallet even though it never pays. 2066 wallet = c.funded_customer(inst.currency) 2067 order = inst.merchant.create_order( 2068 inst.token.value, f"{inst.currency}:1", "pos-simulator to force-delete") 2069 order_id = order["order_id"] 2070 uri = inst.merchant.pay_uri(inst.token.value, order_id) 2071 c.require(bool(uri), f"the backend gave a pay URI for order {order_id}") 2072 wallet.claim_only(uri) 2073 status = inst.merchant.order_status(inst.token.value, order_id) 2074 c.require(status.get("order_status") == "claimed", 2075 f"the order is claimed and so cannot be deleted the ordinary way " 2076 f"({status.get('order_status')})") 2077 c.app.goto("history") 2078 c.app.refresh_history() 2079 screen, _ = c.ep.observe() 2080 c.require(bool(screen.find(r"Delete order")), 2081 f"the history list offers a delete action " 2082 f"(screen: {screen.texts()[:12]})") 2083 c.ep.perform(Action("tap_label", "Delete order")) 2084 time.sleep(7) 2085 screen, _ = c.ep.observe() 2086 dialog = c.app.read_dialog(screen) 2087 c.ep.note(f"deleting a claimed order from the history list: {dialog}") 2088 c.expect(dialog is not None and 2089 bool(re.search(r"(?i)force|anyway|claimed", str(dialog))), 2090 "no-force-delete-prompt-in-history", 2091 f"deleting a claimed order from the history list offered no way " 2092 f"to force it: {dialog or screen.texts()[:12]}", 2093 " | ".join(screen.texts())[:500]) 2094 if dialog is not None and re.search(r"(?i)force", str(dialog)): 2095 c.ep.perform(Action("tap_label", "Force delete")) 2096 time.sleep(8) 2097 c.ep.observe() 2098 remaining = [o for o in inst.merchant.history(inst.token.value, limit=-20) 2099 if o.get("order_id") == order_id] 2100 c.expect(not remaining, 2101 "force-delete-left-the-order", 2102 f"force-deleting claimed order {order_id} from the history " 2103 f"list left it in the backend's order list", 2104 str(remaining)[:400]) 2105 2106 2107 @scenario("demo") 2108 def history_show_payment_again(c: Ctx) -> None: 2109 """Pick an unpaid order out of the history and go back to its code. 2110 2111 The row for an order nobody has paid offers "Show payment", which resumes 2112 a payment the terminal may never have started -- `PaymentManager. 2113 resumePayment` rebuilds one from the history entry alone. Every other 2114 route to the payment screen comes from having just created the order. 2115 """ 2116 inst = c.provision_demo() 2117 order = inst.merchant.create_order( 2118 inst.token.value, f"{inst.currency}:2", "pos-simulator to resume") 2119 order_id = order["order_id"] 2120 c.ep.note(f"created unpaid order {order_id} outside the terminal") 2121 c.app.goto("history") 2122 c.app.refresh_history() 2123 screen, _ = c.ep.observe() 2124 c.require(bool(screen.find(r"^Show payment$")), 2125 f"an unpaid order offers 'Show payment' " 2126 f"({screen.texts()[:14]})") 2127 c.ep.perform(Action("tap_label", "Show payment")) 2128 time.sleep(6) 2129 screen, _ = c.ep.observe() 2130 uri = c.app.displayed_pay_uri() 2131 c.ep.note(f"resumed payment shows {uri}") 2132 c.require(bool(screen.find(MARK_PAYMENT)) or bool(uri), 2133 f"the terminal went back to a payment screen " 2134 f"({screen.texts()[:14]})") 2135 shown = _order_id_from(uri) 2136 c.expect(uri is None or shown is not None, 2137 "resumed-payment-has-no-order", 2138 f"resuming a payment showed a URI naming no order: {uri!r}", 2139 " | ".join(screen.texts())[:400]) 2140 if shown is not None: 2141 c.expect(shown == order_id, 2142 "resumed-the-wrong-order", 2143 f"'Show payment' on order {order_id} showed a code for " 2144 f"{shown}", 2145 " | ".join(screen.texts())[:400]) 2146 2147 2148 @scenario("demo", "pay", "slow") 2149 def history_show_refund_after_restart(c: Ctx) -> None: 2150 """"Show refund" on an order whose refund the terminal has forgotten. 2151 2152 `onShowRefundClicked` asks the refund manager to resume, and when it 2153 cannot -- which is what a restart leaves behind, since the pending refund 2154 lives in memory -- it has to say so rather than open an empty screen. 2155 Both arms are here: the refund is made, then the terminal is restarted. 2156 """ 2157 inst = c.provision_demo() 2158 wallet = c.funded_customer(inst.currency) 2159 c.app.goto("amount") 2160 c.app.enter_amount("2.00") 2161 c.app.charge() 2162 uri = c.app.displayed_pay_uri() 2163 c.require(bool(uri), "the payment screen offered a pay URI") 2164 order_id = _order_id_from(uri) 2165 wallet.pay(uri) 2166 c.app.wait_for_success() 2167 c.app.continue_from_success() 2168 c.app.goto("history") 2169 c.app.refresh_history() 2170 screen, _ = c.ep.observe() 2171 c.require(bool(screen.find(r"^Refund$")), 2172 f"the paid order offers a refund ({screen.texts()[:14]})") 2173 c.app.start_refund() 2174 c.app.submit_refund("1.00", "pos-simulator resume") 2175 screen, _ = c.ep.observe() 2176 c.ep.note(f"refund made: {screen.texts()[:10]}") 2177 # Before the restart the terminal still holds the refund. 2178 c.app.goto("history") 2179 c.app.refresh_history() 2180 screen, _ = c.ep.observe() 2181 if screen.find(r"^Show refund$"): 2182 c.ep.perform(Action("tap_label", "Show refund")) 2183 time.sleep(5) 2184 screen, _ = c.ep.observe() 2185 c.ep.note(f"show refund, still in memory: {screen.texts()[:12]}") 2186 c.expect(bool(screen.find(MARK_REFUND_URI)), 2187 "show-refund-opened-nothing", 2188 "'Show refund' on a refund the terminal still holds did not " 2189 "open the refund code", 2190 " | ".join(screen.texts())[:400]) 2191 # And after it, the manager has nothing to resume from. 2192 c.app.relaunch() 2193 c.app.wait_for_order_entry(timeout=120) 2194 # The demo backend answers the odd 502, and the history screen fetches as 2195 # it opens -- so the dialog can be up before `goto` has anything to look 2196 # for. Clearing and retrying is the difference between a scenario that 2197 # reports the app and one that reports the weather. 2198 _clear_dialog(c) 2199 c.app.goto("history") 2200 _tap_through_dialogs(c, r"Refresh history") 2201 time.sleep(6) 2202 screen, _ = c.ep.observe() 2203 if not screen.find(r"^Show refund$"): 2204 c.ep.note("after the restart the row no longer offers 'Show refund'") 2205 c.require(True, "both arms were reached as far as the app allows") 2206 return 2207 c.ep.perform(Action("tap_label", "Show refund")) 2208 time.sleep(5) 2209 screen, _ = c.ep.observe() 2210 body = " ".join(screen.texts()) 2211 c.ep.note(f"show refund after a restart: {screen.texts()[:12]}") 2212 c.require(True, "'Show refund' was pressed on a forgotten refund") 2213 c.expect(bool(screen.find(MARK_REFUND_URI)) or 2214 bool(re.search(r"(?i)no longer available|refund state", body)), 2215 "forgotten-refund-opens-nothing", 2216 f"'Show refund' after a restart neither opened the code nor said " 2217 f"why not: {screen.texts()[:12]}", 2218 body[:400]) 2219 2220 2221 # ========================================================================= 2222 # what a merchant puts in the catalogue 2223 # ========================================================================= 2224 # 2225 # Almost everything a product can carry is optional, and the healthy profile 2226 # fills in none of it: no picture, a name that is the description, integer 2227 # stock counts, no tax. Each of those is a branch the terminal takes only for 2228 # a merchant who has filled the field in -- `ConfigProduct.displayName`, 2229 # `displayDescription`, `stockLimit`'s three BigDecimal arms, 2230 # `toContractProduct`'s four `takeIf`s, and the two places the order screen 2231 # decodes `image` into a bitmap. 2232 2233 2234 @scenario("mock") 2235 def inventory_rich_catalogue(c: Ctx) -> None: 2236 """A catalogue with pictures, translations, taxes and decimal stock.""" 2237 c.provision_mock("rich-catalogue") 2238 screen = c.app.goto("inventory") 2239 c.ep.observe() 2240 texts = " ".join(screen.texts()) 2241 c.require(bool(screen.find(r"Espresso")), 2242 f"the rich catalogue is on screen ({screen.texts()[:12]})") 2243 # A name that differs from the description puts both on the card. 2244 c.expect(bool(screen.find(r"Espresso")) and 2245 bool(screen.find(r"Single shot")), 2246 "product-name-hides-the-description", 2247 "a product whose name and description differ showed only one of " 2248 f"them: {screen.texts()[:14]}", 2249 texts[:600]) 2250 # Sold out: six of six sold, so the card says so instead of offering it. 2251 pastry = screen.find(r"Pastry") 2252 c.require(pastry is not None, "the sold-out product is listed") 2253 c.expect(bool(screen.find(r"(?i)out of stock|unavailable")), 2254 "sold-out-product-looks-sellable", 2255 "a product with all its stock sold carries no badge saying so: " 2256 f"{screen.texts()[:14]}", 2257 texts[:600]) 2258 before = len(c.app.history_rows(screen)) 2259 c.ep.perform(Action("tap_label", "Pastry"), screen) 2260 time.sleep(2) 2261 after_screen, _ = c.ep.observe() 2262 c.expect(not bool(after_screen.find(r"Total: .*[1-9]")), 2263 "sold-out-product-can-be-ordered", 2264 "tapping a product that has sold out added it to the order", 2265 " | ".join(after_screen.texts())[:500]) 2266 # A product priced in decimal units: the stock arithmetic is BigDecimal, 2267 # and an integer count never reaches it. 2268 c.require(bool(screen.find(r"Flour")), 2269 "the product whose stock is a decimal string is listed") 2270 c.ep.note(f"catalogue: {screen.texts()[:18]}") 2271 2272 2273 @scenario("mock", "form") 2274 def backend_wants_the_token_prefix(c: Ctx) -> None: 2275 """A backend that refuses a bare token and wants `secret-token:` on it. 2276 2277 `ConfigManager.fetchPosConfig` sends the token as it has it, and on a 401 2278 sends it again with the prefix. A backend that accepts the bare form -- 2279 which every other profile does, and the demo backend does -- never makes 2280 the terminal try the second one. 2281 """ 2282 c.provision_mock("token-needs-prefix", need_form=True) 2283 screen = c.app.wait_for_order_entry(timeout=90) 2284 c.ep.observe() 2285 assert c.mock is not None 2286 c.require(c.mock.state.bare_token_requests > 0, 2287 f"the backend refused the bare token at least once " 2288 f"({c.mock.state.bare_token_requests})") 2289 instance, _ = c.app.bound_instance() 2290 c.expect(instance == "mockshop", 2291 "token-prefix-retry-failed", 2292 "a backend that wants the token prefixed left the terminal " 2293 f"bound to {instance!r} after refusing the bare form", 2294 " | ".join(screen.texts())[:400]) 2295 2296 2297 @scenario("mock") 2298 def stock_counts_survive_a_restart(c: Ctx) -> None: 2299 """Stock the terminal learned once is still there after a restart. 2300 2301 `ConfigManager.applyCachedStockData` copies the sold and lost counts from 2302 the cached configuration onto a freshly fetched one, so the grid does not 2303 go back to showing full shelves while the per-product fetches are still in 2304 flight. It needs a cache with stock in it, which means a second start. 2305 """ 2306 c.provision_mock("rich-catalogue") 2307 c.app.goto("inventory") 2308 time.sleep(6) # let the per-product stock fetches land 2309 screen, _ = c.ep.observe() 2310 c.require(bool(screen.find(r"Espresso")), "the catalogue loaded once") 2311 c.app.relaunch() 2312 screen = c.app.wait_for_order_entry(timeout=120) 2313 c.app.goto("inventory") 2314 screen, _ = c.ep.observe() 2315 c.ep.note(f"after a restart: {screen.texts()[:14]}") 2316 c.require(bool(screen.find(r"Espresso")), 2317 f"the catalogue came back after a restart " 2318 f"({screen.texts()[:12]})") 2319 c.expect(bool(screen.find(r"(?i)out of stock|unavailable")), 2320 "stock-forgotten-across-a-restart", 2321 "after a restart the sold-out product was offered again, so the " 2322 "counts the terminal had already learned were dropped", 2323 " | ".join(screen.texts())[:500]) 2324 2325 2326 # ========================================================================= 2327 # click sequences nothing else performs 2328 # ========================================================================= 2329 2330 2331 @scenario("demo") 2332 def order_line_quantity(c: Ctx) -> None: 2333 """Select a line of the order and change its quantity. 2334 2335 Adding a product is one tap and every scenario does it. Selecting the 2336 resulting *line* and using +1 and -1 is three more, and nothing did: the 2337 order screen's `onSelectProduct`, `onIncrease` and `onDecrease` were 2338 untaken on both layouts. 2339 """ 2340 c.provision_demo() 2341 screen = c.app.goto("inventory") 2342 c.ep.observe() 2343 added = c.app.add_products(1) 2344 c.require(bool(added), f"a product is in the order ({added})") 2345 name = added[0] 2346 screen, _ = c.ep.observe() 2347 total_one = _order_total(screen) 2348 c.require(total_one is not None, 2349 f"the order shows a total ({screen.texts()[:12]})") 2350 # Select the order line, which is the row in the order pane rather than 2351 # the product card in the grid. 2352 c.app.select_order_line(name) 2353 screen, _ = c.ep.observe() 2354 c.app.tap_button(r"^\+1$") 2355 time.sleep(2) 2356 screen, _ = c.ep.observe() 2357 total_two = _order_total(screen) 2358 c.ep.note(f"one {name}: {total_one}, two: {total_two}") 2359 c.expect(total_two is not None and total_two != total_one, 2360 "increase-did-nothing", 2361 f"pressing +1 on a selected order line left the total at " 2362 f"{total_one}", 2363 " | ".join(screen.texts())[:500]) 2364 c.app.tap_button(r"^-1$") 2365 time.sleep(2) 2366 screen, _ = c.ep.observe() 2367 total_back = _order_total(screen) 2368 c.ep.note(f"after -1: {total_back}") 2369 c.expect(total_back == total_one, 2370 "decrease-does-not-undo-increase", 2371 f"+1 then -1 left the total at {total_back} and not back at " 2372 f"{total_one}", 2373 " | ".join(screen.texts())[:500]) 2374 2375 2376 @scenario("demo") 2377 def order_custom_product_invalid_amount(c: Ctx) -> None: 2378 """The custom-product dialog refuses an amount it cannot parse.""" 2379 c.provision_demo() 2380 c.app.goto("inventory") 2381 c.ep.observe() 2382 c.app.open_custom_product_dialog() 2383 screen, _ = c.ep.observe() 2384 c.require(bool(screen.find(r"(?i)custom")), 2385 f"the custom-product dialog is open ({screen.texts()[:12]})") 2386 c.app.fill_custom_amount("not an amount") 2387 # On a short screen the dialog's buttons are under the keyboard, and a tap 2388 # aimed at Add presses whatever key is there -- so whether Add can be 2389 # reached at all is the first thing to check, and a failure here is the 2390 # app's, not the scenario's. 2391 reachable = c.app.control_reachable(r"^Add$") 2392 c.ep.note(f"Add reachable with the keyboard up: {reachable}") 2393 if not c.expect(reachable, 2394 "dialog-buttons-behind-the-keyboard", 2395 "the custom-product dialog's Add button is under the " 2396 "keyboard the dialog itself raised, so the only thing a " 2397 "tap on it presses is a letter", 2398 " | ".join(c.app._stable_dump().texts())[:400]): 2399 return 2400 c.ep.perform(Action("tap_label", "Add")) 2401 time.sleep(3) 2402 screen, _ = c.ep.observe() 2403 still_open = bool(screen.find(r"(?i)invalid|custom")) 2404 c.ep.note(f"after a bad amount: {screen.texts()[:12]}") 2405 c.require(still_open, 2406 f"the dialog is still up after a bad amount " 2407 f"({screen.texts()[:12]})") 2408 c.expect(bool(screen.find(r"(?i)invalid amount")), 2409 "bad-custom-amount-unexplained", 2410 f"typing a word where the price goes produced no message: " 2411 f"{screen.texts()[:12]}", 2412 " | ".join(screen.texts())[:500]) 2413 # And then a good one, which is the other arm. 2414 c.app.fill_custom_amount("3.50") 2415 c.ep.perform(Action("tap_label", "Add")) 2416 time.sleep(3) 2417 screen, _ = c.ep.observe() 2418 c.ep.note(f"after a good amount: {screen.texts()[:12]}") 2419 c.expect(bool(screen.find(r"Total: .*3\.50")) or 2420 bool(screen.find(r"3\.50")), 2421 "custom-product-not-added", 2422 "a custom product with a valid price did not reach the order", 2423 " | ".join(screen.texts())[:500]) 2424 2425 2426 @scenario("demo") 2427 def config_help_card_buttons(c: Ctx) -> None: 2428 """The three buttons on the login screen's help card. 2429 2430 "Fill demo credentials" has a scenario of its own; the tutorial link and 2431 the review-URL button next to it had none, and each is a separate lambda 2432 on the config screen. 2433 """ 2434 c.app.fresh_start() 2435 screen = c.app.wait_for_config_screen() 2436 if not screen.find(r"Fill demo credentials"): 2437 c.app.tap_button(r"No account\?|No instance\?") 2438 time.sleep(1) 2439 screen = c.app._stable_dump() 2440 c.ep.observe() 2441 c.require(bool(screen.find(r"Fill demo credentials")), 2442 f"the help card is open ({screen.texts()[:14]})") 2443 for label in ("Fill review URL", "Use review backend", "Review"): 2444 if screen.find(f"^{re.escape(label)}$"): 2445 c.ep.perform(Action("tap_label", label)) 2446 time.sleep(2) 2447 screen, _ = c.ep.observe() 2448 c.ep.note(f"after {label!r}: {screen.texts()[:12]}") 2449 host, _ = c.app.login_form_values() 2450 c.expect(bool(host), 2451 "review-url-button-cleared-the-host", 2452 f"{label!r} left the merchant URL empty", 2453 " | ".join(screen.texts())[:400]) 2454 break 2455 else: 2456 c.ep.note("no review-URL button on this build") 2457 c.require(True, "the help card's buttons were pressed") 2458 2459 2460 # ========================================================================= 2461 # two-factor login 2462 # ========================================================================= 2463 # 2464 # `backend.demo.taler.net` has `mandatory_tan_channels: ["email"]`, so a login 2465 # there answers 202 with a challenge and mails the code -- which is why round 2466 # one could not reach this path and said so. A mock can be that backend with 2467 # a code the harness already knows, and the terminal cannot tell the 2468 # difference: the whole dance is four requests and one header. 2469 2470 2471 # `MfaUtils.MfaCodeInput` is a `BasicTextField` with transparent text that 2472 # draws the digits itself, so there is nothing in the hierarchy holding a value 2473 # to find or to verify -- and it calls `requestFocus()` on composition. So the 2474 # code is typed with no tap first and checked at the backend instead of on the 2475 # screen. 2476 2477 2478 def _submit_mfa_code(c: Ctx, code: str) -> None: 2479 """Type the code and submit it the way the dialog expects. 2480 2481 Not by tapping OK: `Pos.tap_button` puts the keyboard away before every 2482 tap -- it has to, because a button under the IME swallows the tap -- and 2483 on this dialog the Back that does it closes the dialog along with the 2484 keyboard, so OK is gone by the time it would be pressed. The code field 2485 is an `ImeAction.Done` field whose `onDone` is the same submit the button 2486 calls, so Enter takes the same path without touching the keyboard. 2487 """ 2488 c.dev.type_text(code) 2489 time.sleep(1) 2490 c.ep.observe() 2491 c.dev.key("KEYCODE_ENTER") 2492 time.sleep(3) 2493 2494 2495 @scenario("mock", "form") 2496 def login_needs_a_two_factor_code(c: Ctx) -> None: 2497 """A backend that will not hand out a token without a mailed code.""" 2498 c.provision_mock("mfa-two-channels", need_form=True, expect_success=False) 2499 screen = c.dev.wait_for(r"Choose verification method", timeout=45) 2500 c.ep.observe() 2501 c.ep.note(f"challenge chooser: {screen.texts()[:8]}") 2502 c.require(bool(screen.find(r"(?i)email")) and bool(screen.find(r"(?i)sms")), 2503 f"both channels the backend offered are on the chooser " 2504 f"({screen.texts()[:8]})") 2505 c.ep.perform(Action("tap_label", "EMAIL: o...r@example.com")) 2506 screen = c.dev.wait_for(r"Two-factor authentication", timeout=45) 2507 screen, _ = c.ep.observe() 2508 assert c.mock is not None 2509 c.require(c.mock.state.challenges_sent == ["mock-chal-email"], 2510 f"the terminal asked the backend to send the code before asking " 2511 f"for it ({c.mock.state.challenges_sent})") 2512 c.expect(bool(screen.find(r"o\.\.\.r@example\.com")), 2513 "tan-prompt-does-not-say-where", 2514 f"the code dialog does not say which address the code went to: " 2515 f"{screen.texts()[:8]}", 2516 " | ".join(screen.texts())[:400]) 2517 _submit_mfa_code(c, "12345678") 2518 screen = c.app.wait_for_order_entry(timeout=90) 2519 c.ep.observe() 2520 c.require(c.mock.state.challenges_solved == ["mock-chal-email"], 2521 f"the challenge was solved at the backend " 2522 f"({c.mock.state.challenges_solved})") 2523 instance, url = c.app.bound_instance() 2524 c.expect(instance == "mockshop", 2525 "two-factor-login-bound-nothing", 2526 f"a two-factor login left the terminal bound to {instance!r}") 2527 2528 2529 @scenario("mock", "form") 2530 def login_two_factor_wrong_code(c: Ctx) -> None: 2531 """Three wrong codes, then the right one. 2532 2533 The terminal reads exactly two statuses as recoverable -- 409 is "wrong 2534 code, ask again" and 429 is "too many attempts, a new code is on its way" 2535 -- and treats everything else as a dead end. The mock answers 409 twice 2536 and then 429, so one scenario walks both arms of 2537 `MfaUtils.handleChallengeConfirmError` and the resend they lead to. 2538 """ 2539 c.provision_mock("mfa-two-channels", need_form=True, expect_success=False) 2540 c.dev.wait_for(r"Choose verification method", timeout=45) 2541 c.ep.observe() 2542 c.ep.perform(Action("tap_label", "SMS: +49 *** *** 42")) 2543 c.dev.wait_for(r"Two-factor authentication", timeout=45) 2544 c.ep.observe() 2545 assert c.mock is not None 2546 for attempt, code in enumerate(("00000000", "11111111", "22222222"), start=1): 2547 _submit_mfa_code(c, code) 2548 screen, _ = c.ep.observe() 2549 c.ep.note(f"wrong code {attempt} ({code}): {screen.texts()[:8]}") 2550 c.require(bool(screen.find(r"Two-factor authentication")), 2551 f"the terminal asked again after wrong code {attempt} " 2552 f"({screen.texts()[:8]})") 2553 c.require(len(c.mock.state.bad_tans) == 3, 2554 f"the backend saw all three wrong codes ({c.mock.state.bad_tans})") 2555 c.expect(len(c.mock.state.challenges_sent) >= 2, 2556 "rate-limited-code-not-resent", 2557 f"the backend answered 429 -- a new code is on its way -- and the " 2558 f"terminal never asked for one: it requested " 2559 f"{len(c.mock.state.challenges_sent)} code(s)", 2560 str(c.mock.state.challenges_sent)) 2561 _submit_mfa_code(c, "12345678") 2562 c.app.wait_for_order_entry(timeout=90) 2563 c.ep.observe() 2564 c.require(c.mock.state.challenges_solved == ["mock-chal-sms"], 2565 f"the right code got through in the end " 2566 f"({c.mock.state.challenges_solved})") 2567 2568 2569 @scenario("mock", "form") 2570 def login_two_factor_both_channels(c: Ctx) -> None: 2571 """A backend that wants a code from each of two channels. 2572 2573 `combi_and` is the flag, and it takes a different branch of 2574 `handleChallengeResponse`: no chooser at all, both challenges solved in 2575 turn. 2576 """ 2577 c.provision_mock("mfa-both-required", need_form=True, expect_success=False) 2578 screen = c.dev.wait_for(r"Two-factor authentication", timeout=45) 2579 c.ep.observe() 2580 c.expect(not bool(screen.find(r"Choose verification method")), 2581 "chooser-shown-for-a-combined-challenge", 2582 "the backend requires both channels, and the terminal offered a " 2583 "choice between them", 2584 " | ".join(screen.texts())[:400]) 2585 assert c.mock is not None 2586 for round_no in (1, 2): 2587 c.dev.wait_for(r"Two-factor authentication", timeout=45) 2588 _submit_mfa_code(c, "12345678") 2589 c.ep.note(f"after code {round_no}: solved " 2590 f"{c.mock.state.challenges_solved}") 2591 c.app.wait_for_order_entry(timeout=90) 2592 c.ep.observe() 2593 c.require(len(c.mock.state.challenges_solved) == 2, 2594 f"both challenges were solved " 2595 f"({c.mock.state.challenges_solved})") 2596 2597 2598 @scenario("demo") 2599 def login_url_with_instance_path(c: Ctx) -> None: 2600 """A merchant URL pasted whole, scheme and instance path and all. 2601 2602 `ConfigFragment.sanitizeMerchantUrlAndUpdateFields` splits it: the scheme 2603 is taken off, the host and port are kept, and `/instances/<name>` fills the 2604 username field. A host typed bare -- which is what every other scenario 2605 types -- takes none of those branches. 2606 """ 2607 c.app.fresh_start() 2608 screen = c.app.wait_for_config_screen() 2609 if screen.find(r"^Manual config$"): 2610 c.app.tap_button(r"^Manual config$") 2611 time.sleep(1) 2612 screen = c.app._stable_dump() 2613 pasted = f"https://{merchant.DEMO_BASE.split('://')[1]}/instances/{merchant.DEMO_INSTANCE}" 2614 c.ep.note(f"pasting {pasted!r} into the merchant URL field") 2615 c.app.fill_field(r"Merchant portal URL", pasted, screen, verify=False) 2616 # The field is rewritten when it loses focus, so move on before reading it. 2617 c.app.fill_field(r"^Password$", merchant.DEMO_SECRET, c.app._stable_dump()) 2618 screen, _ = c.ep.observe() 2619 host, username = c.app.login_form_values() 2620 # Only an observation, not a judgement: `sanitizeMerchantUrlAndUpdateFields` 2621 # runs when the form is submitted, not as it is typed into, so the fields 2622 # still hold what was pasted. Reading them here and calling the scheme 2623 # "left in" was a false positive -- the login below shows the splitting 2624 # happens, and that is what there is to check. 2625 c.ep.note(f"before Connect the form holds host={host!r} " 2626 f"username={username!r}") 2627 c.require(host is not None, "the merchant URL field can be read back") 2628 c.app.tap_button(r"^Connect$") 2629 c.app.wait_for_order_entry(timeout=120) 2630 c.ep.observe() 2631 bound, url = c.app.bound_instance() 2632 c.expect(bound == merchant.DEMO_INSTANCE, 2633 "pasted-url-bound-the-wrong-instance", 2634 f"a pasted URL bound the terminal to {bound!r} at {url!r}") 2635 c.expect(bool(url) and "/instances/instances/" not in (url or ""), 2636 "instance-path-doubled", 2637 f"a URL that already named the instance was bound as {url!r}") 2638 2639 2640 @scenario("demo") 2641 def login_without_remembering_the_password(c: Ctx) -> None: 2642 """Log in with "Remember password" unticked, then restart. 2643 2644 `ConfigManager.restoreCachedRuntimeConfig` gives up early when the stored 2645 config has no password -- there is nothing to come back to -- and clears 2646 the cache instead. Every other scenario ticks the box, so that arm and the 2647 "ask again" it leads to were never taken. 2648 """ 2649 inst = c.demo() 2650 c.app.fresh_start() 2651 c.app.provision_by_form( 2652 merchant.DEMO_BASE.split("://")[1], merchant.DEMO_INSTANCE, 2653 merchant.DEMO_SECRET, save_password=False) 2654 c.ep.observe() 2655 bound, _ = c.app.bound_instance() 2656 c.require(bound == merchant.DEMO_INSTANCE, 2657 f"the terminal logged in without saving the password ({bound})") 2658 c.app.relaunch() 2659 time.sleep(6) 2660 screen = c.app._stable_dump() 2661 c.ep.observe() 2662 c.ep.note(f"after a restart without a saved password: {screen.texts()[:14]}") 2663 at_login = bool(screen.find(AT_LOGIN)) 2664 c.require(at_login or bool(screen.find(MARK_ORDER)) or 2665 bool(screen.find(MARK_AMOUNT)), 2666 f"the terminal came up somewhere recognisable " 2667 f"({screen.texts()[:12]})") 2668 if at_login: 2669 host, username = c.app.login_form_values() 2670 c.ep.note(f"it asks again, with host={host!r} username={username!r}") 2671 c.expect(bool(host), 2672 "forgotten-password-forgets-everything", 2673 "a terminal that was told not to save the password came back " 2674 "with an empty form, so the cashier retypes the host and the " 2675 "instance as well", 2676 " | ".join(screen.texts())[:400]) 2677 else: 2678 c.ep.note("it came back working, so the session outlived the restart") 2679 c.expect(not bool(screen.find(MARK_FETCHING)), 2680 "stuck-on-spinner-without-a-saved-password", 2681 "restarting without a saved password left the terminal on the " 2682 "configuration spinner", 2683 " | ".join(screen.texts())[:400]) 2684 2685 2686 @scenario("mock", "form") 2687 def login_two_factor_cancelled(c: Ctx) -> None: 2688 """The cashier gives up on the two-factor code. 2689 2690 `ChallengeCancelledException` is its own arm of the login: the terminal has 2691 to stop submitting and leave the form usable, rather than hang on the 2692 spinner or report an error the cashier did not cause. 2693 """ 2694 c.provision_mock("mfa-two-channels", need_form=True, expect_success=False) 2695 screen = c.dev.wait_for(r"Choose verification method", timeout=45) 2696 c.ep.observe() 2697 c.require(bool(screen.find(r"(?i)cancel")), 2698 f"the chooser offers a way out ({screen.texts()[:10]})") 2699 c.ep.perform(Action("tap_label", "Cancel")) 2700 time.sleep(5) 2701 screen, _ = c.ep.observe() 2702 dialog = c.app.read_dialog(screen) 2703 body = (f"{dialog.title} {dialog.message}" if dialog 2704 else " ".join(screen.texts())) 2705 c.ep.note(f"after cancelling the challenge: {screen.texts()[:12]}") 2706 assert c.mock is not None 2707 c.require(not c.mock.state.challenges_solved, 2708 f"nothing was solved ({c.mock.state.challenges_solved})") 2709 c.expect(bool(screen.find(AT_LOGIN)), 2710 "cancelled-challenge-strands-the-form", 2711 f"cancelling the two-factor prompt left the terminal somewhere " 2712 f"other than the login form: {screen.texts()[:12]}", 2713 " | ".join(screen.texts())[:500]) 2714 c.expect(not re.search(r"(?i)error|failed|exception", body), 2715 "cancelled-challenge-reported-as-an-error", 2716 f"giving up on the code was reported as a failure: {body[:200]!r}", 2717 body[:500]) 2718 2719 2720 # ========================================================================= 2721 # the order-details page, against goods a merchant really sold 2722 # ========================================================================= 2723 # 2724 # `OrderDetailsScreen` is 994 lines and most of it only renders when the 2725 # order carries something to render: a product image, a unit, a delivery 2726 # address, a fulfilment link. The mock cannot supply those, because its 2727 # products are never bought and never end up in a contract -- so these 2728 # scenarios buy the awkward products `driver/inventory.py` puts on the demo 2729 # instance, and create orders whose contract terms carry the rest. 2730 2731 2732 @scenario("demo", "pay", "slow") 2733 def order_details_rich_products(c: Ctx) -> None: 2734 """An order of awkward goods, read back off the order-details page.""" 2735 import inventory 2736 inst = c.demo() 2737 wallet = c.funded_customer(inst.currency) 2738 placed = inventory.ensure(inst) 2739 c.ep.note(f"catalogue: {placed}") 2740 c.provision_demo() 2741 c.app.goto("inventory") 2742 c.app.tap_button(r"^POS simulator$") 2743 time.sleep(2) 2744 for name in ("Simulator tile with a picture", "Simulator loose goods"): 2745 c.app.tap_button("^" + re.escape(name[:28])) 2746 time.sleep(1) 2747 c.observe() 2748 c.app.bill() 2749 uri = c.app.copy_displayed_uri() 2750 c.require(bool(uri), "the terminal offered a pay URI for the inventory order") 2751 wallet.pay(uri) 2752 c.app.wait_for_success() 2753 c.app.continue_from_success() 2754 time.sleep(2) 2755 c.app.goto("history") 2756 c.app.refresh_history() 2757 time.sleep(2) 2758 screen = c.app.open_order_details(row=0) 2759 c.observe() 2760 texts = screen.texts() 2761 c.ep.note(f"order details: {texts[:26]}") 2762 # The image is a contract field, decoded by `decodeProductImage`; the page 2763 # offers it as something to open, which is the only handle a dump gives. 2764 c.expect(any(re.search(r"(?i)view image", t) for t in texts), 2765 "order-details-drops-the-product-image", 2766 f"a product sold with a picture shows none on the order-details " 2767 f"page: {texts[:20]}", " | ".join(texts)[:400]) 2768 # "1 kg × ク4.00" -- the unit comes from the catalogue, the quantity from 2769 # the contract, and `quantityLabel` puts them together. 2770 c.expect(any(re.search(r"\bkg\b", t) for t in texts), 2771 "order-details-drops-the-unit", 2772 f"goods sold by the kilogram are listed without their unit: " 2773 f"{texts[:20]}", " | ".join(texts)[:400]) 2774 c.expect(any("2.50" in t for t in texts) and any("4.00" in t for t in texts), 2775 "order-details-drops-a-price", 2776 f"the two products' prices are not both on the page: {texts[:20]}", 2777 " | ".join(texts)[:400]) 2778 2779 2780 @scenario("demo", "pay", "slow") 2781 def order_details_supporting_blocks(c: Ctx) -> None: 2782 """Delivery, pickup and fulfilment, which only a richer contract carries.""" 2783 inst = c.demo() 2784 wallet = c.funded_customer(inst.currency) 2785 extra = { 2786 "delivery_location": {"country": "DE", "town": "Darmstadt", 2787 "street": "Rheinstr. 1"}, 2788 "delivery_date": {"t_s": int(time.time()) + 86400}, 2789 "fulfillment_url": "https://example.com/pickup/possim", 2790 } 2791 order = inst.merchant.create_order( 2792 inst.token.value, f"{inst.currency}:1.50", 2793 "pos-simulator rich contract", extra_order=extra) 2794 order_id = order["order_id"] 2795 c.ep.note(f"created {order_id} with delivery and fulfilment terms") 2796 c.provision_demo() 2797 uri = inst.merchant.pay_uri(inst.token.value, order_id) 2798 c.require(bool(uri), f"the backend offers a pay URI for {order_id}") 2799 wallet.pay(uri) 2800 c.app.goto("history") 2801 c.app.refresh_history() 2802 time.sleep(3) 2803 screen = c.app._stable_dump() 2804 rows = [n for n in screen.labelled() if n.label.strip() == "Order details"] 2805 c.require(bool(rows), f"the history offers an order to open ({screen.texts()[:12]})") 2806 screen = c.app.open_order_details(row=0) 2807 c.observe() 2808 texts = screen.texts() 2809 c.ep.note(f"supporting details: {texts[:26]}") 2810 body = " ".join(texts) 2811 c.expect(re.search(r"(?i)darmstadt|rheinstr", body) is not None, 2812 "order-details-drops-the-delivery-address", 2813 f"the order carries a delivery address and the page shows none: " 2814 f"{texts[:20]}", body[:400]) 2815 c.expect(re.search(r"(?i)example\.com/pickup", body) is not None, 2816 "order-details-drops-the-fulfilment-link", 2817 f"the order carries a fulfilment URL and the page shows none: " 2818 f"{texts[:20]}", body[:400]) 2819 2820 2821 @scenario("demo") 2822 def order_screen_prev_next(c: Ctx) -> None: 2823 """Several orders at once, and the Prev/Next that move between them. 2824 2825 `OrderManager.previousOrder`/`nextOrder` are wired to these two buttons 2826 and to nothing else. (`deleteCurrentOrder` beside them has no caller at 2827 all -- bugs.gnunet.org 11981 -- so there is nothing here to press for it.) 2828 """ 2829 c.provision_demo() 2830 c.app.goto("inventory") 2831 first = c.app.add_products(count=1) 2832 c.require(bool(first), "a product went into the first order") 2833 c.ep.note(f"order #0 holds {first}") 2834 screen = c.app._stable_dump() 2835 c.require(bool(screen.find(r"^Next$")), 2836 f"the order screen offers Next ({screen.texts()[:14]})") 2837 c.app.tap_button(r"^Next$") 2838 time.sleep(2) 2839 screen, _ = c.ep.observe() 2840 c.ep.note(f"after Next: {[t for t in screen.texts() if t.startswith('Order #')]}") 2841 second = c.app.add_products(count=1) 2842 c.ep.note(f"the second order holds {second}") 2843 c.app.tap_button(r"^Prev$") 2844 time.sleep(2) 2845 screen, _ = c.ep.observe() 2846 texts = screen.texts() 2847 c.ep.note(f"back on the first order: {texts[:18]}") 2848 c.expect(any(first[0][:18] in t for t in texts), 2849 "prev-loses-the-first-order", 2850 f"stepping to the next order and back lost what the first one " 2851 f"held ({first}): {texts[:18]}", " | ".join(texts)[:400]) 2852 2853 2854 @scenario("demo", "pay", "portrait", "slow") 2855 def portrait_refund_uri(c: Ctx) -> None: 2856 """The refund QR screen with the device upright.""" 2857 inst = c.demo() 2858 wallet = c.funded_customer(inst.currency) 2859 c.provision_demo() 2860 c.app.goto("amount") 2861 c.app.enter_amount("1.00") 2862 c.app.charge() 2863 uri = c.app.copy_displayed_uri() 2864 c.require(bool(uri), "the terminal offered a pay URI") 2865 wallet.pay(uri) 2866 c.app.wait_for_success() 2867 c.app.continue_from_success() 2868 time.sleep(2) 2869 c.app.goto("history") 2870 c.app.refresh_history() 2871 _portrait(c) 2872 c.app.start_refund() 2873 c.app.submit_refund("1.00") 2874 screen, _ = c.ep.observe() 2875 c.require(c.dev.is_portrait(), 2876 "the device is still in portrait where the judging happens") 2877 texts = screen.texts() 2878 c.ep.note(f"portrait refund screen: {texts[:16]}") 2879 c.expect(bool(screen.find(MARK_REFUND_URI)), 2880 "portrait-refund-screen-missing", 2881 f"the refund code screen did not appear in portrait: " 2882 f"{texts[:16]}", " | ".join(texts)[:400]) 2883 refund_uri = c.app.copy_displayed_uri(scheme="taler") 2884 c.ep.note(f"portrait refund uri: {refund_uri}") 2885 c.expect(bool(refund_uri), 2886 "portrait-refund-offers-no-code", 2887 f"the portrait refund screen offers nothing for the customer to " 2888 f"scan: {texts[:16]}", " | ".join(texts)[:400]) 2889 2890 2891 @scenario("demo", "slow") 2892 def checkout_back_to_payment_options(c: Ctx) -> None: 2893 """Going back from the Taler step of a checkout, which un-creates the order. 2894 2895 `CheckoutManager.revertTalerStep` is reached from exactly one control -- 2896 "Back to payment options" on the payment screen of a checkout -- and it 2897 has to take the backend order back with it, or the cashier is left with a 2898 sale that exists twice. 2899 """ 2900 inst = c.demo() 2901 _enable_cash(c) 2902 c.app.goto("amount") 2903 c.app.enter_amount("4.00") 2904 c.app.charge_to_checkout() 2905 c.app.record_cash("1.00") 2906 c.app.checkout_finish_with_taler() 2907 screen, _ = c.ep.observe() 2908 order_id = c.app.displayed_order_id(screen) 2909 c.ep.note(f"the checkout created {order_id}") 2910 c.require(bool(screen.find(r"^Back to payment options$")), 2911 f"the payment screen offers a way back ({screen.texts()[:14]})") 2912 c.app.tap_button(r"^Back to payment options$") 2913 time.sleep(4) 2914 screen, _ = c.ep.observe() 2915 texts = screen.texts() 2916 c.ep.note(f"after going back: {texts[:16]}") 2917 c.expect(bool(screen.find(MARK_CHECKOUT)), 2918 "back-from-taler-leaves-the-checkout", 2919 f"going back from the Taler step did not return to the " 2920 f"checkout: {texts[:16]}", " | ".join(texts)[:400]) 2921 amounts = c.app.checkout_amounts(screen) 2922 c.ep.note(f"the checkout still holds {amounts}") 2923 c.expect(_minor(amounts.get("paid")) == 100, 2924 "back-from-taler-loses-the-cash", 2925 f"one unit of cash was taken before the Taler step and going " 2926 f"back left {amounts.get('paid')!r} recorded", json.dumps(amounts)) 2927 if order_id: 2928 status = inst.merchant.order_status(inst.token.value, order_id) 2929 c.ep.note(f"the backend now calls {order_id} " 2930 f"{status.get('order_status')!r}") 2931 c.expect(status.get("order_status") != "paid", 2932 "back-from-taler-left-a-paid-order", 2933 f"going back from the Taler step left {order_id} paid at the " 2934 f"backend", json.dumps({"order_status": status.get("order_status")})) 2935 2936 2937 # ========================================================================= 2938 # portrait, and turning the device while something is in flight 2939 # ========================================================================= 2940 # 2941 # The terminal declared `screenOrientation="landscape"` through round three 2942 # and declares `fullUser` on master, so portrait stopped being dead code and 2943 # nobody noticed: `PortraitOrderScreen`, `PortraitPaymentScreen` and 2944 # `PortraitRefundUriScreen` had never been composed when this section was 2945 # written, and neither had any of the `maxWidth > maxHeight` branches beside 2946 # them. 2947 # 2948 # Rotating *during* a flow is the more interesting half. A configuration 2949 # change destroys and recreates every composition, so anything the terminal 2950 # holds in a `remember` rather than a `rememberSaveable` or a ViewModel is 2951 # lost -- and for a landscape-locked app that could never happen, so nothing 2952 # in it has ever been checked against it. 2953 2954 2955 def _portrait(c: Ctx) -> None: 2956 """Turn the device, and say so in the episode. 2957 2958 `fresh_start` puts every scenario back to landscape, so a scenario that 2959 turns the device cannot leak that state into the next one even if it 2960 fails here. 2961 """ 2962 size = c.dev.rotate(portrait=True) 2963 c.ep.note(f"turned to portrait, window now {size[0]}x{size[1]}") 2964 c.require(c.dev.is_portrait(), "the device is in portrait") 2965 2966 2967 @scenario("demo", "portrait") 2968 def portrait_order_screens(c: Ctx) -> None: 2969 """The order screens in portrait, which no round before this one composed.""" 2970 # Provision *first*: `fresh_start` puts the device back to the orientation 2971 # the run asked for, so turning before it is provisioned turns it straight 2972 # back again -- and the scenario then tested landscape under a portrait 2973 # name, which is exactly what that reset exists to prevent. 2974 c.provision_demo() 2975 _portrait(c) 2976 screen = c.app.goto("amount") 2977 c.observe() 2978 texts = " ".join(screen.texts()) 2979 c.ep.note(f"portrait keypad: {screen.texts()[:14]}") 2980 c.require(bool(screen.find(r"^1$")) and bool(screen.find(r"^Clear$")), 2981 f"the keypad is on screen ({screen.texts()[:12]})") 2982 c.expect(c.app.control_reachable(r"Create order \(charge amount\)|^Charge$", 2983 screen), 2984 "portrait-keypad-hides-its-action", 2985 f"the portrait keypad does not show a way to charge: " 2986 f"{screen.texts()[:16]}", texts[:400]) 2987 c.app.enter_amount("3.00") 2988 shown = c.app.displayed_amount() 2989 c.ep.note(f"portrait keypad shows {shown!r} after typing 3.00") 2990 c.expect(_minor(shown) == 300, 2991 "portrait-keypad-miscounts", 2992 f"typing 3.00 on the portrait keypad gave {shown!r}", str(shown)) 2993 c.require(c.dev.is_portrait(), 2994 "the device is still in portrait where the judging happens") 2995 c.app.goto("inventory") 2996 # Waited for, not dumped for: the grid is a lazy list of a hundred-odd 2997 # products and the first dump after navigating catches sixteen of them. 2998 # Judging "there is no Bill button" from that dump reported a button that 2999 # was simply not composed yet. 3000 try: 3001 screen = c.dev.wait_for(BILL_BUTTON, timeout=30) 3002 billable = True 3003 except TimeoutError: 3004 screen = c.app._stable_dump() 3005 billable = False 3006 c.observe() 3007 c.ep.note(f"portrait grid: {len(screen.texts())} labels, " 3008 f"bill button {'present' if billable else 'absent'}") 3009 c.expect(billable, 3010 "portrait-grid-hides-its-action", 3011 f"the portrait order grid offers no way to bill: " 3012 f"{screen.texts()[:16]}", " | ".join(screen.texts())[:400]) 3013 3014 3015 @scenario("demo", "pay", "portrait", "slow") 3016 def portrait_payment_screen(c: Ctx) -> None: 3017 """A payment taken end to end with the device upright.""" 3018 inst = c.demo() 3019 wallet = c.funded_customer(inst.currency) 3020 c.provision_demo() 3021 _portrait(c) 3022 c.app.goto("amount") 3023 c.app.enter_amount("1.00") 3024 c.app.charge() 3025 screen, _ = c.ep.observe() 3026 c.ep.note(f"portrait payment screen: {screen.texts()[:16]}") 3027 c.require(c.dev.is_portrait(), 3028 "the device is still in portrait where the judging happens") 3029 uri = c.app.copy_displayed_uri() 3030 c.require(bool(uri), f"the portrait payment screen offers a pay URI " 3031 f"({screen.texts()[:14]})") 3032 c.expect(bool(re.search(r"(?i)scan", " ".join(screen.texts()))), 3033 "portrait-payment-screen-says-nothing", 3034 f"the portrait payment screen does not tell the customer to " 3035 f"scan anything: {screen.texts()[:16]}", 3036 " | ".join(screen.texts())[:400]) 3037 wallet.pay(uri) 3038 screen = c.app.wait_for_success() 3039 c.observe() 3040 c.expect(bool(screen.find(MARK_SUCCESS)), 3041 "portrait-payment-not-acknowledged", 3042 f"the wallet paid and the portrait terminal did not say so: " 3043 f"{screen.texts()[:12]}", " | ".join(screen.texts())[:400]) 3044 3045 3046 @scenario("demo", "slow") 3047 def rotate_mid_payment(c: Ctx) -> None: 3048 """Turn the device while a customer is paying. 3049 3050 The pay URI, the order id and the polling all have to survive a 3051 configuration change. Nothing in this app has ever met one. 3052 """ 3053 c.provision_demo() 3054 c.app.goto("amount") 3055 c.app.enter_amount("2.00") 3056 c.app.charge() 3057 before_uri = c.app.copy_displayed_uri() 3058 screen, _ = c.ep.observe() 3059 before_id = c.app.displayed_order_id(screen) 3060 c.require(bool(before_uri), "the terminal offered a pay URI before turning") 3061 c.ep.note(f"before turning: order {before_id}, uri {before_uri}") 3062 c.dev.rotate(portrait=True) 3063 time.sleep(3) 3064 screen, _ = c.ep.observe() 3065 texts = " ".join(screen.texts()) 3066 c.ep.note(f"after turning: {screen.texts()[:16]}") 3067 c.expect(not re.search(r"(?i)has stopped|keeps stopping", texts), 3068 "rotation-kills-the-payment-screen", 3069 f"turning the device during a payment left: {screen.texts()[:12]}", 3070 texts[:400]) 3071 c.expect(bool(screen.find(MARK_PAYMENT)), 3072 "rotation-leaves-the-payment-screen", 3073 f"turning the device during a payment navigated away from it: " 3074 f"{screen.texts()[:14]}", texts[:400]) 3075 after_id = c.app.displayed_order_id(screen) 3076 c.ep.note(f"order id after turning: {after_id}") 3077 if before_id and after_id: 3078 c.expect(after_id == before_id, 3079 "rotation-changes-the-order", 3080 f"the payment screen was showing order {before_id} and after " 3081 f"a turn it shows {after_id}", f"{before_id} -> {after_id}") 3082 after_uri = c.app.copy_displayed_uri() 3083 c.ep.note(f"uri after turning: {after_uri}") 3084 c.expect(bool(after_uri), 3085 "rotation-loses-the-pay-uri", 3086 "after turning the device the payment screen offers no pay URI, " 3087 "so the customer has nothing to scan", 3088 texts[:400]) 3089 if before_uri and after_uri: 3090 c.expect(after_uri == before_uri, 3091 "rotation-mints-a-second-order", 3092 f"the pay URI changed when the device was turned, which means " 3093 f"a different order: {before_uri} -> {after_uri}", 3094 f"{before_uri}\n{after_uri}") 3095 c.app.cancel_payment() 3096 3097 3098 @scenario("demo", "slow") 3099 def rotate_mid_checkout(c: Ctx) -> None: 3100 """Turn the device with cash already in the till for this sale.""" 3101 _enable_cash(c) 3102 c.app.goto("amount") 3103 c.app.enter_amount("5.00") 3104 c.app.charge_to_checkout() 3105 c.app.record_cash("2.00") 3106 before = c.app.checkout_amounts() 3107 c.ep.note(f"before turning: {before}") 3108 c.require(_minor(before.get("paid")) == 200, 3109 f"two is recorded before the turn ({before})") 3110 c.dev.rotate(portrait=True) 3111 time.sleep(3) 3112 screen, _ = c.ep.observe() 3113 texts = " ".join(screen.texts()) 3114 c.ep.note(f"after turning: {screen.texts()[:18]}") 3115 c.expect(not re.search(r"(?i)has stopped|keeps stopping", texts), 3116 "rotation-kills-the-checkout", 3117 f"turning the device during a checkout left: {screen.texts()[:12]}", 3118 texts[:400]) 3119 after = c.app.checkout_amounts(screen) 3120 c.ep.note(f"after turning: {after}") 3121 c.expect(_minor(after.get("paid")) == 200, 3122 "rotation-loses-the-cash", 3123 f"two units of cash were in this sale and after a turn the " 3124 f"checkout says {after.get('paid')!r} is paid", json.dumps(after)) 3125 c.expect(_minor(after.get("to pay")) == 300, 3126 "rotation-changes-what-is-owed", 3127 f"three was still to pay and after a turn the checkout says " 3128 f"{after.get('to pay')!r}", json.dumps(after)) 3129 3130 3131 # ========================================================================= 3132 # mixed payments: the checkout that stands between an order and the QR code 3133 # ========================================================================= 3134 # 3135 # Turning on a second payment option changes what Charge does. Instead of 3136 # going straight to the Taler payment screen the terminal opens a checkout: 3137 # cash and card are collected first, each recorded as it is taken, and Taler 3138 # is left to pay whatever is still open. None of that code runs while Taler 3139 # is the only option, which is the terminal's own default -- so every scenario 3140 # here turns one on first, and the ones that do not are testing the gate. 3141 # 3142 # It needs a backend that speaks protocol 42 or newer (`MIXED_PAYMENTS_PROTOCOL` 3143 # in `CheckoutManager`); `backend.demo.taler.net` reports 42:0:30, so the demo 3144 # instance is enough and the mock is only needed for the refusal. 3145 3146 3147 def _enable_cash(c: Ctx) -> None: 3148 """Provision, then turn Cash on, which is what opens the checkout at all.""" 3149 c.provision_demo() 3150 rows = c.app.set_payment_option("Cash", True) 3151 c.ep.note(f"payment options: {rows}") 3152 c.require(rows.get("Cash") is True, "Cash is turned on") 3153 3154 3155 @scenario("demo") 3156 def checkout_appears_once_cash_is_on(c: Ctx) -> None: 3157 """Charge opens the checkout rather than the QR code, and says what is owed.""" 3158 _enable_cash(c) 3159 c.app.goto("amount") 3160 c.app.enter_amount("7.00") 3161 screen = c.app.charge_to_checkout() 3162 c.observe() 3163 amounts = c.app.checkout_amounts(screen) 3164 c.ep.note(f"checkout shows {amounts}") 3165 c.require(bool(amounts), f"the checkout names an amount ({screen.texts()[:12]})") 3166 c.expect(_minor(amounts.get("total")) == 700, 3167 "checkout-total-is-not-the-order", 3168 f"the order was 7.00 and the checkout calls it " 3169 f"{amounts.get('total')!r}", json.dumps(amounts)) 3170 c.expect(_minor(amounts.get("to pay")) == 700, 3171 "checkout-open-amount-wrong", 3172 f"nothing has been paid yet and the checkout says " 3173 f"{amounts.get('to pay')!r} is still to pay", json.dumps(amounts)) 3174 c.expect(bool(screen.find(r"^Cash$")) and 3175 bool(screen.find(r"Charge with Taler")), 3176 "checkout-offers-no-methods", 3177 f"the checkout offers neither cash nor Taler: {screen.texts()[:14]}", 3178 " | ".join(screen.texts())[:400]) 3179 3180 3181 @scenario("demo") 3182 def checkout_cash_change_is_right(c: Ctx) -> None: 3183 """Ten handed over for a seven-unit order: three back, seven recorded.""" 3184 _enable_cash(c) 3185 c.app.goto("amount") 3186 c.app.enter_amount("7.00") 3187 c.app.charge_to_checkout() 3188 dialog = c.app.record_cash("10.00") 3189 c.ep.note(f"after recording ten: {dialog}") 3190 c.require(dialog is not None, 3191 "the terminal said something about the change") 3192 body = str(dialog) 3193 c.expect("3.00" in body.replace(",", "."), 3194 "cash-change-miscounted", 3195 f"ten given for a seven-unit order should hand three back; the " 3196 f"terminal said {body!r}", body[:400]) 3197 screen, _ = c.ep.observe() 3198 amounts = c.app.checkout_amounts(screen) 3199 c.ep.note(f"checkout after the cash: {amounts}") 3200 c.expect(_minor(amounts.get("paid")) == 700, 3201 "cash-recorded-as-the-tendered-amount", 3202 f"seven was owed and ten was handed over; the checkout records " 3203 f"{amounts.get('paid')!r} as paid", json.dumps(amounts)) 3204 c.expect(_minor(amounts.get("to pay")) == 0, 3205 "cash-left-the-order-open", 3206 f"the order was covered in cash and the checkout still wants " 3207 f"{amounts.get('to pay')!r}", json.dumps(amounts)) 3208 c.expect(any("10.00" in t and "3.00" in t for t in screen.texts()), 3209 "cash-line-hides-the-tender", 3210 "the payment line does not say what was handed over and what " 3211 f"came back: {screen.texts()[:16]}", 3212 " | ".join(screen.texts())[:400]) 3213 3214 3215 @scenario("demo", "pay", "slow") 3216 def checkout_cash_then_taler_pays_the_rest(c: Ctx) -> None: 3217 """Half in cash, half from a wallet -- the whole point of the feature.""" 3218 inst = c.demo() 3219 wallet = c.funded_customer(inst.currency) 3220 _enable_cash(c) 3221 c.app.goto("amount") 3222 c.app.enter_amount("6.00") 3223 c.app.charge_to_checkout() 3224 c.app.record_cash("2.00") 3225 screen, _ = c.ep.observe() 3226 amounts = c.app.checkout_amounts(screen) 3227 c.ep.note(f"after two in cash: {amounts}") 3228 c.require(_minor(amounts.get("to pay")) == 400, 3229 f"four is left for the wallet ({amounts})") 3230 c.app.checkout_finish_with_taler() 3231 uri = c.app.copy_displayed_uri() 3232 c.require(bool(uri), "the terminal offered a pay URI for the rest") 3233 c.ep.note(f"pay uri: {uri}") 3234 order_id = c.app.displayed_order_id() 3235 c.ep.note(f"order id on screen: {order_id}") 3236 wallet.pay(uri) 3237 screen = c.app.wait_for_success() 3238 c.observe() 3239 c.expect(bool(screen.find(MARK_SUCCESS)), 3240 "mixed-payment-not-acknowledged", 3241 f"the wallet paid the open four and the terminal did not say so: " 3242 f"{screen.texts()[:12]}", " | ".join(screen.texts())[:400]) 3243 if order_id: 3244 status = inst.merchant.order_status(inst.token.value, order_id) 3245 c.ep.note(f"backend says {status.get('order_status')} " 3246 f"total {status.get('total_amount')}") 3247 c.expect(status.get("order_status") == "paid", 3248 "mixed-payment-left-the-order-unpaid", 3249 f"the terminal reported a completed payment and the backend " 3250 f"still calls {order_id} {status.get('order_status')!r}", 3251 json.dumps({k: status.get(k) for k in 3252 ("order_status", "total_amount")})) 3253 charged = _order_amount(status) 3254 c.ep.note(f"the backend charged {charged!r} for {order_id}") 3255 c.expect(_minor_json(charged) == 400, 3256 "taler-charged-the-whole-order", 3257 f"two was taken in cash, so the wallet should have been asked " 3258 f"for four; the backend order is for {charged!r}", 3259 json.dumps({"amount": charged})) 3260 3261 3262 @scenario("demo") 3263 def checkout_cash_covers_it_all(c: Ctx) -> None: 3264 """A sale settled entirely in cash still has to reach the backend.""" 3265 inst = c.demo() 3266 _enable_cash(c) 3267 c.app.goto("amount") 3268 c.app.enter_amount("3.00") 3269 c.app.charge_to_checkout() 3270 c.app.record_cash("3.00") 3271 screen, _ = c.ep.observe() 3272 c.require(_minor(c.app.checkout_amounts(screen).get("to pay")) == 0, 3273 "the cash covered the order") 3274 c.app.checkout_tile(r"^Complete payment$") 3275 screen = c.dev.wait_for(r"Collect receipt|^Payment received$", timeout=90) 3276 c.observe() 3277 order_id = c.app.displayed_order_id(screen) 3278 c.ep.note(f"receipt screen for {order_id}: {screen.texts()[:14]}") 3279 c.require(bool(order_id), "the receipt screen names the order") 3280 c.app.tap_button(r"^Collect receipt on this device$") 3281 screen = c.dev.wait_for(MARK_SUCCESS, timeout=90) 3282 c.observe() 3283 status = inst.merchant.order_status(inst.token.value, order_id) 3284 c.ep.note(f"backend: {status.get('order_status')} / {status.get('total_amount')}") 3285 c.expect(status.get("order_status") == "paid", 3286 "cash-sale-not-recorded-at-the-backend", 3287 f"the whole order was paid in cash and collected on the device, " 3288 f"and the backend still calls {order_id} " 3289 f"{status.get('order_status')!r}", 3290 json.dumps({"order_status": status.get("order_status")})) 3291 3292 3293 @scenario("demo") 3294 def checkout_cash_left_behind_when_abandoned(c: Ctx) -> None: 3295 """Cash taken, then the cashier backs out -- the money must not vanish.""" 3296 _enable_cash(c) 3297 c.app.goto("amount") 3298 c.app.enter_amount("5.00") 3299 c.app.charge_to_checkout() 3300 c.app.record_cash("2.00") 3301 c.observe() 3302 screen = c.app.checkout_cancel(confirm=True) 3303 c.ep.note(f"after cancelling with money taken: {screen.texts()[:16]}") 3304 c.observe() 3305 body = " ".join(screen.texts()) 3306 c.expect(not re.search(r"(?i)exception|null|error code", body), 3307 "abandoned-checkout-shows-an-internal-error", 3308 f"cancelling a checkout that holds cash showed: {body[:200]!r}", 3309 body[:400]) 3310 # The terminal keeps abandoned checkouts so the cash can be reconciled, 3311 # and the place it keeps them is the history list -- `mergeHistoryEntries` 3312 # puts every checkout that is not Completed above the backend's own 3313 # orders. If the two units are not there, money a cashier took is gone 3314 # from the only screen that could account for it. 3315 screen = c.app.goto("history") 3316 time.sleep(4) 3317 screen = c.app._stable_dump() 3318 texts = screen.texts() 3319 c.ep.note(f"history after abandoning: {texts[:16]}") 3320 paid_line = [t for t in texts if "Paid:" in t] 3321 c.expect(any(_minor(t.split("Paid:")[1]) == 200 for t in paid_line), 3322 "abandoned-cash-is-not-in-the-history", 3323 f"two units were taken in cash and the checkout abandoned; the " 3324 f"history does not account for them: {texts[:16]}", 3325 " | ".join(texts)[:400]) 3326 c.expect(bool(screen.find(r"^Mark as settled$|^Continue$")), 3327 "abandoned-checkout-cannot-be-closed", 3328 f"the abandoned checkout offers no way to settle or resume it: " 3329 f"{texts[:16]}", " | ".join(texts)[:400]) 3330 3331 3332 @scenario("demo") 3333 def checkout_cash_cannot_exceed_nothing(c: Ctx) -> None: 3334 """The keypad's fraction shortcuts, and a zero that must stay unsubmittable.""" 3335 _enable_cash(c) 3336 c.app.goto("amount") 3337 c.app.enter_amount("7.00") 3338 c.app.charge_to_checkout() 3339 c.app.checkout_tile(r"^Cash$") 3340 screen = c.dev.wait_for(MARK_CHECKOUT_PAD, timeout=30) 3341 c.observe() 3342 shortcuts = {t for t in screen.texts() if re.match(r"^1/[234]$", t)} 3343 c.ep.note(f"shortcuts offered: {sorted(shortcuts)}") 3344 c.require(bool(shortcuts), f"the keypad offers fractions ({screen.texts()[:16]})") 3345 submit = [t for t in screen.texts() if t.startswith("Record ")] 3346 c.ep.note(f"submit label at zero: {submit}") 3347 c.expect(bool(submit) and _minor(submit[0]) == 0, 3348 "cash-keypad-starts-non-zero", 3349 f"the cash keypad opened with {submit!r} rather than nothing typed", 3350 " | ".join(screen.texts())[:400]) 3351 node = screen.find(r"^Record .* cash$") 3352 target = screen.tap_target(node) if node else None 3353 c.expect(target is not None and not target.enabled, 3354 "cash-records-nothing", 3355 "the cash keypad lets a payment of zero be recorded", 3356 f"submit node: {target}") 3357 # A half of seven is 3.50 and a third is 2.33 -- both exact enough to 3358 # check, and both the sort of arithmetic that goes wrong quietly. 3359 half = next((t for t in screen.texts() 3360 if t.startswith("Half of remaining balance")), "") 3361 c.ep.note(f"half says: {half!r}") 3362 c.expect(_minor(half) == 350, 3363 "cash-half-shortcut-wrong", 3364 f"half of seven should be 3.50; the button says {half!r}", 3365 half) 3366 3367 3368 @scenario("demo") 3369 def checkout_is_refused_by_an_old_backend(c: Ctx) -> None: 3370 """A backend below protocol 42 has to say so rather than offer the feature.""" 3371 c.provision_mock("healthy") 3372 screen = c.app.goto_payment_options() 3373 c.observe() 3374 body = " ".join(screen.texts()) 3375 version = c.app.about_rows().get("Merchant portal URL", "") 3376 c.ep.note(f"mock backend version in About: {version!r}") 3377 c.ep.note(f"payment options screen: {screen.texts()[:16]}") 3378 mentions = bool(re.search(r"(?i)needs merchant backend protocol|several parts", 3379 body)) 3380 rows = c.app.payment_option_rows(screen) 3381 c.ep.note(f"options: {rows}; warning shown: {mentions}") 3382 c.require("Cash" in rows, f"the options screen listed Cash ({rows})") 3383 c.expect(mentions, 3384 "old-backend-not-warned-about", 3385 f"the mock backend is below protocol 42 and the payment-options " 3386 f"screen says nothing about it: {screen.texts()[:16]}", 3387 body[:400]) 3388 3389 3390 @scenario("demo") 3391 def checkout_survives_process_death(c: Ctx) -> None: 3392 """Cash already taken has to be there after the process is killed.""" 3393 _enable_cash(c) 3394 c.app.goto("amount") 3395 c.app.enter_amount("9.00") 3396 c.app.charge_to_checkout() 3397 c.app.record_cash("4.00") 3398 before = c.app.checkout_amounts() 3399 c.ep.note(f"before the kill: {before}") 3400 c.require(_minor(before.get("paid")) == 400, f"four is recorded ({before})") 3401 c.app.process_death() 3402 time.sleep(4) 3403 screen, _ = c.ep.observe() 3404 texts = " ".join(screen.texts()) 3405 c.ep.note(f"after the kill: {screen.texts()[:16]}") 3406 c.expect(not re.search(r"(?i)has stopped|keeps stopping", texts), 3407 "checkout-crashes-on-restart", 3408 f"the terminal did not survive a restart mid-checkout: " 3409 f"{screen.texts()[:12]}", texts[:400]) 3410 found = bool(re.search(r"(?i)unfinished|continue", texts)) or \ 3411 _minor(c.app.checkout_amounts(screen).get("paid")) == 400 3412 c.expect(found, 3413 "cash-lost-on-restart", 3414 f"four units of cash were taken and after a restart the terminal " 3415 f"shows no sign of them: {screen.texts()[:16]}", 3416 texts[:400]) 3417 3418 3419 @scenario("demo") 3420 def payment_options_summary_counts(c: Ctx) -> None: 3421 """Turning an option on and off again has to be visible and reversible.""" 3422 c.provision_demo() 3423 rows = c.app.set_payment_option("Cash", True) 3424 c.require(rows.get("Cash") is True, "Cash went on") 3425 c.observe() 3426 screen = c.app.goto("settings") 3427 counted = [t for t in screen.texts() if re.search(r"turned on", t)] 3428 c.ep.note(f"settings summary with cash on: {counted}") 3429 c.expect(any("2" in t for t in counted), 3430 "payment-options-count-wrong", 3431 f"Taler and Cash are on and Settings says {counted!r}", 3432 " | ".join(screen.texts())[:400]) 3433 rows = c.app.set_payment_option("Cash", False) 3434 c.expect(rows.get("Cash") is False, 3435 "payment-option-will-not-turn-off", 3436 f"Cash could not be turned off again: {rows}", json.dumps(rows)) 3437 c.app.goto("amount") 3438 c.app.enter_amount("1.00") 3439 screen = c.app.charge() 3440 c.observe() 3441 c.expect(bool(screen.find(MARK_PAYMENT)), 3442 "checkout-shown-with-no-external-options", 3443 f"with Cash off again, Charge should go straight to the payment " 3444 f"screen and showed {screen.texts()[:12]}", 3445 " | ".join(screen.texts())[:400]) 3446 c.app.cancel_payment() 3447 3448 3449 @scenario("demo") 3450 def payment_option_detail_without_a_key(c: Ctx) -> None: 3451 """SumUp with no affiliate key must explain itself, not fail obscurely.""" 3452 c.provision_demo() 3453 screen = c.app.goto_payment_options() 3454 c.observe() 3455 rows = c.app.payment_option_rows(screen) 3456 c.require("SumUp" in rows, f"SumUp is listed ({rows})") 3457 c.app.tap_button(r"^Open SumUp settings$") 3458 time.sleep(3) 3459 screen, _ = c.ep.observe() 3460 body = " ".join(screen.texts()) 3461 c.ep.note(f"SumUp detail: {screen.texts()[:18]}") 3462 c.expect(not re.search(r"(?i)exception|stacktrace|null\b|retrofit|okhttp", 3463 body), 3464 "payment-option-detail-leaks-an-internal-error", 3465 f"the SumUp settings page showed an internal error: {body[:200]!r}", 3466 body[:400]) 3467 c.expect(bool(screen.texts()), 3468 "payment-option-detail-is-blank", 3469 "the SumUp settings page has nothing on it at all", 3470 body[:400]) 3471 3472 3473 @scenario("demo", "slow") 3474 def taler_display_pairing_wizard(c: Ctx) -> None: 3475 """The customer-display pairing wizard, as far as a device without one goes. 3476 3477 `TalerDevicesFragment` and `TalerBluetoothDevice` are a thousand lines 3478 apiece and nothing has ever opened them. An emulator has no Taler display 3479 to pair with, which is the point: what is being judged is that the wizard 3480 asks for what it needs, says what it is doing, and ends in a sentence 3481 rather than in a spinner or an empty list, when the scan finds nothing. 3482 """ 3483 c.provision_demo() 3484 screen = c.app.goto_payment_options() 3485 c.observe() 3486 c.require(bool(screen.find(r"^Open GNU Taler settings$")), 3487 f"the Taler option has a settings page ({screen.texts()[:12]})") 3488 c.app.tap_button(r"^Open GNU Taler settings$") 3489 screen = c.dev.wait_for(r"Manage displays|Add device", timeout=45) 3490 c.observe() 3491 c.ep.note(f"devices screen: {screen.texts()[:14]}") 3492 c.expect(bool(screen.find(r"^Add device$")), 3493 "devices-screen-offers-nothing", 3494 f"the displays page has no way to add one: {screen.texts()[:14]}", 3495 " | ".join(screen.texts())[:400]) 3496 c.app.tap_button(r"^Add device$") 3497 screen = c.dev.wait_for(r"Bluetooth display", timeout=30) 3498 c.observe() 3499 node = screen.find(r"^Bluetooth display$") 3500 c.require(node is not None, f"the chooser offers Bluetooth ({screen.texts()})") 3501 c.dev.tap_node(node, screen) 3502 time.sleep(3) 3503 screen, _ = c.ep.observe() 3504 # The permission prompt is the system's, not the app's. 3505 node = screen.find(r"^Allow device access$") 3506 if node is not None: 3507 c.ep.note("the app asked for nearby-device access before scanning") 3508 # Tapped at the node: this is a Compose AlertDialog, and tap_button 3509 # may press Back on the way, which dismisses it instead of answering. 3510 c.dev.tap_node(node, screen) 3511 time.sleep(3) 3512 grant = c.app._stable_dump() 3513 allow = grant.find(r"^Allow$") 3514 if allow is not None: 3515 c.dev.tap_node(allow, grant) 3516 time.sleep(4) 3517 steps = [] 3518 for _ in range(4): 3519 screen = c.app._stable_dump() 3520 steps.append(screen.texts()[:4]) 3521 node = screen.find(r"^Next$|^Find Taler display$") 3522 if node is None: 3523 break 3524 c.dev.tap_node(node, screen) 3525 time.sleep(4) 3526 c.ep.note(f"wizard steps: {steps}") 3527 c.require(len(steps) > 1, f"the wizard had more than one step ({steps})") 3528 # Nothing to find, so what matters is that it stops looking and says so. 3529 deadline = time.monotonic() + 60 3530 screen = c.app._stable_dump() 3531 while time.monotonic() < deadline and screen.find(r"Looking for"): 3532 time.sleep(4) 3533 screen = c.app._stable_dump() 3534 c.observe() 3535 texts = screen.texts() 3536 c.ep.note(f"after the scan: {texts[:12]}") 3537 c.expect(not any("Looking for" in t for t in texts), 3538 "display-scan-never-stops", 3539 f"the scan for a customer display is still running after a " 3540 f"minute with nothing to find: {texts[:12]}", 3541 " | ".join(texts)[:400]) 3542 c.expect(bool(screen.find(r"(?i)search again|no display|not found|cancel")), 3543 "display-scan-ends-with-nothing-to-do", 3544 f"the scan found no display and offers no way on or out: " 3545 f"{texts[:12]}", " | ".join(texts)[:400]) 3546 body = " ".join(texts) 3547 c.expect(not re.search(r"(?i)exception|null\b|securityexception", body), 3548 "display-pairing-leaks-an-internal-error", 3549 f"the pairing wizard showed an internal error: {body[:200]!r}", 3550 body[:400]) 3551 cancel = screen.find(r"^Cancel$") 3552 if cancel is not None: 3553 c.dev.tap_node(cancel, screen) 3554 time.sleep(2.5) 3555 screen, _ = c.ep.observe() 3556 c.expect(bool(screen.find(r"Manage displays|Add device|Customers pay")), 3557 "display-wizard-cannot-be-left", 3558 f"cancelling the pairing wizard did not return to the devices " 3559 f"page: {screen.texts()[:12]}", " | ".join(screen.texts())[:400]) 3560 3561 3562 @scenario("demo", "phone") 3563 def login_form_fits_a_phone(c: Ctx) -> None: 3564 """The login form has to stay usable once the keyboard is up.""" 3565 c.app.fresh_start() 3566 screen = c.app.wait_for_config_screen() 3567 c.observe() 3568 fields = screen.editable() 3569 c.require(len(fields) >= 3, 3570 f"the form starts with its three fields ({screen.texts()[:12]})") 3571 c.dev.tap_node(fields[0], screen) 3572 time.sleep(2.5) 3573 screen, _ = c.ep.observe() 3574 c.require(c.dev.keyboard_shown(), "tapping a field raised the keyboard") 3575 after = screen.editable() 3576 scrollable = [n for n in screen.nodes if n.scrollable] 3577 c.ep.note(f"with the keyboard up: {len(after)} field(s), " 3578 f"{len(scrollable)} scrollable, texts {screen.texts()[:12]}") 3579 c.expect(bool(after), 3580 "login-form-collapses-under-the-keyboard", 3581 f"tapping the first field left the form with no fields at all; " 3582 f"what is on screen is {screen.texts()[:12]}", 3583 " | ".join(screen.texts())[:400]) 3584 c.expect(bool(after) or bool(scrollable), 3585 "login-form-cannot-be-scrolled-back", 3586 "the form lost its fields to the keyboard and nothing on the " 3587 "screen scrolls, so there is no way back to them", 3588 " | ".join(screen.texts())[:400]) 3589 c.dev.hide_keyboard() 3590 time.sleep(1.5) 3591 screen, _ = c.ep.observe() 3592 c.expect(bool(c.app.control_reachable(r"^Connect$", screen)) 3593 or bool(screen.find(r"^Connect$")), 3594 "login-form-loses-connect", 3595 f"Connect is not reachable with the keyboard down either: " 3596 f"{screen.texts()[:12]}", " | ".join(screen.texts())[:400]) 3597 3598 3599 @scenario("mock") 3600 def checkout_on_a_mock_backend(c: Ctx) -> None: 3601 """The whole cash checkout against a backend of our own. 3602 3603 Until `mockd.py` grew `/collect` and `/refund-external` this could only 3604 be driven against the shared demo instance, which meant it could not be 3605 parallelised and no fault could be injected into it. This is the proof 3606 that it can be, and the oracle is the mock's own memory: what the 3607 terminal said happened has to match what the backend was asked to do. 3608 """ 3609 c.provision_mock("healthy") 3610 rows = c.app.set_payment_option("Cash", True) 3611 c.require(rows.get("Cash") is True, 3612 f"Cash can be turned on against the mock ({rows})") 3613 c.app.goto("amount") 3614 c.app.enter_amount("3.00") 3615 screen = c.app.charge_to_checkout() 3616 c.observe() 3617 c.ep.note(f"checkout on the mock: {c.app.checkout_amounts(screen)}") 3618 c.app.record_cash("3.00") 3619 c.app.checkout_tile(r"^Complete payment$") 3620 c.dev.wait_for(r"Collect receipt|^Payment received$", timeout=90) 3621 screen, _ = c.ep.observe() 3622 order_id = c.app.displayed_order_id(screen) 3623 c.require(bool(order_id), f"the receipt names the order ({screen.texts()[:10]})") 3624 c.app.tap_button(r"^Collect receipt on this device$") 3625 c.dev.wait_for(MARK_SUCCESS, timeout=90) 3626 c.observe() 3627 assert c.mock is not None 3628 order = c.mock.state.orders.get(order_id) 3629 c.ep.note(f"the mock's order {order_id}: " 3630 f"paid={getattr(order, 'paid', None)} " 3631 f"collected={getattr(order, 'collected', None)}") 3632 c.expect(order is not None and order.collected, 3633 "cash-sale-never-collected", 3634 f"the terminal said the sale was complete and the backend was " 3635 f"never asked to settle {order_id}", 3636 f"order={order!r}") 3637 3638 3639 @scenario("mock") 3640 def checkout_collect_refused(c: Ctx) -> None: 3641 """The backend refuses to settle a sale the cashier has already taken cash for. 3642 3643 This is the worst moment for a backend to say no: the money is in the 3644 till and the customer is leaving. What matters is that the terminal says 3645 so rather than reporting a completed sale, and that it does not lose the 3646 cash it has recorded. 3647 """ 3648 c.provision_mock("collect-fails") 3649 rows = c.app.set_payment_option("Cash", True) 3650 c.require(rows.get("Cash") is True, f"Cash is on ({rows})") 3651 c.app.goto("amount") 3652 c.app.enter_amount("2.00") 3653 c.app.charge_to_checkout() 3654 c.app.record_cash("2.00") 3655 c.app.checkout_tile(r"^Complete payment$") 3656 c.dev.wait_for(r"Collect receipt|^Payment received$", timeout=90) 3657 c.app.tap_button(r"^Collect receipt on this device$") 3658 time.sleep(6) 3659 screen, _ = c.ep.observe() 3660 dialog = c.app.read_dialog(screen) 3661 body = (f"{dialog.title} {dialog.message}" if dialog 3662 else " ".join(screen.texts())) 3663 c.ep.note(f"after a refused collect: {body[:220]}") 3664 c.expect(not bool(screen.find(MARK_SUCCESS)), 3665 "refused-collect-reported-as-paid", 3666 f"the backend refused to settle the order and the terminal says " 3667 f"the payment went through: {screen.texts()[:12]}", body[:400]) 3668 _judge_message(c, body, "a backend that refused to settle a cash sale") 3669 assert c.mock is not None 3670 order_ids = list(c.mock.state.orders) 3671 c.ep.note(f"the mock holds {order_ids}") 3672 c.expect(not any(o.collected for o in c.mock.state.orders.values()), 3673 "refused-collect-recorded-anyway", 3674 "the backend refused the collect and the mock has the order " 3675 "marked settled anyway", 3676 json.dumps({k: v.collected 3677 for k, v in c.mock.state.orders.items()})) 3678 3679 3680 @scenario("demo", "slow") 3681 def checkout_cash_refund_is_recorded(c: Ctx) -> None: 3682 """Hand cash back on a cash sale, and see it reach the backend. 3683 3684 The whole external-refund path is new and has never been driven: a 3685 `RefundAvailability` chooser that offers the methods the order was 3686 actually paid with, a confirmation that the money has physically changed 3687 hands, and `POST /private/orders/<id>/refund-external`. None of it is a 3688 Taler refund, so none of it shows up in `refund_amount` -- the backend 3689 keeps it in `refunds_external`, which is what this checks. 3690 """ 3691 inst = c.demo() 3692 _enable_cash(c) 3693 c.app.goto("amount") 3694 c.app.enter_amount("4.00") 3695 c.app.charge_to_checkout() 3696 c.app.record_cash("4.00") 3697 c.app.checkout_tile(r"^Complete payment$") 3698 c.dev.wait_for(r"Collect receipt|^Payment received$", timeout=90) 3699 screen, _ = c.ep.observe() 3700 order_id = c.app.displayed_order_id(screen) 3701 c.require(bool(order_id), f"the receipt names the order ({screen.texts()[:10]})") 3702 c.app.tap_button(r"^Collect receipt on this device$") 3703 c.dev.wait_for(MARK_SUCCESS, timeout=90) 3704 c.app.continue_from_success() 3705 time.sleep(2) 3706 3707 c.app.goto("history") 3708 time.sleep(4) 3709 screen = c.app._stable_dump() 3710 rows = [n for n in screen.labelled() if n.label.strip() == "Order details"] 3711 c.require(bool(rows), f"the history offers an order to open ({screen.texts()[:12]})") 3712 c.dev.tap_node(min(rows, key=lambda n: n.bounds[1]), screen) 3713 time.sleep(4) 3714 screen, _ = c.ep.observe() 3715 c.require(bool(screen.find(r"^Refund$")), 3716 f"the cash-paid order offers a refund ({screen.texts()[:14]})") 3717 c.app.tap_button(r"^Refund$") 3718 screen = c.dev.wait_for(r"Refund method", timeout=45) 3719 c.observe() 3720 texts = " ".join(screen.texts()) 3721 c.ep.note(f"refund chooser: {screen.texts()[:14]}") 3722 c.expect(bool(screen.find(r"^Cash$")), 3723 "cash-refund-not-offered", 3724 f"the order was paid in cash and the refund screen does not " 3725 f"offer it back: {screen.texts()[:14]}", texts[:400]) 3726 c.expect(bool(re.search(r"(?i)hand the cash back", texts)), 3727 "cash-refund-unexplained", 3728 f"the cash refund offers no instruction about the money itself: " 3729 f"{screen.texts()[:14]}", texts[:400]) 3730 3731 c.app.fill_field(r"^Amount$", "1.50") 3732 time.sleep(1) 3733 if c.dev.keyboard_shown(): 3734 c.dev.hide_keyboard() 3735 time.sleep(1) 3736 c.app.tap_button(r"^Record refund$") 3737 time.sleep(3) 3738 screen, _ = c.ep.observe() 3739 confirm = screen.find(r"Money returned") 3740 c.require(confirm is not None, 3741 f"the terminal asked for confirmation ({screen.texts()[:12]})") 3742 c.dev.tap_node(confirm, screen) 3743 time.sleep(5) 3744 screen, _ = c.ep.observe() 3745 dialog = c.app.read_dialog(screen) 3746 c.ep.note(f"after recording: {dialog or screen.texts()[:12]}") 3747 said_recorded = bool(dialog and re.search(r"(?i)recorded", str(dialog))) 3748 c.expect(said_recorded, 3749 "cash-refund-not-acknowledged", 3750 f"the terminal did not say the refund was recorded: " 3751 f"{dialog or screen.texts()[:12]}", 3752 " | ".join(screen.texts())[:400]) 3753 3754 status = inst.merchant.order_status(inst.token.value, order_id) 3755 external = status.get("refunds_external") or [] 3756 c.ep.note(f"backend refunds_external: {json.dumps(external)[:300]}") 3757 c.expect(any(_minor_json(r.get("amount")) == 150 for r in external), 3758 "cash-refund-never-reached-the-backend", 3759 f"the terminal said the refund was recorded on the order and the " 3760 f"backend has {external!r} against {order_id}", 3761 json.dumps(external)[:400]) 3762 c.expect(_minor_json(status.get("refund_amount")) == 0, 3763 "cash-refund-counted-as-a-taler-refund", 3764 f"handing cash back should not become a Taler refund; the " 3765 f"backend reports refund_amount={status.get('refund_amount')!r}", 3766 json.dumps({"refund_amount": status.get("refund_amount")})) 3767 3768 3769 def _minor(shown: Optional[str]) -> Optional[int]: 3770 """A displayed amount as whole minor units, or None if there is none. 3771 3772 The terminal renders amounts with the currency's symbol and the locale's 3773 grouping -- "\u30af7.00", "1,234.56" -- and a scenario comparing against the 3774 backend cares about the number, not the dressing. 3775 """ 3776 if not shown: 3777 return None 3778 m = Pos.AMOUNT_SHOWN.search(shown) 3779 if m: 3780 text = m.group(0) 3781 else: 3782 # A whole number has no separator, and the backend writes amounts that 3783 # way: "KUDOS:0", "KUDOS:4". Reading those as "no amount at all" 3784 # turned a correct zero into a finding. 3785 whole = re.search(r"\d+", shown) 3786 if whole is None: 3787 return None 3788 text = whole.group(0) 3789 for sep in ("\u00a0", "\u202f", " "): 3790 text = text.replace(sep, "") 3791 if text.count(",") and text.count("."): 3792 text = text.replace(",", "") 3793 elif text.count(",") > 1: 3794 text = text.replace(",", "") 3795 else: 3796 text = text.replace(",", ".") 3797 whole, _, frac = text.partition(".") 3798 whole = whole.replace(".", "") 3799 return int(whole or 0) * 100 + int((frac + "00")[:2] or 0) 3800 3801 3802 def _order_amount(status: dict) -> Optional[str]: 3803 """What the backend says an order is for, paid or not. 3804 3805 `total_amount` is only in an *unpaid* order's status; once it is paid the 3806 figure is in `contract_terms.amount`, and reading the first field alone 3807 reported the correct four-unit order as an order for nothing. 3808 """ 3809 direct = status.get("total_amount") 3810 if direct: 3811 return direct 3812 return (status.get("contract_terms") or {}).get("amount") 3813 3814 3815 def _minor_json(amount: Optional[str]) -> Optional[int]: 3816 """A backend amount ("KUDOS:4.5") as whole minor units.""" 3817 if not amount or ":" not in amount: 3818 return None 3819 return _minor(amount.split(":", 1)[1]) 3820 3821 3822 # ========================================================================= 3823 # fault injection: a real backend made to go wrong 3824 # ========================================================================= 3825 # 3826 # The mock answers like a merchant who is set up badly. Twister answers like 3827 # the demo backend having a bad day: everything is the real exchange until one 3828 # field, one status code or one byte count is not. That is where the 3829 # terminal's error branches live -- `Response.getFailureString` picks one of 3830 # five arms by exception type, `fallbackStatusMessage` one of seven by status 3831 # code, and nothing a correctly configured backend says reaches any of them. 3832 # 3833 # Two rules learned from writing these. A mutation fires once, so a *single* 3834 # backend call can be targeted exactly by arming it immediately before the tap 3835 # that makes it; anything the terminal polls needs `sustain`, which re-arms in 3836 # a loop. And a failed login leaves the form on screen, so `expect_success` 3837 # has to be False or `provision_by_form` fails the scenario for the app's 3838 # correct behaviour. 3839 3840 3841 def _order_to_delete(c: Ctx) -> str: 3842 """An unpaid order sitting in the history, ready to be deleted. 3843 3844 Created through the merchant API rather than the terminal, so that the 3845 twister mutation armed later lands on the delete and not on something the 3846 terminal was doing on its way there. 3847 """ 3848 inst = c.demo() 3849 order = inst.merchant.create_order( 3850 inst.token.value, f"{inst.currency}:1", 3851 "pos-simulator to delete under fault") 3852 order_id = order["order_id"] 3853 c.ep.note(f"created {order_id} to delete") 3854 c.app.goto("history") 3855 c.app.refresh_history() 3856 time.sleep(2) 3857 screen = c.app._stable_dump() 3858 c.require(bool(screen.find(r"^Delete order$")), 3859 f"the history offers a delete action ({screen.texts()[:14]})") 3860 return order_id 3861 3862 3863 @scenario("fault", "demo") 3864 def fault_delete_refused_as_claimed(c: Ctx) -> None: 3865 """A delete the backend refuses with 409, which is a real claim. 3866 3867 Only possible since taler-twister learned to proxy DELETE: before that 3868 the request never reached a backend at all, so no scenario could see what 3869 the terminal does with the answer. 409 is the one status where the 3870 force-delete prompt is the right response, so this is the arm that should 3871 stay green. 3872 """ 3873 c.provision_twister() 3874 _order_to_delete(c) 3875 assert c.tw is not None 3876 c.tw.status(409) 3877 c.app.tap_button(r"^Delete order$") 3878 time.sleep(6) 3879 screen, _ = c.ep.observe() 3880 dialog = c.app.read_dialog(screen) 3881 body = (f"{dialog.title} {dialog.message}" if dialog 3882 else " ".join(screen.texts())) 3883 c.ep.note(f"after a 409 on the delete: {body[:220]}") 3884 c.expect(dialog is not None and re.search(r"(?i)force", str(dialog)) is not None, 3885 "claimed-delete-offers-no-force", 3886 f"the backend refused the delete with 409 and the terminal did " 3887 f"not offer to force it: {body[:200]}", body[:400]) 3888 3889 3890 @scenario("fault", "demo") 3891 def fault_delete_server_error(c: Ctx) -> None: 3892 """A delete the backend fails with 502, which is *not* a claim. 3893 3894 The terminal raises its force-delete prompt on any failed delete and 3895 throws the reason away, so a plain server error is reported to the 3896 cashier as "This order has been claimed by a wallet" -- filed as 3897 bugs.gnunet.org 11977 with a patch. This is the regression test for it, 3898 and it could not be written until twister could carry a DELETE. 3899 """ 3900 c.provision_twister() 3901 _order_to_delete(c) 3902 assert c.tw is not None 3903 c.tw.status(502) 3904 c.app.tap_button(r"^Delete order$") 3905 time.sleep(6) 3906 screen, _ = c.ep.observe() 3907 dialog = c.app.read_dialog(screen) 3908 body = (f"{dialog.title} {dialog.message}" if dialog 3909 else " ".join(screen.texts())) 3910 c.ep.note(f"after a 502 on the delete: {body[:220]}") 3911 c.expect(re.search(r"(?i)claimed by a wallet", body) is None, 3912 "failed-delete-blamed-on-a-wallet", 3913 f"the delete failed with a server error and the terminal told " 3914 f"the cashier a wallet had claimed the order: {body[:200]}", 3915 body[:400]) 3916 _judge_message(c, body, "a delete the backend answered 502") 3917 3918 3919 def _fault_dialog_text(c: Ctx) -> tuple[str, Optional[Dialog]]: 3920 """Whatever the terminal said about the fault, dialog or screen.""" 3921 screen, _ = c.ep.observe() 3922 dialog = c.app.read_dialog(screen) 3923 body = (f"{dialog.title} {dialog.message}" if dialog 3924 else " ".join(screen.texts())) 3925 return body, dialog 3926 3927 3928 def _clear_dialog(c: Ctx) -> None: 3929 """Close whatever modal is up, by its button and not by its geometry. 3930 3931 `Pos.dismiss_dialog` goes through `read_dialog`, which infers the dialog 3932 from where things are on screen and returns None when the inference fails. 3933 That is the right conservative answer for *reading* a dialog and the wrong 3934 one for getting rid of it: a sweep that arms seven faults in a row leaves 3935 the first dialog up and then times out looking for a button behind it. 3936 Here it is enough that something dismissible is on screen. 3937 """ 3938 for _ in range(3): 3939 screen = c.app._stable_dump() 3940 node = screen.find(r"^(OK|Ok|ok|Dismiss|Close)$") 3941 if node is None: 3942 return 3943 c.dev.tap_node(node, screen) 3944 time.sleep(1.5) 3945 3946 3947 def _tap_through_dialogs(c: Ctx, pattern: str, tries: int = 4) -> bool: 3948 """Press a control that a dialog keeps appearing in front of. 3949 3950 A screen that fetches on its own puts its error dialog back up between the 3951 clearing and the tap, so one `_clear_dialog` before the tap is not enough: 3952 the fault scenarios arm, tap, read, arm again, and the second arming raced 3953 the dialog the first one had raised. 3954 """ 3955 for _ in range(tries): 3956 _clear_dialog(c) 3957 try: 3958 c.app.tap_button(pattern, timeout=10) 3959 return True 3960 except (PosError, TimeoutError): 3961 time.sleep(2) 3962 return False 3963 3964 3965 def _judge_message(c: Ctx, body: str, what: str) -> None: 3966 """A fault report has to name the failure and not leak the stack. 3967 3968 Both halves have been seen to fail for real: round one's finding 4 is a 3969 dialog that shows the backend's own 401 hint instead of the terminal's 3970 session-expired string, and a dialog quoting `io.ktor...` is the shape of 3971 "internal error" this harness exists to find. 3972 """ 3973 c.expect(not re.search(r"(?i)exception|io\.ktor|kotlinx\.|java\.lang|" 3974 r"\bat [a-z]+\.[a-z]+\.", body), 3975 "exception-in-dialog", 3976 f"{what} produced a message quoting an exception or a stack " 3977 f"frame: {body[:200]!r}", 3978 body[:600]) 3979 # A message need not say "exception" to be one. kotlinx.serialization's 3980 # own wording -- "Field 'orders' is required for type with serial name 3981 # 'net.taler.merchantlib.OrderHistory'" -- names a Kotlin class and a 3982 # serial name and is shown verbatim, which tells a cashier nothing and 3983 # tells everyone else what the app is built out of. 3984 c.expect(not re.search(r"serial name|\bnet\.taler\.[a-z]+\.[A-Za-z]|" 3985 r"\bIllegal input\b", body), 3986 "internal-type-name-in-dialog", 3987 f"{what} produced a message naming an internal type: " 3988 f"{body[:220]!r}", 3989 body[:600]) 3990 c.expect(bool(body.strip()), 3991 "silent-failure", 3992 f"{what} produced no message at all", 3993 body[:600]) 3994 3995 3996 @scenario("fault", "demo") 3997 def fault_login_server_error(c: Ctx) -> None: 3998 """Every backend call during login answers 500.""" 3999 c.provision_twister(expect_success=False, 4000 arm_during_login=(("status", 500),)) 4001 body, dialog = _fault_dialog_text(c) 4002 c.ep.note(f"login against a 500 backend: {body[:300]}") 4003 c.require(bool(body.strip()), "the terminal said something about the 500") 4004 c.expect(bool(re.search(r"(?i)server error|500|could not", body)), 4005 "server-error-not-named", 4006 f"a backend answering 500 to everything produced: {body[:200]!r}", 4007 body[:600]) 4008 _judge_message(c, body, "a backend answering 500") 4009 _clear_dialog(c) 4010 screen, _ = c.ep.observe() 4011 c.expect(bool(screen.find(AT_LOGIN)), 4012 "stuck-after-server-error", 4013 "a 500 during login left the terminal somewhere other than the " 4014 "login form", 4015 " | ".join(screen.texts())[:500]) 4016 4017 4018 @scenario("fault", "demo") 4019 def fault_login_malformed_reply(c: Ctx) -> None: 4020 """The backend's replies are truncated mid-JSON during login. 4021 4022 Not a status code and not a connection failure: a 200 whose body stops. 4023 Ktor's deserializer throws, which is the `else` arm of 4024 `getFailureString` -- the one that shows `exception.message`, and so the 4025 one most likely to put a serialization error in front of a cashier. 4026 """ 4027 c.provision_twister(expect_success=False, 4028 arm_during_login=(("malform",),)) 4029 body, _ = _fault_dialog_text(c) 4030 c.ep.note(f"login against truncated JSON: {body[:300]}") 4031 c.require(bool(body.strip()), "the terminal reported the truncated reply") 4032 _judge_message(c, body, "a truncated JSON reply") 4033 4034 4035 @scenario("fault", "demo") 4036 def fault_login_connection_cut(c: Ctx) -> None: 4037 """The connection closes in the middle of the response body. 4038 4039 This is the only way to reach the `IOException` arm of 4040 `Response.getFailureString`: the request succeeded, the status was 200, the 4041 headers arrived, and then the socket went away. No status code produces 4042 it and neither does an unreachable host, which fails earlier and 4043 differently. 4044 """ 4045 tw = c.provision_twister() 4046 # On the history screen *before* the fault goes in: the dialog it raises 4047 # covers the screen's own markers, so a `goto` inside the block waits out 4048 # its timeout looking for a button behind a modal. 4049 c.app.goto("history") 4050 with c.front.transport("cut"): 4051 # The history fragment fetches its first page as it opens, so the 4052 # dialog is usually already up by the time the block starts and there 4053 # is no Refresh button to find behind it. Either way is the fault 4054 # firing; what must not happen is waiting out a timeout for a button 4055 # the dialog is covering. 4056 deadline = time.monotonic() + 40 4057 body = "" 4058 while time.monotonic() < deadline: 4059 body, dialog = _fault_dialog_text(c) 4060 if dialog is not None or re.search(r"(?i)error", body): 4061 break 4062 try: 4063 c.app.tap_button(r"Refresh history", timeout=8) 4064 except (PosError, TimeoutError): 4065 pass 4066 time.sleep(3) 4067 c.ep.note(f"a body that stopped halfway: {body[:300]}") 4068 c.require(bool(body.strip()), "the terminal reported the cut connection") 4069 _judge_message(c, body, "a response body that stopped halfway") 4070 c.expect(bool(re.search(r"(?i)network|connection|internet|merchant url", 4071 body)), 4072 "transport-error-shows-the-library-wording", 4073 f"a response body that stopped halfway was reported as " 4074 f"{body[:200]!r}. merchant-lib has a sentence for this -- " 4075 f"\"Network error: check your internet connection and merchant " 4076 f"URL.\" -- but `Response.getFailureString` only reaches it for " 4077 f"SocketTimeout, Connect and UnknownHost; every other IOException " 4078 f"falls through to `exception.message`, which is whatever the HTTP " 4079 f"engine happened to call it", 4080 body[:600]) 4081 _clear_dialog(c) 4082 with c.front.transport("none"): 4083 c.app.tap_button(r"Refresh history") 4084 time.sleep(8) 4085 screen, _ = c.ep.observe() 4086 c.expect(bool(c.app.history_rows(screen)), 4087 "history-does-not-recover", 4088 "after one cut connection the history list stayed empty even " 4089 "though the backend answers correctly again", 4090 " | ".join(screen.texts())[:500]) 4091 4092 4093 @scenario("fault", "demo") 4094 def fault_login_wrong_content_type(c: Ctx) -> None: 4095 """The backend answers JSON labelled as plain text.""" 4096 c.provision_twister( 4097 expect_success=False, 4098 arm_during_login=(("header", "Content-Type", "text/plain"),)) 4099 body, _ = _fault_dialog_text(c) 4100 c.ep.note(f"login against text/plain JSON: {body[:300]}") 4101 _judge_message(c, body, "JSON labelled text/plain") 4102 4103 4104 @scenario("fault", "demo") 4105 def fault_status_code_sweep(c: Ctx) -> None: 4106 """Every status code the terminal has its own sentence for. 4107 4108 `Response.fallbackStatusMessage` has seven arms and the terminal's own 4109 dialogs sit on top of them. One history refresh makes exactly one backend 4110 call, so each code can be aimed at precisely instead of hoping a login 4111 hits the right request. 4112 """ 4113 c.provision_twister() 4114 c.app.goto("history") 4115 seen: dict[int, str] = {} 4116 for code in (400, 401, 403, 404, 408, 503, 418): 4117 assert c.tw is not None 4118 c.tw.status(code) 4119 c.app.tap_button(r"Refresh history") 4120 time.sleep(5) 4121 body, dialog = _fault_dialog_text(c) 4122 seen[code] = body[:160] 4123 c.ep.note(f"{code}: {body[:160]}") 4124 _judge_message(c, body, f"a {code} from the backend") 4125 _clear_dialog(c) 4126 c.require(len(seen) == 7, "all seven status codes were served and read") 4127 c.expect(len({v for v in seen.values() if v}) > 1, 4128 "status-codes-indistinguishable", 4129 "every status code from 400 to 418 produced the same message, so " 4130 "a cashier cannot tell a bad request from a server fault: " 4131 f"{seen}", 4132 json.dumps(seen)[:900]) 4133 # 401 is the session-expired case, and round one found it showing the 4134 # backend's hint rather than the terminal's own string. Checked here 4135 # again, on a real backend, because this is the cheapest route to it. 4136 c.expect(not re.search(r"(?i)^error \d+ \(401\)", seen.get(401, "").strip()), 4137 "unauthorized-shows-protocol-error", 4138 f"a 401 showed the protocol error verbatim: {seen.get(401)!r}", 4139 seen.get(401, "")) 4140 4141 4142 @scenario("fault", "demo") 4143 def fault_order_creation_server_error(c: Ctx) -> None: 4144 """The order the cashier just rang up comes back 502.""" 4145 c.provision_twister() 4146 c.app.goto("amount") 4147 c.app.enter_amount("1.00") 4148 assert c.tw is not None 4149 c.tw.status(502) 4150 c.ep.perform(Action("tap_label", "Create order (charge amount)")) 4151 time.sleep(8) 4152 body, _ = _fault_dialog_text(c) 4153 c.ep.note(f"order creation against a 502: {body[:300]}") 4154 c.require(bool(body.strip()), "the terminal reported the failed order") 4155 c.expect(bool(re.search(r"(?i)could not create|order", body)), 4156 "order-failure-unnamed", 4157 f"an order refused with 502 produced: {body[:200]!r}", 4158 body[:600]) 4159 _judge_message(c, body, "an order refused with 502") 4160 4161 4162 @scenario("fault", "demo") 4163 def fault_order_creation_malformed(c: Ctx) -> None: 4164 """The order is created and the reply says so unintelligibly. 4165 4166 The dangerous half of this is not the dialog: the backend really did 4167 create the order, so a terminal that reports a failure and walks away has 4168 left an order behind that nobody will collect. That is what the history 4169 comparison at the end is for. 4170 """ 4171 inst = c.demo() 4172 before = {o.get("order_id") for o in inst.merchant.history(inst.token.value, limit=-8)} 4173 c.provision_twister() 4174 c.app.goto("amount") 4175 c.app.enter_amount("1.00") 4176 assert c.tw is not None 4177 c.tw.malform() 4178 c.ep.perform(Action("tap_label", "Create order (charge amount)")) 4179 time.sleep(10) 4180 body, _ = _fault_dialog_text(c) 4181 c.ep.note(f"order creation with a truncated reply: {body[:300]}") 4182 _judge_message(c, body, "an order whose reply was truncated") 4183 after = inst.merchant.history(inst.token.value, limit=-8) 4184 # Narrowed to orders that look like the one this scenario just asked for. 4185 # The instance is shared, and a diff of the whole history blamed the 4186 # terminal for an order another worker had created *and paid* 67 seconds 4187 # earlier -- which is how this scenario reported two orphans from a single 4188 # POST. 4189 fresh = [o for o in after 4190 if o.get("order_id") not in before 4191 and o.get("summary") == "Regular order" 4192 and str(o.get("amount")) == f"{inst.currency}:1"] 4193 c.ep.note(f"orders the backend gained: {[o.get('order_id') for o in fresh]}") 4194 # A history entry carries `paid`; `order_status` belongs to 4195 # GET /private/orders/{id} and is simply absent here, so asking for it 4196 # made `!= "paid"` true of every order, paid ones included. 4197 unpaid = [o for o in fresh if not o.get("paid")] 4198 if not EXCLUSIVE_DEMO: 4199 c.ep.note("another worker shares this instance, so the orders it " 4200 "gained are not this scenario's to count") 4201 return 4202 c.expect(len(unpaid) <= 1, 4203 "orphaned-orders-after-unreadable-reply", 4204 f"an order reply the terminal could not read left " 4205 f"{len(unpaid)} unpaid orders behind: " 4206 f"{[o.get('order_id') for o in unpaid]}", 4207 json.dumps(fresh)[:800]) 4208 4209 4210 # The insecure-pay-URI dialog stacks its three buttons in a Column rather than 4211 # laying them out in a row, and `Pos.read_dialog` infers a dialog from exactly 4212 # that row -- so it returns None for this one even with the dialog plainly on 4213 # screen. It is recognised by what it says instead. 4214 INSECURE_URI_DIALOG = re.compile( 4215 r"Payment link problem|Try fixed link|Continue as is") 4216 4217 4218 def _insecure_dialog_on(screen) -> bool: 4219 return bool(screen.find(INSECURE_URI_DIALOG.pattern)) 4220 4221 4222 def _insecure_uri_dialog(c: Ctx, button: str) -> tuple[Optional[str], str]: 4223 """Charge an amount, make the pay URI insecure, and press `button`. 4224 4225 The terminal polls the order's status about once a second, and each poll 4226 overwrites the previous one -- so a single mutation raises the dialog for 4227 one poll and the next poll dismisses it again. `sustain` keeps the URI 4228 insecure for as long as it takes to read the dialog and press something. 4229 """ 4230 tw = c.provision_twister() 4231 c.app.goto("amount") 4232 c.app.enter_amount("1.00") 4233 # Arm the mutation *before* the order exists, so the terminal's first 4234 # status poll already sees the insecure URI: `Pos.charge` would wait for a 4235 # payment screen that the dialog is covering. 4236 insecure = "taler+http://pay/backend.demo.taler.net/instances/sandbox/x/" 4237 with tw.sustain(("modify", "taler_pay_uri", insecure)): 4238 c.ep.perform(Action("tap_label", "Create order (charge amount)")) 4239 deadline = time.monotonic() + 60 4240 dialog = None 4241 screen = c.app._stable_dump() 4242 while time.monotonic() < deadline: 4243 screen = c.app._stable_dump() 4244 if _insecure_dialog_on(screen): 4245 dialog = c.app.read_dialog(screen) 4246 break 4247 time.sleep(1.5) 4248 c.require(_insecure_dialog_on(screen), 4249 "the terminal objected to a taler+http:// pay URI " 4250 f"(screen: {screen.texts()[:10]})") 4251 c.ep.note(f"insecure-URI dialog: {dialog}") 4252 c.ep.observe() 4253 c.ep.perform(Action("tap_label", button)) 4254 time.sleep(4) 4255 screen, _ = c.ep.observe() 4256 # Read the URI here, while the backend is still being made to hand out 4257 # an insecure one. Outside the block the next status poll gets the 4258 # real `taler://` URI and the terminal replaces what it is showing with 4259 # it -- which is correct, and which made "continue as is" look like it 4260 # had been ignored. 4261 uri = c.app.displayed_pay_uri() 4262 c.ep.note(f"pay URI while the backend is still wrong: {uri}") 4263 return uri, " | ".join(screen.texts()) 4264 4265 4266 @scenario("fault", "demo") 4267 def fault_insecure_pay_uri_upgrade(c: Ctx) -> None: 4268 """A taler+http:// pay URI, upgraded to https on the cashier's say-so.""" 4269 uri, after = _insecure_uri_dialog(c, "Try fixed link") 4270 c.ep.note(f"after upgrading: {after[:300]}") 4271 c.expect(bool(uri and uri.startswith("taler://")), 4272 "https-upgrade-did-not-upgrade", 4273 f"accepting the HTTPS upgrade left the terminal showing {uri!r}", 4274 after[:600]) 4275 4276 4277 @scenario("fault", "demo") 4278 def fault_insecure_pay_uri_continue(c: Ctx) -> None: 4279 """A taler+http:// pay URI the cashier decides to use anyway.""" 4280 uri, after = _insecure_uri_dialog(c, "Continue as is") 4281 c.ep.note(f"after continuing: {after[:300]}") 4282 c.expect(bool(uri and uri.startswith("taler+http://")), 4283 "insecure-uri-not-honoured", 4284 f"choosing to continue with the insecure URI showed {uri!r} " 4285 f"instead of the insecure one the cashier accepted", 4286 after[:600]) 4287 4288 4289 @scenario("fault", "demo") 4290 def fault_insecure_pay_uri_cancel(c: Ctx) -> None: 4291 """A taler+http:// pay URI the cashier refuses, cancelling the order.""" 4292 _, after = _insecure_uri_dialog(c, "Cancel order") 4293 # The order id, so that "claimed by a wallet" can be checked against what 4294 # the backend actually thinks. Round four could not answer that because 4295 # the id was never written down. 4296 # The payment screen's own order id is unreadable here -- the force-delete 4297 # dialog is on top of it -- so fall back to the id the terminal logs when 4298 # its delete fails. 4299 order_id = c.app.displayed_order_id() 4300 if not order_id: 4301 hit = re.findall(r"Delete order (\S+) (?:failed|succeeded)", 4302 c.dev.logcat(lines=4000)) 4303 order_id = hit[-1] if hit else None 4304 c.ep.note(f"order on screen: {order_id}") 4305 # Asked of the backend directly, not through twister: the dialog claims a 4306 # wallet has claimed the order, so what the backend thinks of it is the 4307 # only thing that can settle that. 4308 if order_id: 4309 try: 4310 inst = c.demo() 4311 status = inst.merchant.order_status(inst.token.value, order_id) 4312 c.ep.note(f"backend on {order_id}: order_status=" 4313 f"{status.get('order_status')!r}") 4314 except Exception as e: # a 404 is itself an answer 4315 c.ep.note(f"backend on {order_id}: {e}") 4316 c.ep.note(f"after cancelling: {after[:300]}") 4317 screen, _ = c.ep.observe() 4318 c.expect(not bool(screen.find(MARK_PAYMENT)) or 4319 bool(screen.find(MARK_AMOUNT)) or bool(screen.find(MARK_ORDER)), 4320 "cancel-left-the-payment-screen-up", 4321 "cancelling the order over an insecure pay URI left the terminal " 4322 "on the payment screen", 4323 after[:600]) 4324 4325 4326 @scenario("fault", "demo") 4327 def fault_history_unreadable(c: Ctx) -> None: 4328 """The order history comes back as something that is not an order history. 4329 4330 Three shapes in one scenario, because each is one refresh: a truncated 4331 body, a deleted field, and a flipped character inside a string. The last 4332 is the subtle one -- the JSON still parses, so nothing throws, and whatever 4333 the terminal draws it draws from a value that is wrong. 4334 """ 4335 c.provision_twister() 4336 c.app.goto("history") 4337 c.app.tap_button(r"Refresh history") 4338 time.sleep(6) 4339 screen, _ = c.ep.observe() 4340 rows = c.app.history_rows(screen) 4341 c.require(bool(rows), f"the history list has rows to corrupt ({len(rows)})") 4342 assert c.tw is not None 4343 for label, arm in (("truncated", ("malform",)), 4344 ("no orders field", ("delete", "orders")), 4345 ("flipped summary", ("flip", "orders.0.summary"))): 4346 # Each round leaves a dialog over the Refresh button, and the screen 4347 # puts it back up on its own, so the tap has to keep clearing it. 4348 _clear_dialog(c) 4349 getattr(c.tw, arm[0])(*arm[1:]) 4350 c.require(_tap_through_dialogs(c, r"Refresh history"), 4351 f"the history could be refreshed for the {label} round") 4352 time.sleep(6) 4353 body, dialog = _fault_dialog_text(c) 4354 c.ep.note(f"history {label}: {(str(dialog) or body)[:240]}") 4355 _judge_message(c, body if dialog else "ok", f"a {label} history") 4356 _clear_dialog(c) 4357 screen, _ = c.ep.observe() 4358 c.expect(bool(screen.find(MARK_HISTORY)), 4359 "history-screen-lost", 4360 f"a {label} history reply took the terminal off the history " 4361 f"screen: {screen.texts()[:10]}", 4362 " | ".join(screen.texts())[:500]) 4363 _tap_through_dialogs(c, r"Refresh history") 4364 time.sleep(6) 4365 screen, _ = c.ep.observe() 4366 c.expect(bool(c.app.history_rows(screen)), 4367 "history-does-not-recover", 4368 "after three broken replies the history list stayed empty even " 4369 "though the backend answers correctly again", 4370 " | ".join(screen.texts())[:500]) 4371 4372 4373 @scenario("fault", "demo", "slow") 4374 def fault_chaos_walk(c: Ctx) -> None: 4375 """The terminal driven normally while one request in eight fails. 4376 4377 Deliberate scenarios arm one fault and look at one screen. What they 4378 cannot produce is a fault arriving at a moment nobody chose -- a config 4379 refresh failing while the order screen is already up, a status poll failing 4380 between two successful ones. Chaos mode is twister answering 503 at 4381 random, and what is being checked is only that nothing crashes and nothing 4382 ends up on a dead screen. 4383 """ 4384 c.provision_twister(chaos=12, expect_success=False) 4385 c.ep.observe() 4386 screen = c.app._stable_dump() 4387 # Logging in may itself have failed; retry until it sticks, because the 4388 # walk is the point and a 503 on the first call is not. 4389 for _ in range(6): 4390 if not screen.find(AT_LOGIN): 4391 break 4392 _clear_dialog(c) 4393 try: 4394 c.app.provision_by_form(c.tw.host, merchant.DEMO_INSTANCE, 4395 merchant.DEMO_SECRET, expect_success=False) 4396 except PosError as e: 4397 c.ep.note(f"login retry: {e}") 4398 screen = c.app._stable_dump() 4399 c.require(not screen.find(AT_LOGIN), 4400 "the terminal got a session despite the chaos") 4401 c.ep.note("logged in under chaos; walking") 4402 for destination in ("amount", "inventory", "history", "settings", 4403 "amount", "history", "inventory"): 4404 try: 4405 c.app.goto(destination) 4406 except (PosError, TimeoutError) as e: 4407 c.ep.note(f"goto {destination}: {e}") 4408 screen = c.app._stable_dump() 4409 if c.app.read_dialog(screen) is not None: 4410 c.app.dismiss_dialog() 4411 continue 4412 screen, findings = c.ep.observe() 4413 dialog = c.app.read_dialog(screen) 4414 if dialog is not None: 4415 c.ep.note(f"{destination}: {dialog}") 4416 _judge_message(c, f"{dialog.title} {dialog.message}", 4417 f"a 503 while opening {destination}") 4418 _clear_dialog(c) 4419 c.require(True, "the terminal was walked under a 12% failure rate") 4420 screen, _ = c.ep.observe() 4421 c.expect(not bool(screen.find(MARK_FETCHING)), 4422 "stuck-on-spinner-after-chaos", 4423 "a walk under random 503s ended on the configuration spinner", 4424 " | ".join(screen.texts())[:500]) 4425 4426 4427 @scenario("fault", "demo") 4428 def fault_token_request_tampered(c: Ctx) -> None: 4429 """The login's own token request is altered on the way up. 4430 4431 Twister can mutate a *request*, not only a reply, and the terminal's login 4432 is the one place it sends a body of its own -- the token request carrying 4433 the scope and the duration. A backend that gets a scope the terminal did 4434 not ask for is a thing no amount of reply-breaking can produce. 4435 """ 4436 c.provision_twister(expect_success=False, 4437 arm_during_login=(("modify_upload", "scope", "readonly"),)) 4438 body, _ = _fault_dialog_text(c) 4439 c.ep.note(f"login with a tampered token request: {body[:300]}") 4440 screen, _ = c.ep.observe() 4441 _judge_message(c, body if body.strip() else "ok", 4442 "a token request altered in flight") 4443 c.require(True, "the token request was altered in flight and the terminal " 4444 "neither crashed nor hung") 4445 c.expect(not bool(screen.find(MARK_FETCHING)), 4446 "stuck-on-spinner-after-tampered-token", 4447 "a tampered token request left the terminal on the spinner", 4448 " | ".join(screen.texts())[:500]) 4449 4450 4451 def _order_total(screen) -> Optional[str]: 4452 """The order screen's running total, as it is drawn. 4453 4454 Two places carry it and the wording differs: the order pane's header says 4455 "Total: KUDOS 5.50" and the complete button says "Bill KUDOS 5.50" 4456 (`order_total` and `order_complete_with_amount`). The compact layout 4457 drops the header, so a scenario that only knew the first one read an 4458 order with a total in it as an order with none. 4459 """ 4460 for pattern in (r"Total:\s*(\S.*)$", r"^Bill\s+(\S.*)$"): 4461 for node in screen.nodes: 4462 m = re.search(pattern, node.label.strip()) 4463 if m: 4464 return m.group(1).strip() 4465 return None 4466 4467 4468 def _order_id_from(uri: Optional[str]) -> Optional[str]: 4469 """The order id inside a `taler://pay/` URI.""" 4470 if not uri: 4471 return None 4472 m = re.search(r"/instances/[^/]+/([^/?]+)/?", uri) 4473 if m: 4474 return m.group(1) 4475 m = re.search(r"taler(?:\+http)?://pay/[^/]+/([^/?]+)", uri) 4476 return m.group(1) if m else None 4477 4478 4479 # -- the runner ----------------------------------------------------------- 4480 4481 4482 def run_one(name: str, out_dir: Path, coverage_dir: Optional[Path]) -> dict: 4483 fn, tags, doc = SCENARIOS[name] 4484 dev = Device(SERIAL) 4485 ep = Episode(dev, out_dir, name=name, coverage_dir=coverage_dir) 4486 app = Pos(dev) 4487 app.before_wipe = lambda: ep.dump_coverage("before-wipe") 4488 c = Ctx(dev=dev, app=app, ep=ep, name=name) 4489 started = time.monotonic() 4490 outcome, error = "ok", "" 4491 try: 4492 fn(c) 4493 except ScenarioFailure as e: 4494 outcome, error = "unreached", str(e) 4495 except (PosError, TimeoutError) as e: 4496 outcome, error = "unreached", f"{type(e).__name__}: {e}" 4497 except Exception as e: 4498 outcome, error = "harness-error", f"{type(e).__name__}: {e}" 4499 traceback.print_exc() 4500 try: 4501 ep.observe() 4502 except Exception: 4503 pass 4504 summary = ep.finish({ 4505 "tags": list(tags), 4506 "doc": doc, 4507 "outcome": outcome, 4508 "error": error, 4509 "checks": c.checks, 4510 "seconds": round(time.monotonic() - started, 1), 4511 }) 4512 serious = summary["serious"] 4513 print(f" {outcome:<14} {name:<36} {summary['seconds']:>6.1f}s " 4514 f"{len(summary['findings'])} finding(s), {serious} serious" 4515 + (f"\n {error}" if error else "")) 4516 return summary 4517 4518 4519 def main(argv: list[str]) -> int: 4520 ap = argparse.ArgumentParser(description=__doc__, 4521 formatter_class=argparse.RawDescriptionHelpFormatter) 4522 ap.add_argument("names", nargs="*") 4523 ap.add_argument("--list", action="store_true") 4524 ap.add_argument("--all", action="store_true") 4525 ap.add_argument("--tag", action="append", default=[]) 4526 ap.add_argument("--skip-tag", action="append", default=[]) 4527 ap.add_argument("--out", default=None) 4528 ap.add_argument("--no-coverage", action="store_true") 4529 args = ap.parse_args(argv) 4530 4531 if args.list: 4532 width = max(len(n) for n in SCENARIOS) 4533 for name, (_, tags, doc) in SCENARIOS.items(): 4534 print(f" {name:<{width}} [{','.join(tags)}] {doc}") 4535 print(f"\n{len(SCENARIOS)} scenarios") 4536 return 0 4537 4538 chosen = list(args.names) 4539 if args.all or args.tag or not chosen: 4540 # Named scenarios are kept rather than replaced, so that a selection 4541 # can be "everything except the mock set, plus these three mock ones" 4542 # -- which is what the campaign asks for when a scenario needs a 4543 # screen only one worker's geometry can show. 4544 selected = [n for n, (_, tags, _) in SCENARIOS.items() 4545 if (not args.tag or set(args.tag) & set(tags)) 4546 and not (set(args.skip_tag) & set(tags))] 4547 chosen = selected + [n for n in chosen if n not in selected] 4548 unknown = [n for n in chosen if n not in SCENARIOS] 4549 if unknown: 4550 print(f"unknown scenario(s): {unknown}; --list shows them all") 4551 return 2 4552 4553 stamp = time.strftime("%Y%m%d-%H%M%S") 4554 out_dir = Path(args.out or (SIM_ROOT / "out" / f"suite-{stamp}-w{WORKER}")) 4555 out_dir.mkdir(parents=True, exist_ok=True) 4556 coverage_dir = None if args.no_coverage else SIM_ROOT / "run" / "coverage" 4557 if coverage_dir: 4558 coverage_dir.mkdir(parents=True, exist_ok=True) 4559 4560 print(f"{len(chosen)} scenario(s) on {SERIAL}, artifacts in {out_dir}") 4561 summaries = [] 4562 try: 4563 for name in chosen: 4564 summaries.append(run_one(name, out_dir, coverage_dir)) 4565 finally: 4566 stop_mocks() 4567 stop_twisters() 4568 4569 (out_dir / "suite.json").write_text(json.dumps(summaries, indent=2)) 4570 ok = [s for s in summaries if s["outcome"] == "ok"] 4571 unreached = [s for s in summaries if s["outcome"] == "unreached"] 4572 broken = [s for s in summaries if s["outcome"] == "harness-error"] 4573 serious = sum(s["serious"] for s in summaries) 4574 print(f"\n{len(ok)} ok, {len(unreached)} unreached, {len(broken)} harness errors; " 4575 f"{serious} serious finding(s) across {len(summaries)} scenarios") 4576 print(f"artifacts: {out_dir}") 4577 return 0 if not broken else 1 4578 4579 4580 if __name__ == "__main__": 4581 sys.exit(main(sys.argv[1:]))