pos.py (75332B)
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 terminal as a set of things one can ask it to do. 15 16 `device.py` knows about taps and labels; this knows about the point-of-sale 17 app: how it is provisioned, how its four screens are reached, how an order is 18 built and billed, and how long each of those legitimately takes. Scenarios are 19 written against this, so that a change to the app's wording costs one edit here 20 rather than one per scenario. 21 22 Every label is a regular expression matched against the English strings in 23 `merchant-terminal/src/main/res/values/strings.xml`, which is the source of 24 truth for translations and therefore the only locale a scenario may assume. 25 """ 26 27 from __future__ import annotations 28 29 import os 30 import re 31 import time 32 from dataclasses import dataclass 33 from pathlib import Path 34 from typing import Callable, Optional 35 36 from device import Device, Node, Screen 37 38 # Screens, by something only that screen shows. The terminal has no titles on 39 # most screens -- the Compose shell draws one top bar for the order screen, one 40 # for history and a bare one for everything else -- so these key off content. 41 MARK_CONFIG = r"Merchant portal URL|Manual config|QR config" 42 MARK_FETCHING = r"Fetching configuration" 43 MARK_AMOUNT = r"Create order \(charge amount\)|Charge" 44 MARK_ORDER = r"Bill|Everything|Add custom product" 45 # The complete-order button is "Bill" with an empty order and "Bill <amount>" 46 # with anything in it, so a pattern with the space baked in matches only half 47 # the time -- which read as a screen with no way to bill. Written once here 48 # because it drifted the moment it was written twice. 49 BILL_BUTTON = r"^Bill( .*)?$|^Complete order$" 50 MARK_HISTORY = r"Refresh history|Payment history" 51 MARK_SETTINGS = r"App settings|Login settings|Modify login settings" 52 # The payment screen reached from a checkout words its instruction 53 # differently ("Scan the QR code with your mobile wallet.") and offers "Back 54 # to payment options" where a plain order offers "Cancel payment", so a marker 55 # built from the old wording waited two minutes on a screen that was already 56 # there. 57 MARK_PAYMENT = (r"scan QR Code|Scan the QR code|Cancel payment" 58 r"|confirm payment|Back to payment options|^Pay with$") 59 # Anchored, and not negotiable: `Screen.find` matches case-insensitively, and 60 # the terminal's failure string is "Error: No payment received" -- which 61 # contains this one. Unanchored, a scenario asking "did the payment NOT 62 # succeed?" was answered "it did" by the very error that says it did not. 63 MARK_SUCCESS = r"^Payment received$" 64 # Master renamed the refund form's submit button: it was "Approve refund" and 65 # is now "Refund Taler", beside a "Refund method" chooser that lets the 66 # cashier pick which payment to give back. Both wordings are matched so the 67 # harness can be run against either build. 68 MARK_REFUND_FORM = r"Approve refund|^Refund Taler$|Refund method" 69 APPROVE_REFUND = r"Approve refund|^Refund Taler$" 70 MARK_REFUND_URI = r"offer refund" 71 # The mixed-payment checkout, which stands between the order and the payment 72 # screen as soon as a second payment option is turned on. "Order total" is 73 # the tablet heading and "To pay:" the compact one, so both are listed. 74 MARK_CHECKOUT = (r"Choose payment method|Order total|To pay:|Total:" 75 r"|Payments so far|Charge with Taler" 76 r"|Charge remaining with Taler|Complete payment") 77 MARK_CHECKOUT_PAD = r"Record .* cash|Charge .* on card" 78 # The Settings screen quotes the payment-options description in its own card, 79 # so "Taler is always available" matches both screens and a reader that waited 80 # for it never left Settings. The per-option descriptions are only on the 81 # options screen itself. 82 MARK_PAYMENT_OPTIONS = r"^Open .* settings$" 83 84 # The error dialog, which is one AlertDialog reused for everything: a title, a 85 # message and an OK button. Its message is the only place several failures say 86 # anything at all, so it is read rather than just dismissed. 87 ERROR_TITLES = ( 88 r"Taler POS", r"Error: ", r"No payment received", r"Could not create order", 89 r"Not enough inventory", r"Could not delete order", r"Invalid username", 90 r"Could not connect", r"configuration JSON is malformed", 91 r"Invalid configuration", r"Enter an amount", r"Unsupported currency", 92 r"Refund state is no longer available", 93 ) 94 95 96 class PosError(RuntimeError): 97 """The harness could not get the terminal to where the scenario needs it.""" 98 99 100 @dataclass 101 class Dialog: 102 """A modal the terminal is showing, flattened to what a tester reads.""" 103 104 title: str 105 message: str 106 buttons: list[str] 107 108 def __str__(self) -> str: 109 return f"{self.title!r}: {self.message!r} {self.buttons}" 110 111 112 class Pos: 113 """One terminal, driven through its UI.""" 114 115 def __init__(self, dev: Device): 116 self.dev = dev 117 # Anything that wipes the app takes the coverage collected so far with 118 # it; the episode plugs in a dump here. 119 self.before_wipe: Optional[Callable[[], None]] = None 120 121 # -- lifecycle -------------------------------------------------------- 122 123 def fresh_start(self, grant_camera: bool = True) -> None: 124 """An unconfigured terminal on a settled device. 125 126 A wipe is the only reliable way back to the login screen: "Log out" 127 leaves the saved language and the initial-order-screen preference 128 behind, which is right for a user and wrong for a scenario that wants 129 to know what a first run looks like. 130 """ 131 if self.before_wipe: 132 self.before_wipe() 133 self.dev.stop() 134 self.dev.clear_data() 135 # Every scenario starts from a known orientation. A scenario that 136 # turns the device and then fails would otherwise leave the worker in 137 # portrait, and the next twenty scenarios would quietly test the other 138 # half of five layouts while reporting the names of this one. 139 want_portrait = os.environ.get("POS_PORTRAIT", "0") != "0" 140 if self.dev.is_portrait() != want_portrait: 141 # Noted and carried on with rather than raised: a device that 142 # will not turn is worth knowing about, but failing here turns 143 # every scenario after a rotating one into a harness error and 144 # hides whatever they would have found. 145 try: 146 self.dev.rotate(portrait=want_portrait) 147 except RuntimeError as exc: 148 print(f" !! could not restore orientation: {exc}") 149 if grant_camera: 150 # pm clear revokes it, and the QR config screen asks for it the 151 # moment that tab is selected -- a permission dialog on top of the 152 # screen under test is not what any scenario is looking at. 153 self.dev.grant_camera() 154 self.dev.launch() 155 self.wait_for_config_screen() 156 157 def relaunch(self) -> None: 158 self.dev.stop() 159 self.dev.launch() 160 time.sleep(2) 161 162 def process_death(self) -> None: 163 """Kill the process the way the system would, then come back.""" 164 self.dev.kill() 165 time.sleep(1.5) 166 self.dev.launch() 167 time.sleep(2) 168 169 # -- provisioning ----------------------------------------------------- 170 171 def wait_for_config_screen(self, timeout: int = 90) -> Screen: 172 """Wait for the login form, fields and all. 173 174 The tab row ("Manual config", "QR config") and the screen title are 175 laid out before the fields are, and all three match MARK_CONFIG -- so 176 a wait on the marker alone came back with a form that had nothing to 177 type into, and every scenario that provisions by form failed at the 178 first field with "no text field on screen at all". What a scenario 179 is actually waiting for is somewhere to type. 180 """ 181 screen = self.dev.wait_for(MARK_CONFIG, timeout=timeout) 182 deadline = time.monotonic() + 20 183 while time.monotonic() < deadline: 184 if screen.editable() or screen.find(r"Scan the QR|Fetching"): 185 return screen 186 time.sleep(1.0) 187 screen = self._stable_dump() 188 return screen 189 190 def provision_by_uri(self, uri: str, timeout: int = 120, 191 expect_success: bool = True) -> Screen: 192 """Configure the terminal with a `taler-pos://` setup URI. 193 194 This is how a merchant provisions a terminal in practice: the back 195 office shows a QR code, the terminal scans it. Delivering the same 196 string as a deep link exercises every line of the parse and the fetch 197 that follows, and leaves the camera out of it -- `provision_by_qr` 198 covers the camera. 199 """ 200 self.dev.setup_uri(uri) 201 if not expect_success: 202 time.sleep(4) 203 return self.dev.dump() 204 return self.wait_for_order_entry(timeout=timeout) 205 206 def _reach_next_field(self, label: str, screen: Screen, 207 tries: int = 3) -> Screen: 208 """Bring the next field of a form into view, the way a cashier does. 209 210 On a screen too short to hold the form under the keyboard -- a phone 211 in landscape is 411 dp and the keyboard takes two thirds of it -- the 212 form shows one field at a time and the others are not laid out at all. 213 Neither a scroll gesture nor a dump can reach them: there is nothing 214 to swipe, because the list has one item in it. 215 216 What does reach them is the keyboard's own Next key. The form wires 217 every field's `ImeAction.Next` to `focusManager.moveFocus(Down)` and 218 the list scrolls whatever takes focus into view, so moving focus is 219 both how a cashier gets there and how the next field comes to exist. 220 """ 221 for _ in range(tries): 222 if screen.find(label) or any( 223 re.search(label, n.label, re.I) for n in screen.labelled()): 224 return screen 225 self.dev.key("KEYCODE_TAB") 226 time.sleep(1.2) 227 screen = self._stable_dump() 228 return screen 229 230 def _wait_for_fields(self, count: int = 1, timeout: int = 25) -> Screen: 231 """A dump that actually has editable fields in it.""" 232 deadline = time.monotonic() + timeout 233 screen = self._stable_dump() 234 while time.monotonic() < deadline: 235 if len(screen.editable()) >= count: 236 return screen 237 time.sleep(1.0) 238 screen = self._stable_dump() 239 return screen 240 241 def provision_by_form(self, host: str, instance: str, token: str, 242 save_password: bool = True, timeout: int = 120, 243 expect_success: bool = True) -> Screen: 244 """Type the merchant URL, instance and password into the login form. 245 246 The form is what a human uses, and it is also the only path that goes 247 through `POST /private/token` from the device -- so it is the only one 248 that can hit the two-factor challenge the backend may ask for. 249 250 Note what it does *not* do: the duration is hard-coded to "forever". 251 An expiring session cannot be set up here; it has to be minted outside 252 and delivered as a setup URI. 253 """ 254 screen = self.wait_for_config_screen() 255 if screen.find(r"^Manual config$"): 256 self.tap_button(r"^Manual config$") 257 time.sleep(1) 258 # Switching tabs recomposes the form, and the tab row is drawn 259 # before the fields are. A plain dump here described a screen 260 # with nothing to type into, and every form-provisioned scenario 261 # died at the first field. 262 screen = self._wait_for_fields() 263 264 self.fill_field(r"Merchant portal URL", host, screen) 265 # A stable dump, not a plain one: filling a field raises the keyboard 266 # and the phone layout scrolls under it, so a dump taken while that is 267 # still happening describes a form that has already moved. 268 screen = self._stable_dump() 269 # Two fields are labelled "Password": the form's and, on some 270 # backends, a token-validity row. The form's is the editable one that 271 # follows Username, which is what fill_field resolves. 272 for label, value in ((r"^Username$", instance), (r"^Password$", token)): 273 screen = self._reach_next_field(label, screen) 274 self.fill_field(label, value, screen) 275 screen = self._stable_dump() 276 277 screen = self.dev.dump() 278 remember = screen.find(r"Remember password") 279 if remember is not None: 280 node = screen.tap_target(remember) 281 if node.checkable and node.checked != save_password: 282 self.dev.tap_node(remember, screen) 283 time.sleep(0.5) 284 285 self.tap_button(r"^Connect$") 286 if not expect_success: 287 time.sleep(6) 288 return self.dev.dump() 289 return self.wait_for_order_entry(timeout=timeout) 290 291 def fill_demo_credentials(self) -> Screen: 292 """Use the terminal's own "Fill demo credentials" button. 293 294 It prefills backend.demo.taler.net with the sandbox instance, which is 295 the first thing a reviewer does -- and the only path where the 296 credential never passes through the harness, so a defect in the 297 prefill itself is visible. 298 """ 299 screen = self.wait_for_config_screen() 300 if not screen.find(r"Fill demo credentials"): 301 # The help card is collapsed until "No account?" is tapped; it was 302 # called "No instance?" before master renamed it. 303 self.tap_button(r"No account\?|No instance\?") 304 time.sleep(1) 305 screen = self.dev.wait_for(r"Fill demo credentials", timeout=20) 306 self.tap_button(r"Fill demo credentials") 307 time.sleep(1.5) 308 return self.dev.dump() 309 310 def provision_by_qr(self, timeout: int = 180) -> Screen: 311 """Switch to the QR tab and wait for the poster on the wall to be read. 312 313 The emulator's virtual scene can only be given its poster at launch, so 314 the image has to already be hanging there; `emu/emu.sh boot <w> <png>` 315 is what puts it up. This only selects the tab and waits. 316 317 It deliberately does not confirm that the QR screen appeared. 318 `uiautomator dump` returns the *previous* layout while a camera 319 preview is on screen -- the screenshot shows the live preview and the 320 "Scan the QR code" hint while the hierarchy still describes the login 321 form, for as long as the preview is up. So the tab selection is 322 verified by screenshot during development and by its effect here: 323 either the terminal provisions itself from what it saw, or it does 324 not. 325 """ 326 screen = self.wait_for_config_screen() 327 node = screen.find(r"^QR config$") 328 if node is None: 329 raise PosError(f"no QR tab on the login screen: {screen.texts()}") 330 self.dev.tap_node(node, screen) 331 time.sleep(2) 332 return self.wait_for_order_entry(timeout=timeout) 333 334 # -- navigation ------------------------------------------------------- 335 336 def open_drawer(self, timeout: int = 20) -> Screen: 337 """Open the navigation drawer through the hamburger button. 338 339 The button carries no contentDescription, so it cannot be found by 340 label; it is the leftmost small unlabelled clickable in the top bar, 341 which is stable across all three top-bar variants the shell draws. 342 343 A dump taken while the UI is settling comes back empty, and an empty 344 dump here reads as "this screen has no drawer button" -- which is the 345 same thing a locked drawer looks like. So the dump is retried before 346 any conclusion is drawn from it. 347 """ 348 screen = self._stable_dump() 349 if screen.find(r"^History$") and screen.find(r"^Settings$"): 350 return screen # already open 351 _, height = self.dev.size() 352 candidates = [n for n in screen.nodes 353 if n.clickable and n.enabled and n.area > 0 354 and n.bounds[1] < height // 4 355 and not n.label.strip() 356 and (n.bounds[2] - n.bounds[0]) < 220] 357 if not candidates: 358 raise PosError(f"no drawer button in the top bar; screen: {screen.texts()}") 359 self.dev.tap_node(min(candidates, key=lambda n: n.bounds[0]), screen) 360 return self.dev.wait_for(r"^Settings$", timeout=timeout) 361 362 def _leave_subscreen(self, screen: Screen, tries: int = 4) -> Screen: 363 """Back out of a screen that has no drawer, so the drawer is reachable. 364 365 The payment-options screen, an option's own settings and the order 366 details page are routes of their own: the top bar carries a Back arrow 367 where the drawer button would be. Both are an unlabelled clickable 368 node in the top-left corner, so `open_drawer` cannot tell them apart 369 and happily pressed Back -- which left the terminal one screen up and 370 the navigation one tap behind, and the failure landed on whatever was 371 tapped next. There is one honest signal: the drawer button's own 372 content description. 373 """ 374 for _ in range(tries): 375 if screen.find(r"^Open navigation menu$") or not screen.nodes: 376 return screen 377 self.dev.back() 378 time.sleep(1.0) 379 screen = self._stable_dump() 380 return screen 381 382 def _stable_dump(self, tries: int = 4) -> Screen: 383 """A dump with something in it. 384 385 `uiautomator dump` answers with an empty hierarchy often enough to 386 matter -- during a navigation animation, while a dialog is being 387 laid out -- and every caller that reasons about which nodes are 388 present needs to tell "nothing there" from "nothing read yet". 389 """ 390 screen = self.dev.dump() 391 for _ in range(tries - 1): 392 if screen.nodes: 393 return screen 394 time.sleep(1.0) 395 screen = self.dev.dump() 396 return screen 397 398 def goto(self, destination: str, timeout: int = 60) -> Screen: 399 """Open one of the four drawer destinations and wait for it. 400 401 `destination` is one of "amount", "inventory", "history", "settings". 402 A destination the terminal is already showing is not navigated to 403 again: re-entering a route rebuilds its fragment, which throws away 404 whatever the scenario had just put on screen. 405 """ 406 rows = { 407 "amount": (r"^Order by amount$", MARK_AMOUNT), 408 "inventory": (r"^Order by inventory$", MARK_ORDER), 409 "history": (r"^History$", MARK_HISTORY), 410 "settings": (r"^Settings$", MARK_SETTINGS), 411 } 412 if destination not in rows: 413 raise ValueError(f"unknown destination {destination!r}") 414 label, mark = rows[destination] 415 current = self._stable_dump() 416 # A modal blocks the drawer, and a scenario that has already recorded 417 # the dialog should still be able to carry on -- a backend hiccup in 418 # the middle of a scenario should not cost the rest of it. 419 if self.read_dialog(current) is not None: 420 self.dismiss_dialog() 421 current = self._stable_dump() 422 if current.find(mark) and not current.find(r"^Log out$|^History$"): 423 return current 424 if current.find(mark) and destination in ("amount", "inventory"): 425 return current 426 current = self._leave_subscreen(current) 427 # The drawer slides in, and a tap that lands while it is still moving 428 # selects nothing: the drawer stays open and the next wait times out 429 # on a screen that is showing four navigation rows. That reads like 430 # the destination does not exist, so it is retried rather than 431 # reported. 432 last: Optional[Exception] = None 433 for attempt in range(3): 434 self.open_drawer() 435 time.sleep(0.6) 436 try: 437 self.tap_button(label) 438 except PosError as exc: 439 last = exc 440 continue 441 try: 442 return self.dev.wait_for(mark, timeout=timeout // (1 + attempt)) 443 except TimeoutError as exc: 444 last = exc 445 screen = self._stable_dump() 446 if not screen.find(r"^Close navigation menu$"): 447 raise 448 assert last is not None 449 raise last 450 451 def wait_for_order_entry(self, timeout: int = 120) -> Screen: 452 """Wait for whichever order screen the terminal starts on. 453 454 Which one it is depends on a saved preference, so a scenario that 455 wants a particular one asks for it with `goto`; this only waits for 456 provisioning to have finished. A configuration error arrives as a 457 dialog rather than as a screen, so it is turned into an exception that 458 names the message -- otherwise the timeout says nothing. 459 """ 460 deadline = time.monotonic() + timeout 461 while time.monotonic() < deadline: 462 screen = self.dev.dump() 463 if screen.find(MARK_AMOUNT) or screen.find(MARK_ORDER): 464 return screen 465 dialog = self.read_dialog(screen) 466 if dialog is not None: 467 raise PosError(f"provisioning failed with a dialog: {dialog}") 468 time.sleep(1.5) 469 raise PosError(f"no order screen within {timeout}s; " 470 f"screen showed: {self.dev.dump().texts()}") 471 472 # -- widgets ---------------------------------------------------------- 473 474 def tap_button(self, pattern: str, timeout: int = 30) -> Screen: 475 """Tap the control that carries a label, not the label's screen title. 476 477 The terminal reuses strings between a heading and the button below it 478 -- "Refund" is a history row's action and the refund screen's own 479 wording, "Settings" is a drawer row and a section heading -- so a plain 480 label search lands on text that cannot be tapped. The lowest matching 481 node that is itself clickable, or sits inside something clickable, is 482 the control. 483 """ 484 screen = self._wait_or_scroll(pattern, timeout) 485 # The IME does not resize this app's screens, so a button the 486 # hierarchy still reports at its layout position may be underneath the 487 # keyboard; a tap there lands on a key and the scenario sees a control 488 # that "does nothing". Putting the keyboard away first removes the 489 # whole class -- but it is done with Back, and Back is also what 490 # dismisses a Compose AlertDialog. Where the IME had already gone, or 491 # where it never covered the control, that Back closed the dialog 492 # instead and the button "vanished before the tap": the custom-product 493 # dialog's Add and the two-factor dialog's OK, both of which a dialog 494 # window draws above the keyboard anyway. 495 # 496 # So the keyboard is only put away when the control is actually behind 497 # it, which the dump itself says: with the IME up the root bounds stop 498 # where the keyboard starts. 499 if self.dev.keyboard_shown() and not self._within_window(pattern, screen): 500 self.dev.hide_keyboard() 501 time.sleep(0.5) 502 screen = self._wait_or_scroll(pattern, max(timeout, 10)) 503 screen = self._scroll_into_view(pattern, screen) 504 rx = re.compile(pattern, re.I) 505 matches = [n for n in screen.nodes if n.label and rx.search(n.label)] 506 if not matches: 507 raise PosError(f"{pattern!r} vanished before the tap") 508 scored = [] 509 for node in matches: 510 target = screen.tap_target(node) 511 interactive = target.clickable and target.enabled 512 scored.append((0 if interactive else 1, -node.bounds[1], node)) 513 scored.sort() 514 chosen = scored[0][2] 515 self.dev.tap_node(chosen, screen) 516 time.sleep(1.0) 517 return screen 518 519 def _wait_or_scroll(self, pattern: str, timeout: int, 520 tries: int = 4) -> Screen: 521 """Wait for a label, scrolling if the screen has somewhere to scroll. 522 523 A control below the fold is not on the screen *at all* -- a lazy list 524 does not compose what it is not showing -- so waiting for it times out 525 with a message that reads like the control does not exist. The login 526 form is the case that matters: once the keyboard is up it scrolls, and 527 Connect, "Remember password" and "No account?" are all underneath it. 528 Scrolling first and judging afterwards is the only way to tell "this 529 screen has no such button" from "this screen has not shown it yet". 530 """ 531 last: Optional[Exception] = None 532 per_try = max(5, timeout // tries) 533 for attempt in range(tries): 534 try: 535 return self.dev.wait_for(pattern, timeout=per_try) 536 except TimeoutError as exc: 537 last = exc 538 screen = self._stable_dump() 539 if not any(n.scrollable for n in screen.nodes): 540 break 541 before = screen.texts() 542 self.dev.scroll(down=True, screen=screen) 543 time.sleep(0.8) 544 if self._stable_dump().texts() == before: 545 # Already at the end; one more wait would say the same thing. 546 break 547 assert last is not None 548 raise last 549 550 def _within_window(self, pattern: str, screen: Screen) -> bool: 551 """Whether a control can be tapped where the dump says it is. 552 553 Two things can hide it. The window the dump describes may end above 554 it, which is the ordinary "below the fold". Or the keyboard may be 555 drawing over it -- and for a *dialog* the dump covers only the dialog, 556 which happily reports its buttons at coordinates the keyboard owns. 557 That is not theoretical: a tap aimed at the custom-product dialog's 558 Add button landed on the letter u and typed it into the field. 559 """ 560 box = screen.root_bounds() 561 if not box: 562 return False 563 ime_top = self.dev.ime_top() 564 if ime_top is None: 565 # The keyboard is up and nothing says where: assume it is in the 566 # way, which is what the driver did before it could ask. Guessing 567 # the other way taps a key and types a letter into whatever has 568 # focus. 569 return False 570 rx = re.compile(pattern, re.I) 571 bottom = min(box[3], ime_top) 572 return any(n.label and rx.search(n.label) and n.bounds[3] <= bottom 573 for n in screen.nodes) 574 575 def control_reachable(self, pattern: str, 576 screen: Optional[Screen] = None) -> bool: 577 """Whether a control can actually be pressed where it is drawn. 578 579 False when the keyboard is over it, which on a short screen is where 580 a dialog's buttons end up -- the dialog is its own window and reports 581 them at their layout position regardless. 582 """ 583 screen = screen or self._stable_dump() 584 ime_top = self.dev.ime_top() 585 if ime_top is None: 586 return bool(screen.find(pattern)) 587 rx = re.compile(pattern, re.I) 588 return any(n.label and rx.search(n.label) and n.bounds[3] <= ime_top 589 for n in screen.nodes) 590 591 def _scroll_into_view(self, pattern: str, screen: Screen, 592 tries: int = 3) -> Screen: 593 """Bring a control inside the window, if the layout has it below. 594 595 The login form is taller than a phone's screen in landscape and 596 Connect is the last thing on it: with the keyboard up the form scrolls 597 itself and Connect is reachable, with the keyboard down it is a couple 598 of hundred pixels past the bottom edge. A tap there does nothing at 599 all, which reads as a dead button -- and the keyboard has to be down 600 before the tap for the separate reason above, so one of the two has to 601 give and it is this one. 602 """ 603 rx = re.compile(pattern, re.I) 604 _, height = self.dev.size() 605 for _ in range(tries): 606 matches = [n for n in screen.nodes if n.label and rx.search(n.label)] 607 if not matches or any(n.bounds[3] <= height for n in matches): 608 return screen 609 before = screen 610 self.dev.scroll(down=True, screen=before) 611 time.sleep(1) 612 screen = self._stable_dump() 613 # A scroll aimed at the largest scrollable can move something that 614 # is not the control -- a dialog's own list, say -- and carry the 615 # control off the screen altogether. Losing it is worse than not 616 # having moved it, so that is undone. 617 if not any(n.label and rx.search(n.label) for n in screen.nodes): 618 self.dev.scroll(down=False, screen=before) 619 time.sleep(1) 620 return self._stable_dump() 621 return screen 622 623 def field_for(self, label: str, screen: Optional[Screen] = None) -> Node: 624 """The text field a label belongs to. 625 626 A Material text field draws its label *inside* its own box while the 627 field is empty and lifts it to the top edge once there is content, so 628 the label and the field are two nodes whose relationship changes as 629 the form is filled. Three rules in order, each exact enough to be 630 wrong loudly rather than quietly: 631 632 1. the field whose own label matches -- which is how a filled field 633 with a floating label and a placeholder presents itself; 634 2. the field whose box contains the label's centre, which covers the 635 empty case and the lifted case alike; 636 3. failing that, the nearest field below the label. 637 638 Rule 2 replaced a "first field at or below the label's top edge" test, 639 which looked equivalent and was not: the login form's empty Username 640 label starts a single pixel below its own field, so the field was 641 excluded and the *password* field was the nearest match. Typing the 642 instance name into the password box is not the kind of mistake a 643 scenario notices -- the form just refuses to log in. 644 """ 645 screen = screen or self._stable_dump() 646 fields = screen.editable() 647 if not fields: 648 # The caller may have handed in a screen from before a navigation, 649 # or the dump may have lost its race; read it again before 650 # concluding that the form has no fields. 651 screen = self._stable_dump() 652 fields = screen.editable() 653 rx = re.compile(label, re.I) 654 if not fields: 655 raise PosError(f"no text field on screen at all; " 656 f"screen: {screen.texts()}") 657 direct = next((n for n in fields if rx.search(n.label)), None) 658 if direct is not None: 659 return direct 660 anchors = [n for n in screen.nodes if n.label and rx.search(n.label)] 661 if not anchors: 662 raise PosError(f"no field labelled {label!r}; screen: {screen.texts()}") 663 anchor = anchors[0] 664 ax, ay = anchor.center 665 containing = [n for n in fields 666 if n.bounds[0] <= ax <= n.bounds[2] 667 and n.bounds[1] <= ay <= n.bounds[3]] 668 if containing: 669 return min(containing, key=lambda n: n.area) 670 below = [n for n in fields if n.bounds[1] >= anchor.bounds[3] - 8] 671 if below: 672 return min(below, key=lambda n: (n.bounds[1], n.bounds[0])) 673 raise PosError( 674 f"{label!r} has no field inside or below it; " 675 f"label at {anchor.bounds}, fields at {[n.bounds for n in fields]}") 676 677 def fill_field(self, label: str, text: str, 678 screen: Optional[Screen] = None, 679 verify: bool = True) -> None: 680 """Clear the field belonging to a label and type into it. 681 682 With `verify`, what the field ends up holding is checked against what 683 was typed -- by content where the field shows its text, and by length 684 where it shows dots instead. A field that did not take the text is 685 the single most expensive kind of harness bug there is: the form then 686 fails to log in, and the scenario reports that the terminal rejected a 687 valid credential. 688 """ 689 screen = screen or self._stable_dump() 690 field = self._field_in_view(label, screen) 691 self.dev.clear_field(field, screen) 692 self.dev.type_text(text) 693 time.sleep(0.5) 694 if not verify: 695 return 696 after = self._stable_dump() 697 try: 698 now = self.field_for(label, after) 699 except PosError: 700 return # the layout moved; nothing to check against 701 value = now.label 702 masked = set(value) <= set("\u2022*\u00b7 ") 703 if masked and value: 704 if len(value.strip()) != len(text): 705 raise PosError( 706 f"the field for {label!r} holds {len(value.strip())} " 707 f"masked characters, not the {len(text)} that were typed") 708 return 709 if value.strip() != text.strip(): 710 raise PosError( 711 f"the field for {label!r} holds {value!r} after typing {text!r}") 712 713 def _field_in_view(self, label: str, screen: Screen) -> Node: 714 """The field for a label, at coordinates a tap can still reach. 715 716 On a tablet the login form fits and the coordinates in any dump are 717 good. On a phone it does not: the form scrolls itself to keep the 718 focused field above the soft keyboard, so the second field a scenario 719 fills has moved by a couple of hundred pixels since the dump it was 720 resolved from -- and a tap at the old place lands on the keyboard, 721 where it silently types a letter into the field that still has focus. 722 723 So the box is checked against the window the dump itself describes. If 724 it falls outside, the form is scrolled and the field resolved again; 725 if it is still outside, that is worth failing on rather than tapping 726 blind. 727 """ 728 # A form short enough to scroll does not compose the fields it is not 729 # showing, so a field further down is not merely out of the window -- 730 # it is not in the hierarchy at all, and `field_for` says there is no 731 # such field. That is the same sentence a form genuinely without the 732 # field would produce, so the scroll has to come first and the 733 # complaint afterwards. 734 for attempt in range(4): 735 try: 736 field = self.field_for(label, screen) 737 except PosError: 738 if attempt == 3: 739 raise 740 # Not "is anything scrollable?": a lazy form showing one item 741 # reports no scrollable node at all, and that is exactly the 742 # case this is for. 743 before = screen.texts() 744 self.dev.scroll(down=True, screen=screen) 745 time.sleep(1) 746 screen = self._stable_dump() 747 if screen.texts() == before: 748 raise 749 continue 750 _, height = self.dev.size() 751 if field.bounds[3] <= height: 752 return field 753 self.dev.scroll(down=True, screen=screen) 754 time.sleep(1) 755 screen = self._stable_dump() 756 field = self.field_for(label, screen) 757 _, height = self.dev.size() 758 if field.bounds[3] > height: 759 raise PosError( 760 f"the field for {label!r} is at {field.bounds}, below the " 761 f"{height}px window, and scrolling did not bring it up") 762 return field 763 raise PosError(f"no field labelled {label!r} after scrolling") 764 765 # Buttons that only a dialog has. Matching on the terminal's own wording 766 # rather than on a widget class, because a Compose AlertDialog's buttons 767 # are ordinary Buttons and nothing in the hierarchy says "dialog". 768 DIALOG_BUTTONS = re.compile( 769 r"(?i)^(ok|cancel|continue|force delete|log out|approve refund|abort|" 770 r"try fixed link|continue as is|cancel order|cancel payment|add|" 771 r"received|dismiss|close)$") 772 773 def read_dialog(self, screen: Optional[Screen] = None) -> Optional[Dialog]: 774 """The modal on screen, if there is one, as a tester reads it. 775 776 Recognised by shape rather than by wording, so that a dialog with an 777 unexpected message is still read -- "Error: Invalid configuration" with 778 nothing else is itself a finding. 779 780 The shape has to be found geometrically. The terminal uses two kinds of 781 modal: a `DialogFragment` (the error dialog), which is its own window 782 and dumps alone; and Compose `AlertDialog`s (logout, force delete, the 783 insecure-payment prompt), which are drawn *into the same window* as the 784 screen behind them -- so that dump contains the whole settings screen 785 as well, and any rule of the form "a dialog has few labels" calls it a 786 screen. What is reliably true is that the dialog's text sits directly 787 above its buttons and within their horizontal span, so that is what is 788 collected. 789 """ 790 screen = screen or self._stable_dump() 791 buttons = [n for n in screen.nodes 792 if n.label.strip() and self.DIALOG_BUTTONS.fullmatch(n.label.strip()) 793 and (n.clickable or screen.tap_target(n).clickable)] 794 if not buttons: 795 return None 796 labels = [n.label.strip() for n in buttons] 797 top = min(n.bounds[1] for n in buttons) 798 above = [n for n in screen.nodes 799 if n.label.strip() 800 and n.label.strip() not in labels 801 and n.bounds[3] <= top + 8 802 and n.bounds[1] >= top - 900] 803 if not above: 804 return None 805 # A dialog of the terminal's dumps as a window of its own, so what is 806 # above the buttons is the dialog and nothing else. The exception is 807 # a modal drawn into the screen behind it, which shows up as far more 808 # text than a dialog has -- and then the dialog's own text is what 809 # shares a column with its widest line. 810 if len(above) > 8: 811 anchor = max(above, key=lambda n: n.bounds[2] - n.bounds[0]) 812 lo, hi = anchor.bounds[0] - 40, anchor.bounds[2] + 40 813 above = [n for n in above if n.bounds[0] >= lo and n.bounds[2] <= hi] 814 if not above: 815 return None 816 above.sort(key=lambda n: (n.bounds[1], n.bounds[0])) 817 texts = [n.label.strip() for n in above] 818 title = texts[0] 819 message = " ".join(texts[1:])[:600] if len(texts) > 1 else "" 820 return Dialog(title=title, message=message, buttons=labels) 821 822 def dismiss_dialog(self) -> Optional[Dialog]: 823 """Read and close whatever modal is up; returns what it said.""" 824 dialog = self.read_dialog() 825 if dialog is None: 826 return None 827 for label in ("OK", "Ok", "ok"): 828 node = self.dev.dump().find(rf"^{label}$") 829 if node is not None: 830 self.dev.tap_node(node, self.dev.dump()) 831 time.sleep(1) 832 return dialog 833 self.dev.back() 834 time.sleep(1) 835 return dialog 836 837 # -- building an order ------------------------------------------------ 838 839 def enter_digits(self, digits: str) -> Screen: 840 """Press keypad keys, in order, without interpreting them. 841 842 The keypad is deliberately digits-only -- there is no decimal key at 843 all. It fills from the right, so "100" is one unit and "1" is one 844 cent, exactly like a till. Scenarios that care about the keypad's own 845 behaviour (overflow, leading zeros, backspace) use this; scenarios that 846 just want to charge a price use `enter_amount`. 847 """ 848 screen = self.dev.wait_for(MARK_AMOUNT, timeout=45) 849 for char in digits: 850 if char in "cC": 851 self.tap_button(r"^Clear$") 852 screen = self.dev.dump() 853 continue 854 if char in "<b": 855 node = screen.find(r"^Backspace$") 856 if node is None: 857 raise PosError("no backspace key on the keypad") 858 self.dev.tap_node(node, screen) 859 time.sleep(0.25) 860 continue 861 node = screen.find(rf"^{re.escape(char)}$") 862 if node is None: 863 raise PosError(f"no keypad key for {char!r}; " 864 f"keys: {sorted(set(screen.texts()))}") 865 self.dev.tap_node(node, screen) 866 time.sleep(0.25) 867 return self.dev.dump() 868 869 # The keypad groups thousands once the amount is long enough, so the 870 # display reads "999,999,999,999.99" rather than a bare run of digits. 871 # Matching only the ungrouped shape reported the terminal's largest 872 # amount as no amount at all. 873 AMOUNT_SHOWN = re.compile(r"\d{1,3}(?:[.,\u00a0\u202f ]\d{3})*[.,]\d{2}|\d+[.,]\d+") 874 875 def displayed_amount(self, screen: Optional[Screen] = None) -> Optional[str]: 876 """The amount the keypad is showing, as the terminal renders it.""" 877 screen = screen or self.dev.dump() 878 keys = {str(d) for d in range(10)} 879 for node in screen.nodes: 880 text = node.label.strip() 881 if text in keys: 882 continue 883 if self.AMOUNT_SHOWN.fullmatch(text): 884 return text 885 return None 886 887 def enter_amount(self, amount: str, verify: bool = True) -> Screen: 888 """Type a price on the keypad of the "order by amount" screen. 889 890 `amount` is written the way it is displayed -- "1.00", "0.05" -- and 891 translated into the keystrokes that produce it, because the keypad has 892 no separator key and fills from the right. With `verify`, what the 893 screen ends up showing is compared against what was asked for, which is 894 the cheapest check there is on the keypad's own arithmetic. 895 896 The keypad is used rather than the text field above it: the field is 897 editable, but the keypad is what a cashier touches, and the two do not 898 share their input filtering. 899 """ 900 if not re.fullmatch(r"\d+(?:[.,]\d+)?", amount): 901 raise ValueError(f"{amount!r} is not a plain decimal amount") 902 digits = amount.replace(".", "").replace(",", "").lstrip("0") or "0" 903 self.tap_button(r"^Clear$") 904 screen = self.enter_digits(digits) 905 if verify: 906 shown = self.displayed_amount(screen) 907 if shown is None: 908 raise PosError(f"the keypad shows no amount after typing {digits!r}; " 909 f"screen: {screen.texts()}") 910 if _as_minor(shown) != _as_minor(amount): 911 raise PosError( 912 f"typing {digits!r} on the keypad was meant to give " 913 f"{amount} and gave {shown}") 914 return screen 915 916 def charge(self, timeout: int = 90) -> Screen: 917 """Press Charge and wait for the payment screen.""" 918 self.tap_button(r"Create order \(charge amount\)|^Charge$") 919 return self.dev.wait_for(MARK_PAYMENT, timeout=timeout) 920 921 def add_products(self, count: int = 1) -> list[str]: 922 """Tap the first sellable products in the order grid. 923 924 Which products exist depends on the instance, so this picks them off 925 the grid rather than by name, and skips the ones the terminal has 926 marked unsellable -- tapping "Out of stock" is a scenario of its own, 927 not a way to build an order. 928 """ 929 screen = self.dev.wait_for(MARK_ORDER, timeout=60) 930 blocked = {"Unavailable", "Out of stock", "Wrong currency"} 931 added: list[str] = [] 932 for _ in range(count): 933 screen = self.dev.dump() 934 cards = self._product_cards(screen, blocked) 935 if not cards: 936 raise PosError(f"no sellable product in the grid; " 937 f"screen: {screen.texts()[:40]}") 938 card = cards[len(added) % len(cards)] 939 self.dev.tap_node(card, screen) 940 added.append(card.label.strip()) 941 time.sleep(1.0) 942 return added 943 944 def _product_cards(self, screen: Screen, blocked: set[str]) -> list[Node]: 945 """The tappable product tiles, with the unsellable ones left out.""" 946 width, height = self.dev.size() 947 out = [] 948 for node in screen.nodes: 949 label = node.label.strip() 950 if not label or label in blocked: 951 continue 952 if node.bounds[0] < width // 5: 953 continue # the category column, not the grid 954 if node.bounds[1] < height // 6: 955 continue # the top bar 956 target = screen.tap_target(node) 957 if not (target.clickable and target.enabled): 958 continue 959 # A price is what tells a product tile from a section label. 960 near = [n.label for n in screen.nodes 961 if abs(n.bounds[1] - node.bounds[1]) < 240 962 and abs(n.bounds[0] - node.bounds[0]) < 240] 963 if not any(re.search(r"\d+[.,]\d\d", t or "") for t in near): 964 continue 965 out.append(node) 966 return out 967 968 def add_custom_product(self, name: str, amount: str) -> Screen: 969 """Use the order screen's "Add custom product" dialog.""" 970 self.tap_button(r"Add custom product") 971 self.dev.wait_for(r"Custom product name", timeout=20) 972 screen = self.dev.dump() 973 self.fill_field(r"Custom product name", name, screen) 974 screen = self.dev.dump() 975 fields = screen.editable() 976 if len(fields) < 2: 977 raise PosError(f"the custom product dialog has {len(fields)} fields, " 978 f"expected a name and an amount") 979 amount_field = max(fields, key=lambda n: (n.bounds[1], n.bounds[0])) 980 self.dev.clear_field(amount_field, screen) 981 self.dev.type_text(amount) 982 time.sleep(0.4) 983 self.tap_button(r"^Add$") 984 return self.dev.dump() 985 986 def open_custom_product_dialog(self) -> Screen: 987 """Open the custom-product dialog and leave it open.""" 988 self.tap_button(r"Add custom product") 989 self.dev.wait_for(r"Custom product name", timeout=20) 990 return self._stable_dump() 991 992 def fill_custom_amount(self, amount: str) -> None: 993 """Type into the dialog's price field. 994 995 The two fields have the same kind of label from the driver's point of 996 view -- the second one's label is the currency -- so it is taken by 997 position: the lower of the two editables. 998 """ 999 screen = self._stable_dump() 1000 fields = screen.editable() 1001 if len(fields) < 2: 1002 raise PosError(f"the custom product dialog has {len(fields)} " 1003 f"fields, expected a name and an amount") 1004 amount_field = max(fields, key=lambda n: (n.bounds[1], n.bounds[0])) 1005 self.dev.clear_field(amount_field, screen) 1006 self.dev.type_text(amount) 1007 time.sleep(0.4) 1008 1009 def select_order_line(self, name: str) -> Screen: 1010 """Tap a product where it appears in the order, not in the grid. 1011 1012 Both show the same text, and the grid's card is the one higher up the 1013 screen on a tablet and on a different pane on a phone -- so the line 1014 is the *lowest* node carrying the name, which is the one inside the 1015 order pane in both layouts. 1016 """ 1017 screen = self._stable_dump() 1018 matches = [n for n in screen.nodes 1019 if n.label and re.search(re.escape(name), n.label)] 1020 if not matches: 1021 raise PosError(f"{name!r} is not in the order") 1022 line = max(matches, key=lambda n: n.bounds[1]) 1023 self.dev.tap_node(line, screen) 1024 time.sleep(1) 1025 return self._stable_dump() 1026 1027 def login_form_values(self) -> tuple[Optional[str], Optional[str]]: 1028 """What the login form's host and username fields hold.""" 1029 screen = self._stable_dump() 1030 host = username = None 1031 try: 1032 host = self.field_for(r"Merchant portal URL", screen).label or None 1033 except PosError: 1034 pass 1035 try: 1036 username = self.field_for(r"^Username$", screen).label or None 1037 except PosError: 1038 pass 1039 return host, username 1040 1041 def bill(self, timeout: int = 90) -> Screen: 1042 """Press Bill on the inventory order screen.""" 1043 self.tap_button(BILL_BUTTON) 1044 return self.dev.wait_for(MARK_PAYMENT, timeout=timeout) 1045 1046 # -- the payment screen ----------------------------------------------- 1047 1048 def copy_displayed_uri(self, scheme: str = "taler", 1049 tries: int = 3) -> Optional[str]: 1050 """Read the URI behind the QR code, through the screen's copy button. 1051 1052 The payment and refund screens render their URI only as a QR code, and 1053 a view-hierarchy dump cannot read an image -- but both screens offer a 1054 copy button, and the sim hooks can read the clipboard back from inside 1055 the app. So the harness sees exactly the string the customer's wallet 1056 would get, and the copy button gets exercised on the way. 1057 1058 Three things are retried, because each of them fails occasionally and 1059 each failure otherwise reads as "the terminal is offering no code at 1060 all": a dump that comes back empty, a tap that lands while the screen 1061 is still settling, and a clipboard that still holds the previous 1062 value. The expected scheme is what tells the last case apart -- which 1063 is why it is checked here rather than by the caller. 1064 """ 1065 for attempt in range(tries): 1066 screen = self._stable_dump() 1067 node = screen.find(r"^Copy$|Copy payment URI") 1068 if node is None: 1069 if not screen.find(MARK_PAYMENT) and not screen.find(MARK_REFUND_URI): 1070 return None # not a screen with a code on it 1071 time.sleep(1.5) 1072 continue 1073 self.dev.tap_node(node, screen) 1074 time.sleep(1.2 + attempt) 1075 value = self.dev.read_clipboard() 1076 if value and value.startswith(scheme): 1077 return value 1078 return None 1079 1080 def displayed_pay_uri(self) -> Optional[str]: 1081 """The pay URI the terminal is currently showing.""" 1082 return self.copy_displayed_uri(scheme="taler") 1083 1084 def published_nfc_uri(self) -> Optional[str]: 1085 """The pay URI the terminal is offering over NFC, if any. 1086 1087 Always absent on an emulator -- there is no NFC adapter for the 1088 service to publish through -- so this exists to confirm the terminal 1089 does not claim an NFC payment is possible when it is not. 1090 """ 1091 payload = self.dev.report_nfc_payload() 1092 return None if payload in (None, "none", "empty-message") else payload 1093 1094 def wait_for_claimed(self, timeout: int = 90) -> Screen: 1095 return self.dev.wait_for(r"confirm payment", timeout=timeout) 1096 1097 def wait_for_success(self, timeout: int = 180) -> Screen: 1098 return self.dev.wait_for(MARK_SUCCESS, timeout=timeout) 1099 1100 def cancel_payment(self) -> Screen: 1101 self.tap_button(r"Cancel payment") 1102 time.sleep(2) 1103 return self.dev.dump() 1104 1105 def continue_from_success(self) -> Screen: 1106 self.tap_button(r"^Continue$") 1107 time.sleep(2) 1108 return self.dev.dump() 1109 1110 # -- history and refunds ---------------------------------------------- 1111 1112 def refresh_history(self, timeout: int = 90) -> Screen: 1113 self.tap_button(r"Refresh history") 1114 # The list keeps its old contents while reloading, so there is nothing 1115 # to wait for on screen except the toast; a short settle is honest. 1116 time.sleep(4) 1117 return self.dev.wait_for(MARK_HISTORY, timeout=timeout) 1118 1119 def history_rows(self, screen: Optional[Screen] = None) -> list[str]: 1120 """The order references the history list is showing.""" 1121 screen = screen or self.dev.dump() 1122 return [n.label.strip() for n in screen.nodes 1123 if re.match(r"(?i)^(Ref|Receipt)\s*#", n.label.strip() or "")] 1124 1125 def open_order_details(self, row: int = 0, timeout: int = 45) -> Screen: 1126 """Open the order-details page for the nth history row, newest first. 1127 1128 `tap_button` cannot be used: every row carries an identical "Order 1129 details" label and it picks the *lowest* match on screen, which is the 1130 oldest order rather than the one a scenario just created. The rows 1131 are therefore sorted by their own position and indexed. 1132 """ 1133 screen = self.dev.wait_for(r"^Order details$", timeout=timeout) 1134 rows = sorted((n for n in screen.labelled() 1135 if n.label.strip() == "Order details"), 1136 key=lambda n: n.bounds[1]) 1137 if row >= len(rows): 1138 raise PosError(f"the history has {len(rows)} row(s) with details, " 1139 f"not {row + 1}") 1140 self.dev.tap_node(rows[row], screen) 1141 time.sleep(3) 1142 return self.dev.wait_for(r"Order reference|Payment breakdown", 1143 timeout=timeout) 1144 1145 def start_refund(self, row_pattern: str = r"^Refund$", 1146 timeout: int = 45) -> Screen: 1147 self.tap_button(row_pattern, timeout=timeout) 1148 # The refund form focuses its amount field as it opens, so the keyboard 1149 # is up before anything has been tapped -- and on a short screen the 1150 # form's buttons are then not in the hierarchy at all, so waiting for 1151 # "Approve refund" waits for something that is not there. Putting the 1152 # keyboard away first is what a person would have to do too. 1153 time.sleep(1) 1154 if self.dev.keyboard_shown(): 1155 self.dev.hide_keyboard() 1156 time.sleep(1) 1157 try: 1158 return self.dev.wait_for(MARK_REFUND_FORM, timeout=timeout) 1159 except TimeoutError: 1160 # The form is open and its controls are not in the hierarchy; that 1161 # is worth a picture, because the difference between "the terminal 1162 # clipped them" and "the driver is looking in the wrong place" is 1163 # not visible in a list of labels. 1164 shot = Path(os.environ.get("POS_SIM_ROOT", "/tmp/taler-pos-sim")) 1165 shot = shot / "out" / "refund-form-without-its-buttons.png" 1166 shot.parent.mkdir(parents=True, exist_ok=True) 1167 self.dev.screenshot(str(shot)) 1168 raise 1169 1170 def submit_refund(self, amount: str, reason: str = "pos-simulator", 1171 expect_success: bool = True) -> Screen: 1172 screen = self.dev.wait_for(MARK_REFUND_FORM, timeout=45) 1173 self.fill_field(r"^Amount$", amount, screen) 1174 screen = self.dev.dump() 1175 if screen.find(r"Refund reason"): 1176 self.fill_field(r"Refund reason", reason, screen) 1177 self._reach_approve_refund() 1178 self.tap_button(APPROVE_REFUND) 1179 if not expect_success: 1180 time.sleep(5) 1181 return self.dev.dump() 1182 return self.dev.wait_for(MARK_REFUND_URI, timeout=90) 1183 1184 def _reach_approve_refund(self) -> None: 1185 """Make sure the refund form's buttons are on screen before tapping. 1186 1187 Filling the amount raises the keyboard, and on a short screen the form 1188 -- a Column with no `verticalScroll` -- then has no room for its two 1189 buttons and drops them from the hierarchy entirely. `start_refund` 1190 sees them because it puts the keyboard away first; by the time the 1191 amount has been typed they are gone again, which is why the failure 1192 lands on the tap and not on opening the form. 1193 1194 The screen is photographed in that state before the keyboard is put 1195 away, because the picture is the evidence for whether this is the 1196 terminal clipping its controls or the driver looking in the wrong 1197 place. 1198 """ 1199 screen = self._stable_dump() 1200 if screen.find(APPROVE_REFUND): 1201 return 1202 shot = Path(os.environ.get("POS_SIM_ROOT", "/tmp/taler-pos-sim")) 1203 shot = shot / "out" / "refund-form-without-its-buttons.png" 1204 shot.parent.mkdir(parents=True, exist_ok=True) 1205 self.dev.screenshot(str(shot)) 1206 if self.dev.keyboard_shown(): 1207 self.dev.hide_keyboard() 1208 time.sleep(1.5) 1209 1210 def refund_uri_for(self, merchant_host: str, instance: str, 1211 order_id: str) -> str: 1212 """The refund URI the terminal is showing, by construction. 1213 1214 The payment screen offers Copy and Share; the refund screen offers 1215 neither -- only Abort -- so the URI behind its QR code cannot be read 1216 off the device at all. It is derived from the order instead, which is 1217 what the backend put in the code. 1218 """ 1219 # The trailing slash is load-bearing: the backend's own builder writes 1220 # an empty final path component (`GNUNET_buffer_write_path (&buf, "")` 1221 # in make_taler_refund_uri), and a wallet rejects the URI without it 1222 # as malformed rather than as an unknown order. 1223 return f"taler://refund/{merchant_host}/instances/{instance}/{order_id}/" 1224 1225 # -- settings --------------------------------------------------------- 1226 1227 def settings_logout(self, confirm: bool = True) -> Screen: 1228 """Log out, through both of the dialogs that stand in the way.""" 1229 self.goto("settings") 1230 self.tap_button(r"^Log out$") 1231 time.sleep(1.5) 1232 if not confirm: 1233 self.tap_button(r"^Cancel$") 1234 return self.dev.dump() 1235 # The first dialog warns what logging out removes and its positive 1236 # button is labelled "Continue"; the second asks "are you sure". 1237 for label in (r"^Continue$", r"^Log out$"): 1238 try: 1239 self.tap_button(label, timeout=15) 1240 except TimeoutError: 1241 break 1242 time.sleep(1.5) 1243 return self.dev.wait_for(MARK_CONFIG, timeout=60) 1244 1245 def about_rows(self) -> dict[str, str]: 1246 """The Settings screen's About block, as label -> value. 1247 1248 It is where the terminal says which instance and URL it is bound to, 1249 which is the only place a scenario can confirm that provisioning 1250 landed where it meant to -- and the backend version it negotiated, 1251 which it appends to the URL in brackets. 1252 1253 The block renders each row as a single `"Label: value"` node, so the 1254 pair is split out of one label rather than matched across two; the 1255 two-node shape is kept as a fallback because a long value wraps. 1256 """ 1257 # The keyboard survives the move from the login form to Settings, and 1258 # it takes two thirds of the list with it -- so the About card's rows 1259 # cannot be scrolled to while it is up, and a reader that did not put 1260 # it away reported an unbound terminal on a terminal that was bound. 1261 if self.dev.keyboard_shown(): 1262 self.dev.hide_keyboard() 1263 time.sleep(0.8) 1264 screen = self.goto("settings") 1265 # The About card is the last item of a lazy list, so finding its 1266 # *title* is not enough -- the rows under it are still off screen, and 1267 # a reader that stopped there reported an unbound terminal on a 1268 # terminal that was bound. Scroll until a row appears, or until the 1269 # screen stops changing. 1270 for _ in range(8): 1271 if screen.find(r"^(?:Taler POS|Username|Merchant portal URL):"): 1272 break 1273 before = screen.texts() 1274 self.dev.scroll(down=True, screen=screen) 1275 time.sleep(1) 1276 screen = self._stable_dump() 1277 if screen.texts() == before: 1278 break 1279 wanted = ("Taler POS", "Username", "Merchant portal URL") 1280 rows: dict[str, str] = {} 1281 labels = [n for n in screen.nodes if n.label.strip()] 1282 for node in labels: 1283 text = node.label.strip() 1284 for key in wanted: 1285 if text.startswith(f"{key}:"): 1286 rows[key] = text[len(key) + 1:].strip() 1287 for key in wanted: 1288 if key in rows: 1289 continue 1290 anchor = next((n for n in labels if n.label.strip() == key), None) 1291 if anchor is None: 1292 continue 1293 same_row = [n for n in labels 1294 if n is not anchor 1295 and abs(n.center[1] - anchor.center[1]) < 60 1296 and n.bounds[0] > anchor.bounds[0]] 1297 if same_row: 1298 rows[key] = min(same_row, key=lambda n: n.bounds[0]).label.strip() 1299 return rows 1300 1301 # -- payment options and the mixed-payment checkout ------------------- 1302 # 1303 # Turning on a second payment option changes what Charge does: instead of 1304 # going straight to the Taler QR code, the terminal opens a checkout that 1305 # collects cash or card first and leaves Taler to pay whatever is still 1306 # open. Everything below drives that, and none of it is reachable while 1307 # Taler is the only option -- which is the terminal's own default, so a 1308 # scenario has to turn one on before it can test any of it. 1309 1310 def goto_payment_options(self, timeout: int = 45) -> Screen: 1311 """Settings -> Manage payment options.""" 1312 screen = self.goto("settings") 1313 if screen.find(MARK_PAYMENT_OPTIONS): 1314 return screen 1315 # "Payment options" is also the Settings card's own heading, which is 1316 # not clickable; the button under it says "Manage payment options" and 1317 # on a phone it is below the fold, so the tap has to scroll to it. 1318 self.tap_button(r"^Manage payment options$") 1319 return self.dev.wait_for(MARK_PAYMENT_OPTIONS, timeout=timeout) 1320 1321 def payment_option_rows(self, screen: Optional[Screen] = None 1322 ) -> dict[str, bool]: 1323 """Each payment option and whether its switch is on. 1324 1325 The switch is a separate, unlabelled node beside the option's name -- 1326 Compose puts the name in the card and the `Switch` next to it -- so it 1327 is found by row rather than by label, the same way the About block is 1328 read. 1329 """ 1330 screen = screen or self._stable_dump() 1331 names = [n for n in screen.labelled() 1332 if n.label.strip() in ("GNU Taler", "Cash", "SumUp")] 1333 switches = [n for n in screen.nodes if n.checkable] 1334 out: dict[str, bool] = {} 1335 for name in names: 1336 same_row = [sw for sw in switches 1337 if abs(sw.center[1] - name.center[1]) < 120] 1338 if same_row: 1339 nearest = min(same_row, 1340 key=lambda sw: abs(sw.center[1] - name.center[1])) 1341 out[name.label.strip()] = nearest.checked 1342 return out 1343 1344 def set_payment_option(self, name: str, on: bool = True, 1345 timeout: int = 20) -> dict[str, bool]: 1346 """Turn a payment option on or off, and confirm it took. 1347 1348 An option with an activation notice (SumUp has one) puts a dialog in 1349 the way, so the confirm button is pressed if it appears. Tapping the 1350 card itself opens the option's own screen instead of toggling it, so 1351 the switch is what gets tapped. 1352 """ 1353 screen = self.goto_payment_options() 1354 rows = self.payment_option_rows(screen) 1355 if name not in rows: 1356 raise PosError(f"no payment option named {name!r}; " 1357 f"options: {sorted(rows)}") 1358 if rows[name] == on: 1359 return rows 1360 anchor = next(n for n in screen.labelled() if n.label.strip() == name) 1361 switches = [n for n in screen.nodes if n.checkable 1362 and abs(n.center[1] - anchor.center[1]) < 120] 1363 if not switches: 1364 raise PosError(f"no switch beside {name!r}") 1365 self.dev.tap_node(min(switches, 1366 key=lambda sw: abs(sw.center[1] - anchor.center[1])), 1367 screen) 1368 time.sleep(1.0) 1369 # "Before you turn this on" -- only some options have it. 1370 notice = self._stable_dump() 1371 if notice.find(r"^Turn on$"): 1372 self.tap_button(r"^Turn on$") 1373 time.sleep(1.0) 1374 deadline = time.monotonic() + timeout 1375 while time.monotonic() < deadline: 1376 rows = self.payment_option_rows() 1377 if rows.get(name) == on: 1378 return rows 1379 time.sleep(1.0) 1380 raise PosError(f"{name!r} is still {rows.get(name)!r} after asking for {on}") 1381 1382 def charge_to_checkout(self, timeout: int = 90) -> Screen: 1383 """Press Charge and wait for the checkout rather than the QR code.""" 1384 self.tap_button(r"Create order \(charge amount\)|^Charge$") 1385 return self.dev.wait_for(MARK_CHECKOUT, timeout=timeout) 1386 1387 def bill_to_checkout(self, timeout: int = 90) -> Screen: 1388 """Complete an inventory order into the checkout.""" 1389 self.tap_button(BILL_BUTTON) 1390 return self.dev.wait_for(MARK_CHECKOUT, timeout=timeout) 1391 1392 # "Total: X", "Paid: X", "To pay: X" on the compact layout; "Order total" 1393 # with the amount underneath, "Paid: X" and "Remaining: X" on the wide one. 1394 CHECKOUT_ROW = re.compile( 1395 r"^(Total|Paid|To pay|Remaining|Still to pay)\s*:\s*(.+)$", re.I) 1396 1397 def checkout_amounts(self, screen: Optional[Screen] = None 1398 ) -> dict[str, str]: 1399 """What the checkout says the order comes to, and what is left. 1400 1401 Returned as the terminal renders them -- symbol, grouping and all -- 1402 because the point of reading them is to compare the screen against the 1403 backend, and reformatting first would hide a formatting bug. 1404 """ 1405 screen = screen or self._stable_dump() 1406 out: dict[str, str] = {} 1407 for node in screen.labelled(): 1408 m = self.CHECKOUT_ROW.match(node.label.strip()) 1409 if m: 1410 key = m.group(1).lower() 1411 key = {"still to pay": "to pay", "remaining": "to pay"}.get(key, key) 1412 out.setdefault(key, m.group(2).strip()) 1413 # The compact layout writes the open amount as a "Remaining" heading 1414 # with the figure underneath rather than as "Remaining: X". 1415 if "to pay" not in out: 1416 heading = next((n for n in screen.labelled() 1417 if n.label.strip() in ("Remaining", "Still to pay")), 1418 None) 1419 if heading is not None: 1420 below = [n for n in screen.labelled() 1421 if n is not heading 1422 and abs(n.center[0] - heading.center[0]) < 260 1423 and n.bounds[1] >= heading.bounds[1] 1424 and self.AMOUNT_SHOWN.search(n.label.strip())] 1425 if below: 1426 out["to pay"] = min(below, 1427 key=lambda n: n.bounds[1]).label.strip() 1428 if "total" not in out: 1429 # The wide layout puts "Order total" on its own line with the 1430 # amount underneath, rather than as "Total: X". 1431 heading = next((n for n in screen.labelled() 1432 if n.label.strip() == "Order total"), None) 1433 if heading is not None: 1434 below = [n for n in screen.labelled() 1435 if n.bounds[1] >= heading.bounds[1] 1436 and self.AMOUNT_SHOWN.search(n.label.strip())] 1437 if below: 1438 nearest = min(below, key=lambda n: n.bounds[1]) 1439 out["total"] = nearest.label.strip() 1440 return out 1441 1442 def displayed_order_id(self, screen: Optional[Screen] = None 1443 ) -> Optional[str]: 1444 """The backend order id the terminal is showing, without its "#".""" 1445 screen = screen or self._stable_dump() 1446 for node in screen.labelled(): 1447 m = re.fullmatch(r"#(\S+)", node.label.strip()) 1448 if m: 1449 return m.group(1) 1450 return None 1451 1452 def checkout_tile(self, pattern: str, timeout: int = 30) -> Screen: 1453 """Tap one of the checkout's payment-method tiles.""" 1454 screen = self.dev.wait_for(MARK_CHECKOUT, timeout=timeout) 1455 self._scroll_into_view(pattern, screen) 1456 return self.tap_button(pattern) 1457 1458 def checkout_pad_digits(self, digits: str) -> Screen: 1459 """Press the checkout keypad's keys, in order. 1460 1461 The same till behaviour as the order keypad -- digits fill from the 1462 right and there is no separator key -- but a keypad of its own, in a 1463 full-screen dialog, so it cannot wait for the order screen's marker. 1464 """ 1465 screen = self._stable_dump() 1466 for char in digits: 1467 if char in "cC": 1468 self.tap_button(r"^Clear$") 1469 screen = self._stable_dump() 1470 continue 1471 if char in "<b": 1472 node = screen.find(r"^Backspace$") 1473 if node is None: 1474 raise PosError("no backspace key in the checkout keypad") 1475 self.dev.tap_node(node, screen) 1476 time.sleep(0.25) 1477 continue 1478 node = screen.find(rf"^{re.escape(char)}$") 1479 if node is None: 1480 raise PosError(f"no checkout keypad key for {char!r}; " 1481 f"keys: {sorted(set(screen.texts()))}") 1482 self.dev.tap_node(node, screen) 1483 time.sleep(0.25) 1484 return self._stable_dump() 1485 1486 def checkout_entry_amount(self, screen: Optional[Screen] = None 1487 ) -> Optional[str]: 1488 """The amount the checkout's keypad is showing. 1489 1490 The submit button spells it out -- "Record ク7.00 cash" -- which is the 1491 one place it appears unambiguously; the big display above the keypad is 1492 a bare number that the "Remaining to pay" line also matches. 1493 """ 1494 screen = screen or self._stable_dump() 1495 for node in screen.labelled(): 1496 m = re.match(r"^(?:Record|Charge)\s+(.+?)\s+(?:cash|on card)$", 1497 node.label.strip()) 1498 if m: 1499 return m.group(1).strip() 1500 return None 1501 1502 def record_cash(self, amount: str, verify: bool = True) -> Optional[Dialog]: 1503 """Take a cash payment of `amount` in the checkout. 1504 1505 Returns the "Give change" dialog if one opens, which is how a scenario 1506 reads what the terminal worked out the change to be. 1507 """ 1508 if not re.fullmatch(r"\d+(?:[.,]\d+)?", amount): 1509 raise ValueError(f"{amount!r} is not a plain decimal amount") 1510 self.checkout_tile(r"^Cash$") 1511 self.dev.wait_for(MARK_CHECKOUT_PAD, timeout=30) 1512 digits = amount.replace(".", "").replace(",", "").lstrip("0") or "0" 1513 screen = self.checkout_pad_digits(digits) 1514 if verify: 1515 shown = self.checkout_entry_amount(screen) 1516 if shown is None: 1517 raise PosError("the checkout keypad shows no amount; " 1518 f"screen: {screen.texts()}") 1519 # The submit label carries the currency symbol as well, so the 1520 # number is picked out of it before the two are compared. 1521 number = self.AMOUNT_SHOWN.search(shown) 1522 if number is None or _as_minor(number.group(0)) != _as_minor(amount): 1523 raise PosError(f"typing {digits!r} in the checkout keypad was " 1524 f"meant to give {amount} and gave {shown!r}") 1525 self.tap_button(r"^Record .* cash$") 1526 time.sleep(1.5) 1527 dialog = self.read_dialog() 1528 if dialog is not None and re.search(r"Give change|Hand .* back", str(dialog)): 1529 self.dismiss_dialog() 1530 return dialog 1531 return dialog 1532 1533 def checkout_finish_with_taler(self, timeout: int = 120) -> Screen: 1534 """Tap the Taler tile and wait for the payment screen.""" 1535 self.checkout_tile(r"^Charge with Taler$|^Charge remaining with Taler$" 1536 r"|^Complete payment$") 1537 return self.dev.wait_for(MARK_PAYMENT, timeout=timeout) 1538 1539 def checkout_cancel(self, confirm: bool = True) -> Screen: 1540 """Cancel the checkout, through the warning if money has been taken.""" 1541 screen = self._stable_dump() 1542 if screen.find(r"^About this checkout$"): 1543 self.tap_button(r"^About this checkout$") 1544 time.sleep(1.2) 1545 # Tapped straight at the node rather than through `tap_button`: 1546 # the dialog's buttons are inside a Compose AlertDialog, and 1547 # `tap_button` may press Back on the way (to put a keyboard away, 1548 # or to undo a scroll), which dismisses the dialog instead of 1549 # answering it -- reported as "vanished before the tap". 1550 screen = self.dev.wait_for(r"^Cancel payment anyway$", timeout=20) 1551 want = r"^Cancel payment anyway$" if confirm else r"^Close$" 1552 node = screen.find(want) 1553 if node is None: 1554 raise PosError(f"no {want!r} in the checkout's warning: " 1555 f"{screen.texts()}") 1556 self.dev.tap_node(node, screen) 1557 else: 1558 self.tap_button(r"^Cancel payment$") 1559 time.sleep(2.0) 1560 return self._stable_dump() 1561 1562 def bound_instance(self) -> tuple[Optional[str], Optional[str]]: 1563 """Which instance and merchant URL the terminal believes it is using.""" 1564 rows = self.about_rows() 1565 url = rows.get("Merchant portal URL", "") 1566 return rows.get("Username"), re.sub(r"\s*\([^)]*\)\s*$", "", url) or None 1567 1568 1569 def _as_minor(amount: str) -> int: 1570 """A displayed amount as an integer number of its smallest units.""" 1571 whole, _, frac = amount.replace(",", ".").partition(".") 1572 frac = (frac + "00")[:2] 1573 return int(whole or 0) * 100 + int(frac)