scenarios.py (14851B)
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 """Scripted flows that put the wallet into a deep, interesting state. 15 16 Random exploration from the launcher almost never reaches "has coins and has 17 paid for something"; these do it in a handful of steps, so exploration can 18 start from there instead. Each one drives the real UI and uses the host-side 19 APIs only for the steps a counterparty would perform. 20 """ 21 22 from __future__ import annotations 23 24 import os 25 import time 26 from typing import Callable 27 28 from cli import CliWallet 29 from device import Screen 30 from stack import Bank, Env, Merchant 31 from wallet import Wallet 32 33 # Each parallel worker gets its own bank customer, so two emulators running 34 # scenarios at the same time cannot spend each other's money. 35 WORKER = int(os.environ.get("SIM_WORKER", "0")) 36 WALLET_USER = (f"wallet{WORKER + 1}", f"walletpass{WORKER + 1}") 37 38 39 def tap_if(app: Wallet, pattern: str, timeout: int = 8) -> bool: 40 """Tap a label if it is there; unlike Device.tap_text, do not raise.""" 41 try: 42 app.dev.tap_text(pattern, timeout=timeout) 43 return True 44 except TimeoutError: 45 return False 46 47 48 def tap_lowest_button(app: Wallet, pattern: str, timeout: int = 60) -> bool: 49 """Tap the lowest *clickable* node whose label matches. 50 51 Several screens use one string for the heading and the submit button; the 52 heading comes first in the hierarchy and is not clickable, so a plain 53 tap_text hits nothing. Ctx.tap_button does this for scenarios; flows need 54 their own copy. 55 """ 56 import re as _re 57 rx = _re.compile(pattern, _re.I) 58 deadline = time.time() + timeout 59 while time.time() < deadline: 60 screen = app.dev.dump() 61 targets = [] 62 for node in screen.labelled(): 63 if not rx.search(node.label): 64 continue 65 target = screen.tap_target(node) 66 if target.clickable and target.enabled: 67 targets.append(target) 68 if targets: 69 app.dev.tap_node(max(targets, key=lambda n: n.bounds[1]), screen) 70 time.sleep(1.5) 71 return True 72 time.sleep(1.5) 73 return False 74 75 76 def accept_tos(app: Wallet, timeout: int = 20) -> bool: 77 """Get past the terms of service, if the exchange has any. 78 79 An exchange that serves /terms turns the withdrawal prompt's own button 80 into "Terms of Service", which opens the review screen; nothing else can 81 be done until the terms are accepted. An exchange without terms (the 82 shipped TERMS_DIR points into an empty test home) never shows this, so 83 every caller has to cope with both. 84 """ 85 # Two orders of events: the button is already there, or the screen says the 86 # terms are required and the button arrives with the next recomposition 87 # (which is what happens after switching to a different payment service). 88 deadline = time.time() + 10 89 while True: 90 screen = app.dev.dump() 91 if screen.find(r"(?i)^Terms of Service$") is not None: 92 break 93 if screen.find(r"(?i)terms of service before you can withdraw|" 94 r"must first accept") is None: 95 return False 96 if time.time() > deadline: 97 return False 98 time.sleep(1.5) 99 # Opening the review screen fetches the terms document, which on a loaded 100 # host takes longer than one tap's patience; and the accept button can sit 101 # below the fold. So: tap, look, scroll, and tap again rather than giving 102 # up on the first miss -- a flaky accept here fails the *setup* of whatever 103 # scenario asked for a funded wallet, which reads as that scenario being 104 # broken. 105 for attempt in range(3): 106 if not tap_if(app, r"(?i)^Terms of Service$", timeout=timeout): 107 break 108 time.sleep(2) 109 deadline = time.time() + timeout 110 while time.time() < deadline: 111 if app.dev.dump().find(r"(?i)^Accept Terms of Service$") is not None: 112 app.dev.tap_text(r"(?i)^Accept Terms of Service$", timeout=10) 113 time.sleep(2) 114 return True 115 app.dev.scroll(down=True) 116 time.sleep(1.5) 117 # Still on the prompt: go back up and try the button once more. 118 if app.dev.dump().find(r"(?i)^Terms of Service$") is None: 119 app.dev.back() 120 time.sleep(1.5) 121 return False 122 123 124 def pick_payment_service(app: Wallet, url: str) -> bool: 125 """Switch the withdrawal prompt to a particular payment service. 126 127 The prompt shows the chosen service as a row labelled with its URL, and 128 that row is `clickable` but **disabled** until the terms of service have 129 been accepted -- so this only works after accept_tos, and tapping it 130 earlier does nothing (or lands on a neighbour and leaves the screen). 131 """ 132 import re as _re 133 screen = app.dev.dump() 134 row = next((n for n in screen.labelled() 135 if _re.match(r"(?i)^https?://", n.label.strip())), None) 136 if row is None: 137 return False 138 target = screen.tap_target(row) 139 if not target.enabled: 140 return False 141 app.dev.tap_node(target, screen) 142 time.sleep(2) 143 # The picker lists every service that can serve this currency. 144 return tap_lowest_button(app, _re.escape(url.rstrip("/")), timeout=15) 145 146 147 def withdraw(app: Wallet, bank: Bank, amount: str = "EUR:10", timeout: int = 180, 148 pick_exchange: str | None = None) -> Screen: 149 """Bank-initiated withdrawal, all the way to a completed transaction. 150 151 The bank opens the operation, the wallet picks the exchange and confirms, 152 and the host plays the part of the human authorising it in the bank's own 153 UI. `pick_exchange` switches the service first, which is the only way to 154 get coins at a second exchange. 155 """ 156 op = bank.create_withdrawal(*WALLET_USER, amount) 157 app.handle_uri(op["taler_withdraw_uri"]) 158 accept_tos(app) 159 if pick_exchange and pick_payment_service(app, pick_exchange): 160 # A different service means its own terms. 161 accept_tos(app) 162 app.dev.tap_text(r"(?i)confirm withdrawal", timeout=60) 163 # The wallet has to have selected the exchange before the bank will let the 164 # operation be confirmed; confirming anyway answers "Cannot confirm an 165 # unselected withdrawal" (5130), which reads like a bank problem rather 166 # than a wallet that was still thinking. 167 deadline = time.monotonic() + 90 168 while True: 169 status = bank.withdrawal_status(op["withdrawal_id"])["status"] 170 if status == "selected": 171 break 172 if time.monotonic() > deadline: 173 raise TimeoutError( 174 f"the wallet did not select an exchange for {amount} within 90s " 175 f"(bank says {status!r}; screen: {app.dev.dump().texts()[:12]})") 176 time.sleep(2) 177 bank.confirm_withdrawal(*WALLET_USER, op["withdrawal_id"]) 178 deadline = time.monotonic() + timeout 179 while time.monotonic() < deadline: 180 screen = app.dev.dump() 181 if screen.find(r"(?i)completed successfully"): 182 return screen 183 time.sleep(3) 184 raise TimeoutError(f"withdrawal {op['withdrawal_id']} did not complete") 185 186 187 def pay(app: Wallet, merchant: Merchant, amount: str = "EUR:2", 188 summary: str = "Simulator order") -> dict: 189 """Create an order and pay it from the wallet's balance.""" 190 order = merchant.create_order(amount, summary=summary) 191 app.handle_uri(order["pay_uri"]) 192 # The button carries the amount, e.g. "Pay €2.00". 193 app.dev.tap_text(r"(?i)^pay\b|confirm payment", timeout=60) 194 deadline = time.monotonic() + 90 195 while time.monotonic() < deadline: 196 if merchant.order_status(order["order_id"], 197 order["token"]).get("order_status") == "paid": 198 return order 199 time.sleep(2) 200 raise TimeoutError(f"order {order['order_id']} was not paid") 201 202 203 def fund_wallet(app: Wallet, env: Env | None = None, amount: str = "EUR:10") -> Screen: 204 """Fresh profile in developer mode, with coins in it.""" 205 env = env or Env.load() 206 app.fresh_start(dev_mode=True) 207 screen = withdraw(app, Bank(env.bank), amount) 208 app.home() 209 return screen 210 211 212 def funded_and_paid(app: Wallet, env: Env | None = None) -> dict: 213 """The deepest cheap state: coins, one completed purchase, refundable.""" 214 env = env or Env.load() 215 fund_wallet(app, env) 216 order = pay(app, Merchant(env.merchant)) 217 app.home() 218 return order 219 220 221 def deposit_via_payto_link(app: Wallet, env: Env | None = None) -> Screen: 222 """Try to start a deposit from a payto link, which the wallet refuses. 223 224 `DepositManager.isSupportedPayToUri` accepts `payto://iban/...` and nothing 225 else, so the `payto://x-taler-bank/...` URI the simulator's bank hands out 226 answers "Not a valid Taler link" -- see 227 findings/payto-link-only-accepts-iban.md. 228 """ 229 env = env or Env.load() 230 payto = Bank(env.bank).payto(*WALLET_USER) 231 app.handle_uri(payto) 232 app.dev.wait_for(r"(?i)Not a valid Taler link|deposit|amount|send", timeout=60) 233 return app.dev.dump() 234 235 236 def deposit_to_bank(app: Wallet, env: Env | None = None, 237 digits: str = "100", 238 before_submit: Callable[[], None] | None = None) -> Screen: 239 """Deposit from the app to a bank account, through the UI. 240 241 Not through a payto link: the wallet refuses every target type but IBAN 242 (see `deposit_via_payto_link`), and the simulator's bank is x-taler-bank, 243 so the link path cannot deposit at all. The Deposit button can, and the 244 account is already known to the wallet from its withdrawals. 245 246 `digits` is typed as an amount field takes them, from the right: "100" is 247 1.00. 248 """ 249 env = env or Env.load() 250 app.home() 251 app.dev.tap_text(r"(?i)^Deposit$", timeout=30) 252 screen = app.dev.wait_for( 253 r"(?i)deposit to bank account|Manage bank accounts|x-taler-bank", 254 timeout=30) 255 account = screen.find(r"(?i)^wallet\d+$") or screen.find(r"(?i)x-taler-bank") 256 if account is not None: 257 app.dev.tap_node(account, screen) 258 time.sleep(2) 259 app.dev.wait_for(r"(?i)Amount to deposit|Make deposit", timeout=25) 260 fields = app.dev.dump().editable() 261 if fields: 262 app.dev.tap_node(fields[0]) 263 app.dev.type_text(digits) 264 time.sleep(1) 265 # The fees appear on their own once an amount is in; older builds had a 266 # "Check fees" button, so it is tapped when present and skipped otherwise. 267 tap_if(app, r"(?i)^Check fees$", timeout=6) 268 # A caller that wants the deposit to *stay* pending -- to reach the 269 # aborting state, say -- takes the network away here: against a healthy 270 # exchange the whole thing is over in under four seconds. 271 if before_submit is not None: 272 before_submit() 273 app.dev.tap_text(r"(?i)^Make deposit$|^Deposit$", timeout=20) 274 time.sleep(4) 275 return app.dev.dump() 276 277 278 # The peer wallet gets a bank customer of its own, so funding it never eats 279 # into the balance the app under test is spending. 280 PEER_USER = (f"peer{WORKER + 1}", f"peerpass{WORKER + 1}") 281 282 283 def fund_peer(peer: CliWallet, env: Env, amount: str = "EUR:5", 284 exchange: str | None = None) -> str: 285 """Give the CLI peer wallet coins, through the bank like any wallet. 286 287 `exchange` picks which one they come from, which is how the app ends up 288 holding a second currency scope: a peer payment is spent at the sender's 289 exchange. 290 """ 291 from stack import Bank 292 return peer.fund_via_bank(Bank(env.bank), PEER_USER, amount, 293 exchange or env.exchange) 294 295 296 def peer_receive(app: Wallet, env: Env | None = None, amount: str = "EUR:1", 297 peer: CliWallet | None = None, 298 exchange: str | None = None) -> Screen: 299 """The CLI wallet pushes money; the app accepts it. 300 301 `exchange` is where the peer's coins come from, and therefore which scope 302 the app ends up holding -- the cheapest way to give this wallet a balance 303 at a second exchange, since no withdrawal UI lets one be chosen. 304 """ 305 env = env or Env.load() 306 peer = peer or CliWallet() 307 exchange = exchange or env.exchange 308 if exchange != env.exchange: 309 peer.add_exchange(exchange) 310 fund_peer(peer, env, "EUR:5", exchange=exchange) 311 uri = peer.peer_send(amount, exchange) 312 app.handle_uri(uri) 313 # With terms the prompt's button is "Review terms of service" first, and 314 # the review screen has to be accepted before the payment can be. 315 if app.dev.wait_for(r"(?i)Review terms of service|Receive payment|accept", 316 timeout=60).find(r"(?i)Review terms of service") is not None: 317 app.dev.tap_text(r"(?i)Review terms of service", timeout=20) 318 time.sleep(2) 319 app.dev.tap_text(r"(?i)^Accept Terms of Service$", timeout=20) 320 time.sleep(3) 321 # "Receive payment" is both the screen's heading and its button, and 322 # tap_text takes the first match -- the heading, which is not clickable, so 323 # the payment was never accepted and the balance stayed at zero while the 324 # scenario reported success. Tap the lowest clickable match instead. 325 tap_lowest_button(app, r"(?i)^Receive payment$|accept|confirm") 326 return app.dev.dump() 327 328 329 def peer_pay_invoice(app: Wallet, env: Env | None = None, amount: str = "EUR:1", 330 peer: CliWallet | None = None) -> Screen: 331 """The CLI wallet invoices the app; the app pays it.""" 332 env = env or Env.load() 333 peer = peer or CliWallet() 334 peer.add_exchange(env.exchange) 335 uri = peer.peer_request(amount, exchange=env.exchange) 336 app.handle_uri(uri) 337 # Paying an invoice needs the exchange's terms accepted first, like any 338 # other first use of it. 339 if app.dev.wait_for(r"(?i)Review terms of service|^Pay\b|accept|confirm", 340 timeout=60).find(r"(?i)Review terms of service") is not None: 341 app.dev.tap_text(r"(?i)Review terms of service", timeout=20) 342 time.sleep(2) 343 app.dev.tap_text(r"(?i)^Accept Terms of Service$", timeout=20) 344 time.sleep(3) 345 app.dev.tap_text(r"(?i)^pay\b|accept|confirm", timeout=60) 346 return app.dev.dump()