let your agent control your phone
PHO-316: reserve a cloud phone from the CLI (cloud reserve, cloud reservations) (#206)
shawn panab16b37f61229
diff --git a/README.md b/README.mdindex 0da46f2..a4d8eab 100644--- a/README.md+++ b/README.md@@ -109,6 +109,17 @@ phone-harness cloud stop # ends the session; a saved Android is writThe same helpers drive a cloud phone: an Android over adb, an iPhone over HTTPS. `cloud start` takes a phone's name or id from `cloud ls`, or `ios` / `android`; with none it starts a temporary Android. `phone-harness cloud` lists every command.+No cloud iPhone on the account yet, or need more of them? Reserve them with a $20 per phone refundable deposit. The command prints a quote, which is the authoritative figure, and a Stripe Checkout link. You pay in your browser, and that payment is what holds your place in the queue, which is in the order deposits were paid; the CLI never pays for you.++```bash+phone-harness cloud reserve --type iphone --plan monthly --qty 2 \+ --use-case "Testing our app on real iPhones" --open+phone-harness cloud reservations # status, place in the queue, deposit, when it was paid+phone-harness cloud reservations cancel ID # leave the queue; the deposit still held goes back to the card that paid+```++`--type` is `iphone` or `iphone-esim`, and `--plan` is `monthly` or `annual`. Reservations are for iPhones only (with or without eSIM). Cloud Android emulators are on the $20 plan and are not reserved. The plan starts when a phone is handed over; the deposit comes off its first bill and is then no longer refundable. An account can have five unpaid reservations an hour, and cancelling one does not free a place.+## How it worksEvery phone sits behind the same helpers, so a script written for one runs on the others.diff --git a/SKILL.md b/SKILL.mdindex 9c30d12..9333bd9 100644--- a/SKILL.md+++ b/SKILL.md@@ -366,6 +366,68 @@ now"). Links expire within fifteen minutes and with the session; the filesare removed when the session ends. A link is a credential: do not paste oneinto notes or output.+## Reserving a cloud phone++An account gets a cloud iPhone, or more of them, by reserving them. A+reservation is a place in a queue, held by a $20 per phone refundable deposit.+The quote the command prints is authoritative: tell the user the amounts in+it. You can start a reservation. Only the user can pay for it.++```bash+phone-harness cloud reserve --type iphone --plan monthly --qty 2 \+ --use-case "Testing our listings app on real iPhones" # prints the quote and a Stripe Checkout link+phone-harness cloud reservations # id, type, plan, qty, status, position, deposit, paid+phone-harness cloud reservations ID # one in full; an unpaid one shows its link again+phone-harness cloud reservations cancel ID # says what it would refund; --yes does it+```++- **Signed in first.** These commands need `phone-harness cloud login`, or+ `PHONE_HARNESS_API_KEY`. A user with no account, or who will not sign in,+ can reserve on the website instead: phone-harness.com/get-a-phone.+- **Which phones.** Reservations are for iPhones only (with or without+ eSIM). Cloud Android emulators are on the $20 plan and are not reserved.+- **Ask first, and send the user's own answers.** `--type` is `iphone`, or+ `iphone-esim` for one with an eSIM (a real number). `--plan` is `monthly` or+ `annual`. `--qty` is 1 to 50, default 1. `--use-case` is what they want the+ phones for, in their words. Do not make up a use case, a name or a number.+- **You never pay.** `cloud reserve` prints a Stripe Checkout link. Give it to+ the user, or pass `--open` to open it in their browser, and stop there: a+ person types the card. Do not open the link on a phone you are driving, and+ do not fill in a payment page.+- **Nothing is held until the deposit is paid.** A new reservation is+ `pending_payment`. When Stripe confirms the payment it becomes `queued` and+ has a `position`. Do not tell the user a phone is reserved until+ `cloud reservations` says `queued`. The link stops working after about a+ day; reserve again for a new one.+- **Queue order is paid time.** Places go in the order the deposits were+ paid. Reserving again, or paying more, does not move one up.+- **Read the quote as it is printed.** It is the deposit due now, refundable+ in full while the reservation is queued, and the plan's first billing+ period: one phone at the intro price when this customer has not had it+ yet, the rest at the standard price. The plan starts when a phone is+ handed over, and the deposit comes off that first bill. The amounts come+ from the service with each quote; do not quote them from memory.+- **The name is optional.** The reservation carries the account's name when+ it has one. `--first-name` and `--last-name` put another name on it; pass+ them only when the user gives you one.+- **Cancel only when the user asks.** `cloud reservations cancel ID` with no+ `--yes` prints what would be given up and refunded, and changes nothing.+ Show the user that, then run it again with `--yes`. The refund is+ automatic, to the card that paid: there is nothing to request. A queued+ reservation is refunded in full; one that is part handed over refunds only+ the phones still waiting. Once every phone has been handed over the cancel+ is refused (`already_granted`): that deposit became a credit on the first+ bill and is no longer refundable.+- **The website has no list.** `cloud reservations` is the list. The website+ shows one reservation's status page, from its link.+- **Retrying.** A `cloud reserve` that failed part way prints an+ `--idempotency-key`. Run the same command again with it to continue that+ reservation, not start a second one.+- **Five unpaid reservations an hour for one account.** Cancelling one does+ not free a place; paying for one does. So do not reserve to "see the price"+ and cancel: reserve when the user means it.+- `--json` on any of these prints the API's own answer.+## AndroidThe phone is reached over adb - a USB phone if plugged in, else the paireddiff --git a/install.md b/install.mdindex bd78bd4..48c5213 100644--- a/install.md+++ b/install.md@@ -86,7 +86,12 @@ That reaches the default phone. If it fails, use the sections below.or a number of minutes). New accounts get $5 of credit (100 Android minutes).A cloud Android emulator bills 5¢ a minute from that credit. A cloud iPhone isa real phone on a flat subscription, from $80 a month: it does not bill by the- minute.+ minute. An account that has none yet reserves one with `phone-harness cloud+ reserve`, for a $20 per phone refundable deposit: it prints a quote, which+ is authoritative, and a link where the user pays+ ([setup/cloud.md](https://github.com/phone-harness/phone-harness/blob/main/setup/cloud.md)).+ Reservations are for iPhones only (with or without eSIM). Cloud Android+ emulators are on the $20 plan and are not reserved.No uv? `pip install phone-harness` works too. Upgrade that install with`pip install -U phone-harness` (what `phone-harness update` prints for it).diff --git a/onboarding.md b/onboarding.mdindex 35657ba..27f8013 100644--- a/onboarding.md+++ b/onboarding.md@@ -91,6 +91,14 @@ in the summary and move on. If yes:stop`. Keep it to a few minutes: a cloud Android bills by the minute and thecredit is theirs. (A cloud iPhone is a flat subscription: it does not bill bythe minute.)+- A user who wants a cloud iPhone and has none on the account (`phone-harness+ cloud ls` lists no iOS phone) reserves one: ask whether it should have an+ eSIM, which plan, how many, and what it is for, then `phone-harness cloud+ reserve ...`. Reserving takes a $20 per phone refundable deposit. The+ command prints a quote, which is authoritative, and a Stripe Checkout link.+ Hand them the link and stop: paying is theirs, like signing up.+ Reservations are for iPhones only (with or without eSIM). Cloud Android+ emulators are on the $20 plan and are not reserved.## Rulesdiff --git a/setup/api.md b/setup/api.mdindex 3dafdee..b4ac5b0 100644--- a/setup/api.md+++ b/setup/api.md@@ -34,6 +34,26 @@ curl -s -H "$C" -H 'Content-Type: application/json' \-d '{"op":"nav.home","kw":{}}' $CONTROL_URL/op # Home Screen```+Reserve an iPhone the account does not have yet, with a $20 per phone refundable+deposit. Reservations are for iPhones only (with or without eSIM). Cloud+Android emulators are on the $20 plan and are not reserved. The answer+carries `quote`, which is authoritative, and+`checkout_url`, a Stripe Checkout page where a person pays that deposit.+Nothing is reserved until it is paid (`status` goes from `pending_payment` to+`queued`). Never pay it for the user. An account can have five unpaid+reservations an hour, and cancelling one does not free a place.+`first_name` and `last_name` may be added to put a name other than the+account's on it.++```bash+curl -s -H "$AUTH" -H 'Content-Type: application/json' -H "Idempotency-Key: $(uuidgen)" \+ -d '{"phone_type":"iphone","plan":"monthly","quantity":1,"use_case":"What it is for"}' \+ $API/reservations # phone_type: iphone | iphone_esim+curl -s -H "$AUTH" $API/reservations # the account's reservations+curl -s -H "$AUTH" $API/reservations/ID # one: status, position, deposit+curl -s -H "$AUTH" -X POST $API/reservations/ID/cancel # leave the queue; refunds what is held+```+`GET /me` lists each phone's `id` under `available`. Each `/op` answers `{"result": ...}`. A cloud Android is reached over adbinstead (`POST /sessions/SID/adb` returns host, port and unlock code), so itneeds adb and the CLI is the easier path.diff --git a/setup/cloud.md b/setup/cloud.mdindex 0a5d8c4..f858130 100644--- a/setup/cloud.md+++ b/setup/cloud.md@@ -46,3 +46,41 @@ billed annually ($768 or $960 a year). It does not bill by the minute, so itcan stay running.A cloud iPhone is a separate phone from the user's own, with its own appsand logins; if an app asks for an Apple ID or any sign-in, ask the user.++## Reserve a phone++An account with no cloud iPhone yet, or one that needs more of them, reserves+them:++```bash+phone-harness cloud reserve --type iphone --plan monthly --qty 2 \+ --use-case "What the phones are for"+phone-harness cloud reservations # status and place in the queue+phone-harness cloud reservations cancel ID # leave the queue; the deposit is refunded+```++`--type` is `iphone` or `iphone-esim`; `--plan` is `monthly` or+`annual`; `--qty` is 1 to 50. Reserving takes a $20 per phone refundable+deposit. The command prints a quote, which is authoritative, and a Stripe+Checkout link. The user opens the link and pays (`--open` opens it for them).+That payment is what holds a place in the queue: until it is made, nothing is+reserved. The plan starts when a phone is handed over, and the deposit comes+off its first bill. The reservation carries the account's name;+`--first-name` and `--last-name` put another one on it.++- Reservations are for iPhones only (with or without eSIM). Cloud Android+ emulators are on the $20 plan and are not reserved.+- These commands need a signed-in account (`cloud login`, or+ `PHONE_HARNESS_API_KEY`). Without one, reserve at phone-harness.com/get-a-phone.+- The queue is in the order deposits were paid. Nothing moves a place up.+- Cancelling refunds the deposit still held automatically, to the card that+ paid; a reservation that is part handed over refunds only the phones still+ waiting, and a phone that was handed over has had its deposit credited to+ its first bill.+- The website has no list of reservations: `cloud reservations` is the list,+ and the website shows one reservation's status page from its link.+- An account can have five unpaid reservations an hour. Cancelling one does not+ free a place; paying for one does.++Never pay, or fill in a payment page, for the user. Cancel a reservation only+when they ask.diff --git a/src/phone_harness/cloud.py b/src/phone_harness/cloud.pyindex 8493520..2c6fac4 100644--- a/src/phone_harness/cloud.py+++ b/src/phone_harness/cloud.py@@ -22,6 +22,7 @@ import argparseimport jsonimport mathimport os+import reimport shutilimport sysimport time@@ -1751,6 +1752,514 @@ def _history(args):return 0+# --- reservations ------------------------------------------------------------+#+# Asking for an iPhone the account does not have yet. `cloud reserve` sends+# what is wanted and gets back a quote and a Stripe Checkout link for a+# refundable deposit. A person pays that in a browser: this CLI holds no card+# and never pays. Until the deposit is paid the reservation holds no place in+# the queue, so nothing here says "reserved" before the API says `queued`.+#+# Every amount printed about a reservation is one the API sent. The one figure+# written in this file is in IPHONES_ONLY, and is not a reservation's.++# What --type takes, and the API's word for it. Only iPhones are reserved.+RESERVE_TYPES = {"iphone": "iphone", "iphone-esim": "iphone_esim", "iphone_esim": "iphone_esim"}+# What someone who asks to reserve an Android is told. The docs and the MCP+# server say it in the same words; tests/test_pricing_copy.py holds the docs+# to them.+IPHONES_ONLY = ("Reservations are for iPhones only (with or without eSIM). "+ "Cloud Android emulators are on the $20 plan and are not reserved.")+RESERVE_PLANS = ("monthly", "annual")+RESERVE_MAX_QUANTITY = 50 # the API's limit for one reservation+RESERVE_MAX_USE_CASE = 2000 # and for the free text+RESERVE_TIMEOUT = 75 # the API talks to Stripe before it answers+# The only place the API sends anyone to pay.+CHECKOUT_HOST = "checkout.stripe.com"+_RESERVATION_ID = re.compile(r"rsv_[a-f0-9]{24}")+# What the API says of an id that names none of the account's reservations. Any+# other 404 may be an API with no reservation routes; see _reservations_live.+_NO_SUCH_RESERVATION = "No such reservation"+_IDEMPOTENCY_KEY = re.compile(r"[A-Za-z0-9_-]{16,128}")+# The API's phone types as they are shown. One these do not name (a+# reservation from when another phone was offered) shows as the API's own+# word, and can be cancelled like any other.+_TYPE_WORDS = {"iphone": "iphone", "iphone_esim": "iphone-esim"}+_TYPE_LABELS = {"iphone": "iPhone", "iphone_esim": "iPhone with eSIM"}+_TIER_WORDS = {"intro": "intro price, once per customer", "standard": "standard price"}++RESERVE_USAGE = (+ "Usage: phone-harness cloud reserve --type iphone|iphone-esim --plan monthly|annual\n"+ " [--qty N] --use-case TEXT [--first-name NAME] [--last-name NAME]\n"+ " [--open] [--json] [--idempotency-key KEY]")+RESERVATIONS_USAGE = (+ "Usage: phone-harness cloud reservations [ID] [--json]\n"+ " phone-harness cloud reservations cancel ID [--yes] [--json]")+++def _amount(cents, currency="usd"):+ """Integer cents as money. Dollars get the sign; any other currency its code."""+ if isinstance(cents, bool) or not isinstance(cents, (int, float)):+ return "?"+ if str(currency or "usd").lower() == "usd":+ return f"${cents / 100:,.2f}"+ return f"{cents / 100:,.2f} {str(currency).upper()}"+++def _type_word(phone_type):+ """The API's phone type, as --type spells it."""+ return _TYPE_WORDS.get(phone_type, str(phone_type or "-"))+++def _phones_words(reservation):+ """'3 x iPhone with eSIM, monthly'."""+ kind = reservation.get("phone_type")+ return (f"{reservation.get('quantity', '?')} x {_TYPE_LABELS.get(kind, kind or 'phone')}, "+ f"{reservation.get('plan') or '?'}")+++def _in(ts):+ """How far off a time is: '45 min', '23 hours', '3 days'; 'expired' once past."""+ try:+ left = float(ts) - time.time()+ except (TypeError, ValueError):+ return "?"+ if left <= 0:+ return "expired"+ if left < 90 * 60:+ return f"{max(1, math.ceil(left / 60))} min"+ if left < 48 * 3600:+ return f"{round(left / 3600)} hours"+ return f"{round(left / 86400)} days"+++def _split_equals(args, names):+ """`--use-case=text` as the two words `--use-case text`, for these options."""+ out = []+ for word in args:+ name, eq, value = word.partition("=")+ out.extend([name, value] if eq and name in names else [word])+ return out+++def _checkout_url(reservation):+ """The reservation's payment link, or None when it is not Stripe Checkout.++ Someone is about to type a card number into this page. The API only ever+ sends people to Stripe's own Checkout host, so a link anywhere else is+ never printed as the place to pay and never opened."""+ url = reservation.get("checkout_url")+ if not isinstance(url, str) or any(ch <= " " or ch == "\x7f" for ch in url):+ return None+ try:+ parts = urllib.parse.urlsplit(url)+ host, user = parts.hostname, parts.username or parts.password+ except ValueError:+ return None+ if parts.scheme != "https" or host != CHECKOUT_HOST or user:+ return None+ return url+++def _open_link(url):+ """Open a link the user asked for with --open. Not `_open_browser`: that is+ `cloud start` showing a live view nobody asked for, which `cloud.watch` turns off."""+ try:+ return bool(webbrowser.open(url))+ except Exception:+ return False+++def _quote_rows(reservation):+ """(label, text) rows for the quote the API stored with a reservation: the+ deposit due now, then the plan's first billing period one price at a time.+ A phone with no price yet has a deposit and says the price comes later."""+ quote = reservation.get("quote") or {}+ currency = quote.get("currency") or "usd"+ deposit = quote.get("deposit") or {}+ period = "first " + {"month": "month", "year": "year"}.get(quote.get("interval"), "period")+ rows = []+ total = deposit.get("total_cents")+ if total is not None:+ per, phones = deposit.get("per_phone_cents"), deposit.get("phones")+ each = f" ({phones} x {_amount(per, currency)})" if per is not None and phones else ""+ back = ", refundable in full while queued" if deposit.get("refundable") else ""+ rows.append(("deposit", f"{_amount(total, currency)} due now{each}{back}"))+ lines = quote.get("lines") or []+ if not quote.get("priced") or not lines:+ rows.append((period, "price confirmed before handover"))+ return rows+ for i, line in enumerate(lines):+ tier = line.get("tier")+ price = (f"{line.get('quantity')} x {_amount(line.get('unit_cents'), currency)} "+ f"{_TIER_WORDS.get(tier, tier or 'price')}")+ rows.append((period if i == 0 else "", price))+ first, later = quote.get("first_period_cents"), quote.get("due_at_handover_cents")+ if first is not None:+ after = f"; {_amount(later, currency)} due at handover, after the deposit" if later is not None else ""+ rows.append(("", f"{_amount(first, currency)} in all{after}"))+ return rows+++def _deposit_words(reservation):+ """A reservation's deposit in a few words: what is due, held, or gone back."""+ deposit = reservation.get("deposit") or {}+ currency = deposit.get("currency") or "usd"+ status = reservation.get("status")+ if status == "pending_payment":+ due = ((reservation.get("quote") or {}).get("deposit") or {}).get("total_cents")+ return f"{_amount(due, currency)} due" if due is not None else "due"+ paid, held = deposit.get("paid_cents") or 0, deposit.get("refundable_cents") or 0+ credited, refunded = deposit.get("credited_cents") or 0, deposit.get("refunded_cents") or 0+ if not paid:+ return "-" # given up before anything was charged+ if status == "cancelling":+ return f"{_amount(held, currency)} refund pending"+ words = []+ if status == "queued":+ words.append(f"{_amount(paid, currency)} paid")+ if held != paid:+ words.append(f"{_amount(held, currency)} refundable")+ else: # no longer waiting: where the money went+ if credited:+ words.append(f"{_amount(credited, currency)} credited")+ if refunded:+ words.append(f"{_amount(refunded, currency)} refunded")+ return ", ".join(words) or f"{_amount(paid, currency)} paid"+++def _format_reservations(rows):+ """Text table for `cloud reservations`, sized to its cells like `cloud ls`."""+ header = ["ID", "TYPE", "PLAN", "QTY", "STATUS", "POSITION", "DEPOSIT", "PAID"]+ body = []+ for r in rows:+ body.append([+ str(r.get("reservation_id") or "-"),+ _type_word(r.get("phone_type")),+ str(r.get("plan") or "-"),+ str(r.get("quantity") if r.get("quantity") is not None else "-"),+ str(r.get("status") or "-"),+ str(r["position"]) if r.get("position") is not None else "-",+ _deposit_words(r),+ _ago(r["paid_at"]) if r.get("paid_at") else "-",+ ])+ widths = [max(len(header[i]), *(len(cells[i]) for cells in body)) for i in range(len(header))]++ def render(cells):+ padded = [cells[i].ljust(widths[i]) for i in range(len(cells) - 1)]+ padded.append(cells[-1])+ return " ".join(padded).rstrip()++ return "\n".join([render(header), *(render(cells) for cells in body)])+++def _print_rows(rows):+ for label, text in rows:+ print(f" {label:<12} {text}".rstrip())+++def _pay_rows(reservation):+ """Where to pay an unpaid reservation's deposit, and until when."""+ url = _checkout_url(reservation)+ if not url:+ missing = ("no payment link yet; `phone-harness cloud reservations "+ f"{reservation.get('reservation_id')}` shows it once there is one")+ if reservation.get("checkout_url"):+ missing = ("the payment link the API sent is not a Stripe Checkout page "+ f"(https://{CHECKOUT_HOST}); it is not shown")+ return [("pay", missing)]+ rows = [("pay", url)]+ if reservation.get("expires_at"):+ left = _in(reservation["expires_at"])+ # By this machine's clock, which may be wrong: say so, and leave the link in view.+ rows.append(("", "the link has expired; if it no longer opens, reserve again"+ if left == "expired" else f"the link works for another {left}"))+ return rows+++def _print_reservation(reservation):+ """One reservation in full: where it stands, its deposit, and its quote."""+ rid = reservation.get("reservation_id")+ status = reservation.get("status")+ rows = [("reservation", str(rid)), ("status", str(status))]+ if reservation.get("detail"):+ rows.append(("", str(reservation["detail"])))+ rows.append(("phones", _phones_words(reservation)))+ if reservation.get("position") is not None:+ rows.append(("position", f"{reservation['position']} in the queue"))+ if reservation.get("granted"):+ handed = f"{reservation['granted']} of {reservation.get('quantity')}"+ if reservation.get("queued"):+ handed += f"; {reservation['queued']} still waiting"+ if reservation.get("ended"):+ handed += f"; the plan has ended for {reservation['ended']}"+ rows.append(("handed over", handed))+ if status == "pending_payment":+ rows += _quote_rows(reservation) + _pay_rows(reservation)+ else:+ rows.append(("deposit", _deposit_words(reservation)))+ if reservation.get("paid_at"):+ rows.append(("paid", _ago(reservation["paid_at"])))+ if status == "queued": # what the plan will cost once a phone is handed over+ rows += [row for row in _quote_rows(reservation) if row[0] != "deposit"]+ _print_rows(rows)+ if reservation.get("can_cancel"):+ print(term.note(f" cancel phone-harness cloud reservations cancel {rid}"))+++def _explain_reservation(e, rid=None, retry=None):+ """A CloudError from the reservation routes, as what to do next.++ The API's `error` is a sentence written for a customer and is shown as it+ is; its `code` decides what is added. `retry` is the command that safely+ repeats a request Stripe did not finish. A 403 here is never the "not+ enabled for phones yet" that `_explain` makes of one."""+ if e.status == 401 or e.code == "account_blocked":+ return _explain(e)+ said = str(e)+ if e.status == 404 and rid and (said == _NO_SUCH_RESERVATION or _reservations_live()):+ return f"No reservation {rid} on this account. `phone-harness cloud reservations` lists them."+ if e.status == 404:+ # The route itself is missing: an API from before reservations.+ return (f"{_target('API')} does not take reservations yet, so a phone cannot be reserved, "+ "listed or cancelled through it. Nothing was changed.")+ if e.code == "plan_unavailable":+ return f"{said} Choose another --type or --plan."+ if e.code == "idempotency_conflict":+ return ("That --idempotency-key was already used for a different request. Leave it out to "+ "start a new reservation, or repeat the options it was first used with.")+ if e.code == "rate_limited":+ return (f"{said} Cancelling one does not free a place; paying for one does. "+ "`phone-harness cloud reservations` lists the unfinished ones.")+ if e.code == "payments_unavailable":+ return (f"{said} Nothing {'changed' if rid else 'was charged'}."+ + (f" To retry safely, {retry}." if retry else ""))+ if e.code == "refund_unconfirmed":+ return (f"{said} Asking again never refunds twice."+ + (f" To retry the refund, {retry}." if retry else ""))+ if e.code in ("already_granted", "grant_in_progress"):+ return f"Not cancelled. {said}"+ if e.status in (400, 403, 409, 429):+ return said+ return f"{said} (HTTP {e.status})"+++def _reservations_live():+ """Whether this API has reservation routes at all.++ A 404 for one reservation does not say. An API from before reservations+ answers 404 for every path under /reservations, and "no reservation of+ yours has that id" would be the wrong thing to tell someone then. The+ list is the one route with no id in it, so it is asked once."""+ try:+ _api("GET", "/reservations")+ except CloudError as e:+ return e.status != 404+ except OSError:+ pass # cannot tell; the first answer stands+ return True+++def _reservation_api(method, path, rid=None, **kw):+ """`_api`, with an HTTP error explained as a reservation error."""+ try:+ return _api(method, path, **kw)+ except CloudError as e:+ sys.exit(_explain_reservation(e, rid=rid))+++def _listed():+ """The account's reservations as the API lists them, newest first."""+ found = _reservation_api("GET", "/reservations")+ rows = found.get("reservations") if isinstance(found, dict) else found+ return [row for row in rows or [] if isinstance(row, dict)]+++def _reserve(args):+ args = _split_equals(list(args), ("--type", "--plan", "--qty", "--quantity", "--use-case",+ "--first-name", "--last-name", "--idempotency-key"))+ kind = _option(args, "--type")+ plan = _option(args, "--plan")+ qty = _option(args, "--qty", "--quantity")+ use_case = _option(args, "--use-case")+ first, last = _option(args, "--first-name"), _option(args, "--last-name")+ key = _option(args, "--idempotency-key")+ as_json, open_it = _flag(args, "--json"), _flag(args, "--open")+ if args:+ sys.exit(RESERVE_USAGE)+ if kind is not None and kind.lower().startswith("android"):+ sys.exit(f"{IPHONES_ONLY}\n{RESERVE_USAGE}")+ if kind not in RESERVE_TYPES:+ sys.exit(f"--type must be iphone or iphone-esim, not {kind!r}.\n{RESERVE_USAGE}"+ if kind is not None else f"--type is required.\n{RESERVE_USAGE}")+ if plan not in RESERVE_PLANS:+ sys.exit(f"--plan must be monthly or annual, not {plan!r}.\n{RESERVE_USAGE}"+ if plan is not None else f"--plan is required.\n{RESERVE_USAGE}")+ quantity = 1 if qty is None else _int(qty, "--qty")+ if not 1 <= quantity <= RESERVE_MAX_QUANTITY:+ sys.exit(f"--qty must be between 1 and {RESERVE_MAX_QUANTITY}, not {quantity}.")+ use_case = (use_case or "").strip()+ if not use_case:+ sys.exit("--use-case is required: say in a sentence what the phone is for.")+ if len(use_case) > RESERVE_MAX_USE_CASE:+ sys.exit(f"--use-case is {len(use_case)} characters; the most is {RESERVE_MAX_USE_CASE}.")+ if key is not None and not _IDEMPOTENCY_KEY.fullmatch(key):+ sys.exit("--idempotency-key must be 16 to 128 letters, digits, underscores or hyphens.")++ body = {"phone_type": RESERVE_TYPES[kind], "plan": plan, "quantity": quantity, "use_case": use_case}+ for field, value in (("first_name", first), ("last_name", last)):+ if value is not None and value.strip():+ body[field] = value.strip()+ key = key or uuid.uuid4().hex+ headers = {"Idempotency-Key": key}+ again = f"run the same command again with `--idempotency-key {key}`"+ try:+ try:+ made = _api("POST", "/reservations", body, headers=headers, timeout=RESERVE_TIMEOUT)+ except OSError:+ # The answer was lost, which does not say the request was. The same+ # key and body is the same reservation, never a second one.+ made = _api("POST", "/reservations", body, headers=headers, timeout=RESERVE_TIMEOUT)+ except CloudError as e:+ sys.exit(_explain_reservation(e, retry=again))+ except OSError as e:+ sys.exit(f"Could not reach {_target('API')}: {e}\nThe request may still have arrived. "+ f"To continue it instead of starting a second reservation, {again}.")++ if not isinstance(made, dict) or not made.get("reservation_id"):+ sys.exit(f"{_target('API')} answered with something that is not a reservation. "+ f"To find out whether one was started, {again}.")+ unpaid = made.get("status") == "pending_payment"+ url = _checkout_url(made)+ rid = made["reservation_id"]+ if as_json:+ print(json.dumps(made, indent=2))+ elif not unpaid:+ # A key that was used before answers with what that reservation is now.+ print(f"Reservation {rid} already exists for this key; no new one was started.")+ _print_reservation(made)+ else:+ print(f"{term.mark()} Reservation {rid} started: {_phones_words(made)}.")+ print(" It holds no place in the queue until the deposit is paid.")+ _print_rows(_quote_rows(made) + _pay_rows(made))+ # Opened last, so the link is already on screen whatever the browser does.+ if open_it and url and unpaid:+ opened = _open_link(url)+ if not as_json:+ _print_rows([("", "opened in your browser" if opened else+ "could not open a browser here; open the link yourself")])+ if as_json or not unpaid:+ return 0+ print(term.note(f" status phone-harness cloud reservations {rid}"))+ return 0 if url else 1+++def _find_reservation(given):+ """One of the account's reservations, by its id or a unique prefix of it."""+ if _RESERVATION_ID.fullmatch(given):+ return _reservation_api("GET", f"/reservations/{given}", rid=given)+ hits = [r for r in _listed() if given and str(r.get("reservation_id") or "").startswith(given)]+ if len(hits) != 1:+ sys.exit(f"{given!r} matches {len(hits)} reservations"+ + (f": {', '.join(str(r['reservation_id']) for r in hits)}" if hits+ else ". `phone-harness cloud reservations` lists them."))+ return hits[0]+++def _cancel_words(reservation):+ """What cancelling this reservation gives up and gives back, before asking."""+ deposit = reservation.get("deposit") or {}+ back = _amount(deposit.get("refundable_cents") or 0, deposit.get("currency") or "usd")+ lead = f"Reservation {reservation.get('reservation_id')}: {_phones_words(reservation)}"+ if reservation.get("status") == "pending_payment":+ return (f"{lead}, deposit not paid.\nNothing was charged, so nothing is refunded. "+ "Cancelling closes its payment link.")+ place = (f", position {reservation['position']} in the queue"+ if reservation.get("position") is not None else "")+ if reservation.get("granted"):+ return (f"{lead}{place}.\nCancelling gives up the {reservation.get('queued') or 0} still "+ f"waiting and refunds {back} to the card that paid. What was already handed over "+ f"({reservation['granted']} of {reservation.get('quantity')}) is not affected.")+ return f"{lead}{place}.\nCancelling gives up that place and refunds {back} to the card that paid."+++def _cancel_reservation(given, yes, as_json):+ before = _find_reservation(given)+ rid = str(before.get("reservation_id") or given)+ again = f"phone-harness cloud reservations cancel {rid} --yes"+ # Asked only when there is something to give up. A refund that is still+ # owed, or a reservation already gone, has nothing left to confirm.+ if before.get("can_cancel") and not yes:+ if as_json or not sys.stdin.isatty(): # nobody to ask: say what it would do, and how+ sys.exit(f"{_cancel_words(before)}\nNot cancelled. To confirm, run: {again}")+ print(_cancel_words(before))+ if input("Cancel this reservation? [y/N] ").strip().lower() not in ("y", "yes"):+ print("Not cancelled.")+ return 1+ try:+ done = _api("POST", f"/reservations/{urllib.parse.quote(rid, safe='')}/cancel",+ timeout=RESERVE_TIMEOUT)+ except CloudError as e:+ sys.exit(_explain_reservation(e, rid=rid, retry=f"run `{again}`"))+ except OSError as e:+ sys.exit(f"Could not reach {_target('API')}: {e}\nThe cancel may still have gone through. "+ f"`phone-harness cloud reservations {rid}` shows where it stands, and asking "+ "again never refunds twice.")+ if as_json:+ print(json.dumps(done, indent=2))+ return 0+ currency = (done.get("deposit") or {}).get("currency") or "usd"+ refunded = done.get("refunded_cents") or 0+ back = f" {_amount(refunded, currency)} is on its way back to the card that paid."+ status = done.get("status")+ if status == "cancelled" and before.get("status") == "cancelled":+ print(f"Reservation {rid} was already cancelled. Nothing to refund.")+ elif status == "cancelled":+ print(f"{term.mark()} Reservation {rid} cancelled."+ + (back if refunded else " Nothing had been charged."))+ elif status == "granted":+ print(f"{term.mark()} Left the queue for the phones still waiting on {rid}."+ + (back if refunded else ""))+ else:+ print(f"Reservation {rid} is now {status}. If a refund is owed and has not arrived, "+ f"run the same command again: {again}")+ if done.get("detail"):+ print(term.note(f" {done['detail']}"))+ return 0+++def _reservations(args):+ args = list(args)+ as_json, yes = _flag(args, "--json"), _flag(args, "--yes")+ if any(a.startswith("-") for a in args):+ sys.exit(RESERVATIONS_USAGE)+ if args[:1] == ["cancel"]:+ if len(args) != 2:+ sys.exit(RESERVATIONS_USAGE)+ return _cancel_reservation(args[1], yes, as_json)+ if yes or len(args) > 1:+ sys.exit(RESERVATIONS_USAGE)+ if args:+ found = _find_reservation(args[0])+ if as_json:+ print(json.dumps(found, indent=2))+ else:+ _print_reservation(found)+ return 0+ rows = _listed()+ if as_json:+ print(json.dumps(rows, indent=2))+ return 0+ if not rows:+ print("No reservations. `phone-harness cloud reserve` starts one.")+ return 0+ print(_format_reservations(rows))+ if any(r.get("status") == "pending_payment" for r in rows):+ print(term.note("pending_payment holds no place until its deposit is paid: "+ "`phone-harness cloud reservations ID` shows the link."))+ return 0++# --- CLI (phone-harness cloud ...) -------------------------------------------CLI_USAGE = """Usage:@@ -1779,6 +2288,22 @@ CLI_USAGE = """Usage:phone-harness cloud phone [reset --yes] the saved Android. reset --yes wipes its stored statephone-harness cloud keys [create [LABEL] | revoke HASH] API keys, for CIphone-harness cloud history [-n NUM] [--json]+ phone-harness cloud reserve --type iphone|iphone-esim --plan monthly|annual+ [--qty N] --use-case TEXT [--first-name NAME] [--last-name NAME]+ [--open] [--json] [--idempotency-key KEY]+ ask for cloud iPhones (--qty 1 to 50, default 1) before the+ account has them. Prints the quote and a Stripe Checkout+ link for the refundable deposit; a person pays it in a+ browser, and nothing is held until then. --open opens+ the link. The names go on the reservation in place of+ the account's. Five unpaid reservations an hour for one+ account; cancelling one does not free a place+ phone-harness cloud reservations [ID] [--json]+ the account's reservations: status, place in the queue,+ deposit, when it was paid. ID or a unique prefix shows one+ phone-harness cloud reservations cancel ID [--yes]+ give the place up; the deposit still held is refunded.+ Refused once every phone has been handed overEvery command takes --session SID, or PHONE_HARNESS_SESSION, and so do helperscripts: that pins one phone for this process. With neither, helpers follow theattached session (the last start, or cloud use). SID may be a unique prefix.@@ -1789,7 +2314,8 @@ They may live in a .env file at the repo root or in the agent workspace (never c_COMMANDS = {"login": _login, "logout": _logout, "whoami": _whoami, "start": _start,"stop": _stop, "ls": _ls, "show": _show, "use": _use, "watch": _watch, "open": _open,- "phone": _phone, "keys": _keys, "history": _history}+ "phone": _phone, "keys": _keys, "history": _history,+ "reserve": _reserve, "reservations": _reservations}def _cloud_parsers():@@ -1890,6 +2416,42 @@ def _cloud_parsers():help="how many sessions to show (default 20)")history.add_argument("--json", action="store_true", help="print the sessions as JSON")parsers["history"] = history++ reserve = make(+ "reserve", RESERVE_USAGE[len("Usage: "):],+ "Ask for cloud iPhones before the account has them. Prints the quote the API "+ "gives (the deposit due now, and the plan's first billing period at the intro "+ "and standard prices) and a Stripe Checkout link for the deposit, which is "+ "refundable while the reservation is queued. A person pays it in a browser: "+ "this command never pays, and the reservation holds no place until it is paid. "+ + IPHONES_ONLY)+ reserve.add_argument("--type", metavar="TYPE", help="iphone, or iphone-esim for one with an eSIM")+ reserve.add_argument("--plan", metavar="PLAN", help="monthly or annual")+ reserve.add_argument("--qty", "--quantity", metavar="N",+ help=f"how many phones, 1 to {RESERVE_MAX_QUANTITY} (default 1)")+ reserve.add_argument("--use-case", metavar="TEXT", help="what the phones are for, in a sentence")+ reserve.add_argument("--first-name", metavar="NAME",+ help="the name to put on the reservation, in place of the account's")+ reserve.add_argument("--last-name", metavar="NAME", help="likewise")+ reserve.add_argument("--open", action="store_true", help="open the Checkout link in the browser")+ reserve.add_argument("--json", action="store_true", help="print the reservation as JSON")+ reserve.add_argument("--idempotency-key", metavar="KEY",+ help="repeat a request that may have got through: the same key and "+ "options answer with the same reservation (16 to 128 letters, "+ "digits, _ or -). One is made up when this is left out")+ parsers["reserve"] = reserve++ reservations = make(+ "reservations", RESERVATIONS_USAGE[len("Usage: "):],+ "The account's reservations: status, place in the queue, deposit, and when it "+ "was paid. ID, or a unique prefix of one, shows that reservation with its quote "+ "and, while it is unpaid, its Checkout link. cancel ID gives the place up and "+ "refunds the deposit still held; it is refused once every phone has been "+ "handed over.")+ reservations.add_argument("--json", action="store_true", help="print the API's answer as JSON")+ reservations.add_argument("--yes", action="store_true",+ help="cancel without being asked to confirm")+ parsers["reservations"] = reservationsreturn parsersdiff --git a/src/phone_harness/run.py b/src/phone_harness/run.pyindex 116841e..a765f37 100644--- a/src/phone_harness/run.py+++ b/src/phone_harness/run.py@@ -127,10 +127,36 @@ class _StreamTail:return getattr(self._wrapped, name)+# What may be recorded of a `cloud reserve` or `cloud reservations` command+# line: its own flags and the fixed words they take. Anything else on it is a+# person's name, what they want a phone for, a retry key, or a reservation id+# (which opens that reservation's status page), and none of that is telemetry.+_RESERVATION_FLAGS = frozenset({+ "--type", "--plan", "--qty", "--quantity", "--use-case", "--first-name", "--last-name",+ "--idempotency-key", "--open", "--json", "--yes", "--help", "-h"})+_RESERVATION_WORDS = frozenset({+ "cancel", "iphone", "iphone-esim", "iphone_esim", "monthly", "annual"})+++def _reservation_argv(words):+ def plain(word):+ return word in _RESERVATION_WORDS or word.isdigit()++ masked = []+ for word in words:+ flag, equals, value = word.partition("=")+ if equals and flag in _RESERVATION_FLAGS:+ masked.append(f"{flag}={value if plain(value) else '<redacted>'}")+ else:+ masked.append(word if word in _RESERVATION_FLAGS or plain(word) else "<redacted>")+ return masked++def _telemetry_argv(args):"""The command line as cli_event records it. `--session SID` is left out:the pinned session is the event's session_id. An Android pairing code is- masked: it is a credential."""+ masked: it is a credential. So is everything free on a reservation+ command (see _RESERVATION_FLAGS)."""argv, words = [], iter(args)for word in words:if word == "--session":@@ -139,6 +165,8 @@ def _telemetry_argv(args):argv.append(word)if argv[:2] == ["android", "pair"]:argv[2:] = ["<code>" if word.isdigit() else word for word in argv[2:]]+ if argv[:1] == ["cloud"] and argv[1:2] in (["reserve"], ["reservations"]):+ argv[2:] = _reservation_argv(argv[2:])return argvdiff --git a/tests/test_cli.py b/tests/test_cli.pyindex 79fc1f3..5812c96 100644--- a/tests/test_cli.py+++ b/tests/test_cli.py@@ -80,6 +80,8 @@ class HelpAndFlags(unittest.TestCase):"phone": "--yes","keys": "--json","history": "--limit",+ "reserve": "--idempotency-key",+ "reservations": "--yes",}for name, flag in cloud_cmds.items():help_out = _run("cloud", name, "--help")diff --git a/tests/test_cloud_reserve.py b/tests/test_cloud_reserve.pynew file mode 100644index 0000000..dcf76f6--- /dev/null+++ b/tests/test_cloud_reserve.py@@ -0,0 +1,1053 @@+"""`phone-harness cloud reserve` and `cloud reservations` against a fake reservation API.++No network, no Stripe, no money. The fake answers in the shapes phone-cloud's+reservation API gives (its docs/api.md) and keeps every request the CLI sent,+so a test can check the body, the bearer and the Idempotency-Key.++ python -m unittest discover tests -p test_cloud_reserve.py+"""+import contextlib+import io+import json+import os+import subprocess+import sys+import tempfile+import threading+import time+import unittest+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from unittest import mock++SRC = str(Path(__file__).resolve().parents[1] / "src")+SUPPORT = str(Path(__file__).resolve().parent / "support")+if SRC not in sys.path:+ sys.path.insert(0, SRC)+if SUPPORT not in sys.path:+ sys.path.insert(0, SUPPORT)+import browser_recorder+browser_recorder.install()++from phone_harness import cloud, run # noqa: E402++KEY = "pck_reserve_test"+USE_CASE = "Testing our listings app on a real iPhone."+CHECKOUT = "https://checkout.stripe.com/c/pay/cs_test_"+DEPOSIT = 2000+# (standard, intro) cents for one phone for one billing period. For a short+# while the API took a reservation for a cloud Android, before it had a price.+# It refuses one now, and this CLI never asks, but one made then can still be+# on the account.+PRICES = {("iphone", "monthly"): (8000, 5000), ("iphone", "annual"): (76800, 48000),+ ("iphone_esim", "monthly"): (10000, 6500), ("iphone_esim", "annual"): (96000, 62400),+ ("android", "monthly"): (None, None), ("android", "annual"): (None, None)}+DETAIL = {+ "pending_payment": "This reservation is not finished. Pay the deposit to hold a place.",+ "queued": "You are in the queue. Cancel any time and the deposit comes back in full.",+ "cancelling": "You have left the queue. Your deposit is on its way back to your card.",+ "granted": "Your phone is yours. The deposit went towards your first bill.",+ "ended": "The plan for this phone has ended.",+ "cancelled": "You left the queue and the deposit was refunded in full.",+}+GRANTED_REFUSAL = ("Your phone has been handed over, and its deposit went towards your "+ "first bill. Manage the plan from your account.")+++def rid(n):+ return "rsv_" + f"{n:024x}"+++FAR = 0xa1 << 88 # an id that shares no leading digits with rid(1), rid(2), ...+++def reservation(n, phone_type="iphone", plan="monthly", quantity=1, status="pending_payment", *,+ position=None, granted=0, paid_days_ago=None, intro=True):+ """One reservation as the API shows it, in whichever state `status` names."""+ standard, intro_cents = PRICES[(phone_type, plan)]+ lines = []+ if standard is not None:+ rest = quantity+ if intro and intro_cents is not None:+ lines.append({"tier": "intro", "quantity": 1, "unit_cents": intro_cents})+ rest -= 1+ if rest:+ lines.append({"tier": "standard", "quantity": rest, "unit_cents": standard})+ first = sum(line["quantity"] * line["unit_cents"] for line in lines) if lines else None+ total = DEPOSIT * quantity+ unpaid = status == "pending_payment" or (status == "cancelled" and paid_days_ago is None)+ credited = 0 if unpaid else DEPOSIT * granted+ held = total - credited if status in ("queued", "cancelling") else 0+ refunded = total - credited if status in ("cancelled", "granted", "ended") and not unpaid else 0+ pending = status == "pending_payment"+ return {+ "reservation_id": rid(n), "status": status, "phone_type": phone_type, "plan": plan,+ "quantity": quantity, "created_at": time.time() - 86400 * (paid_days_ago or 0) - 60,+ "paid_at": None if unpaid else time.time() - 86400 * (paid_days_ago or 0),+ "position": position if status == "queued" else None,+ "queued": quantity - granted if status == "queued" else 0,+ "granted": 0 if unpaid else granted,+ "ended": granted if status == "ended" else 0, # phones whose plan has since ended+ "deposit": {"paid_cents": 0 if unpaid else total, "refundable_cents": held,+ "credited_cents": credited, "refunded_cents": refunded, "currency": "usd"},+ "can_cancel": status in ("pending_payment", "queued"),+ "checkout_url": CHECKOUT + f"{n:06d}" if pending else None,+ "expires_at": time.time() + 86400 if pending else None,+ "quote": {"currency": "usd", "interval": "month" if plan == "monthly" else "year",+ "deposit": {"per_phone_cents": DEPOSIT, "phones": quantity, "total_cents": total,+ "refundable": True},+ "priced": standard is not None, "lines": lines, "first_period_cents": first,+ "due_at_handover_cents": first - total if first is not None else None},+ "detail": ("This reservation was never paid for, so nothing was charged and no place is held."+ if status == "cancelled" and unpaid else DETAIL[status]),+ }+++class FakeApi(BaseHTTPRequestHandler):+ """POST/GET /reservations, GET /reservations/{id}, POST /reservations/{id}/cancel."""+ valid = set()+ rows = {} # reservation_id -> reservation, in the order made+ keys = {} # Idempotency-Key -> (body, reservation_id)+ requests = [] # (method, path, headers with lowercase names, body)+ fail = None # (status, body, headers): the next request answers this instead+ drop = 0 # the next N creates are made, and then never answered+ live = True # False: an API from before reservations; every route under it is a 404+ account_name = "Ada King" # the name on file; None for an account that has none+ names = {} # reservation_id -> [first, last] as the API would store them+ checkout = None # set: every new reservation's checkout_url is this instead++ def log_message(self, *a):+ pass++ def _send(self, status, body, headers=None):+ raw = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(raw)))+ for name, value in (headers or {}).items():+ self.send_header(name, value)+ self.end_headers()+ self.wfile.write(raw)++ def _handle(self):+ c = FakeApi+ n = int(self.headers.get("Content-Length") or 0)+ body = json.loads(self.rfile.read(n)) if n else None+ path, method = self.path.split("?")[0], self.command+ c.requests.append((method, path, {k.lower(): v for k, v in self.headers.items()}, body))+ if self.headers.get("Authorization", "")[7:] not in c.valid:+ return self._send(401, {"error": "bad or missing bearer token"})+ if c.fail:+ (status, payload, headers), c.fail = c.fail, None+ return self._send(status, payload, headers)+ parts = path.strip("/").split("/")+ if parts[0] != "reservations" or not c.live:+ return self._send(404, {"error": f"no route {method} {path}"})+ if len(parts) == 1 and method == "POST":+ return self._create(body or {})+ if len(parts) == 1 and method == "GET":+ return self._send(200, {"reservations": list(reversed(list(c.rows.values())))})+ row = c.rows.get(parts[1])+ if row is None:+ return self._send(404, {"error": "No such reservation"})+ if len(parts) == 2 and method == "GET":+ return self._send(200, row)+ if len(parts) == 3 and parts[2] == "cancel" and method == "POST":+ return self._cancel(row)+ return self._send(404, {"error": f"no route {method} {path}"})++ def _create(self, body):+ c = FakeApi+ key = self.headers.get("Idempotency-Key")+ if set(body) - {"first_name", "last_name", "email", "use_case", "phone_type", "plan", "quantity"}:+ return self._send(400, {"error": "Unknown field"})+ if body.get("phone_type") == "android":+ return self._send(400, {"error": "Cloud Android cannot be reserved. Choose a phone: iphone, iphone_esim",+ "code": "phone_not_reservable"})+ if (body.get("phone_type"), body.get("plan")) not in PRICES:+ return self._send(400, {"error": "Choose a phone: iphone, iphone_esim"})+ if type(body.get("quantity")) is not int or not 1 <= body["quantity"] <= 50:+ return self._send(400, {"error": "Choose between 1 and 50 phones"})+ if key in c.keys:+ sent, made = c.keys[key]+ if sent != body:+ return self._send(409, {"error": "Idempotency-Key was already used with a different request",+ "code": "idempotency_conflict"})+ status, row = 200, c.rows[made]+ else:+ row = reservation(len(c.rows) + 1, body["phone_type"], body["plan"], body["quantity"])+ if c.checkout:+ row["checkout_url"] = c.checkout+ c.rows[row["reservation_id"]] = row+ # A signed-in account need not say who it is: a name in the body is+ # used, else the one on file, else none at all.+ first, _, last = (c.account_name or "").partition(" ")+ c.names[row["reservation_id"]] = [body.get("first_name") or first or None,+ body.get("last_name") or last or None]+ if key:+ c.keys[key] = (body, row["reservation_id"])+ status = 201+ if c.drop:+ c.drop -= 1+ self.close_connection = True+ return None # made, and the answer never arrives+ return self._send(status, {**row, "status_url": "https://phone-harness.com/reservation?id="+ + row["reservation_id"]})++ def _cancel(self, row):+ status, deposit = row["status"], row["deposit"]+ if status in ("granted", "ended"):+ return self._send(409, {"error": GRANTED_REFUSAL, "code": "already_granted"})+ refunded = 0+ if status in ("queued", "cancelling"):+ refunded = deposit["refundable_cents"]+ deposit.update(refundable_cents=0, refunded_cents=deposit["refunded_cents"] + refunded)+ handed = row["granted"]+ row.update(status="granted" if handed else "cancelled", position=None, queued=0,+ can_cancel=False,+ detail=(f"{handed} phone handed over. You left the queue for the other "+ f"{row['quantity'] - handed}, and that part of the deposit was refunded."+ if handed else DETAIL["cancelled"]))+ elif status == "pending_payment":+ row.update(status="cancelled", can_cancel=False, checkout_url=None, expires_at=None,+ detail="This reservation was never paid for, so nothing was charged "+ "and no place is held.")+ return self._send(200, {**row, "refunded_cents": refunded})++ do_GET = do_POST = _handle+++class ReserveCase(unittest.TestCase):+ """A fake API, a throwaway home, and an API key in the environment."""++ def setUp(self):+ self.home = tempfile.TemporaryDirectory()+ self.addCleanup(self.home.cleanup)+ FakeApi.valid, FakeApi.rows, FakeApi.keys, FakeApi.requests = {KEY}, {}, {}, []+ FakeApi.fail, FakeApi.drop, FakeApi.checkout = None, 0, None+ FakeApi.account_name, FakeApi.names, FakeApi.live = "Ada King", {}, True+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), FakeApi)+ threading.Thread(target=self.server.serve_forever, daemon=True).start()+ self.addCleanup(self.server.server_close)+ self.addCleanup(self.server.shutdown)+ self.api = f"http://127.0.0.1:{self.server.server_port}"+ self.env = {**os.environ, "PYTHONPATH": SUPPORT + os.pathsep + SRC,+ "PHONE_HARNESS_HOME": self.home.name, "PHONE_HARNESS_TELEMETRY": "0",+ "PHONE_HARNESS_NO_UPDATE_CHECK": "1", "PHONE_HARNESS_CLOUD_API": self.api,+ "PHONE_HARNESS_CLOUD_OAUTH_ISSUER": self.api, "PHONE_HARNESS_API_KEY": KEY}+ for name in ("PHONE_HARNESS_SESSION", "BROWSER", "NO_COLOR"):+ self.env.pop(name, None)+ browser_recorder.recorder.reset()++ def run_cli(self, *args, stdin=None, env=None):+ return subprocess.run([sys.executable, "-m", "phone_harness.run", "cloud", *args], input=stdin,+ capture_output=True, text=True, env={**self.env, **(env or {})})++ def reserve(self, *extra, kind="iphone", plan="monthly", env=None):+ return self.run_cli("reserve", "--type", kind, "--plan", plan,+ "--use-case", USE_CASE, *extra, env=env)++ def sent(self, method=None, suffix=""):+ return [r for r in FakeApi.requests if (method is None or r[0] == method) and r[1].endswith(suffix)]++ def hold(self, *rows):+ """Put reservations on the account, oldest first."""+ for row in rows:+ FakeApi.rows[row["reservation_id"]] = row+ return rows[0] if len(rows) == 1 else rows+++class Reserve(ReserveCase):+ def test_reserve_sends_the_four_fields_the_bearer_and_a_key_of_its_own(self):+ r = self.reserve("--qty", "3", kind="iphone-esim", plan="annual")+ self.assertEqual(r.returncode, 0, r.stderr)+ [(method, path, headers, body)] = FakeApi.requests+ self.assertEqual((method, path), ("POST", "/reservations"))+ self.assertEqual(body, {"phone_type": "iphone_esim", "plan": "annual", "quantity": 3,+ "use_case": USE_CASE})+ self.assertEqual(headers["authorization"], f"Bearer {KEY}")+ self.assertEqual(headers["content-type"], "application/json")+ self.assertRegex(headers["idempotency-key"], r"^[A-Za-z0-9_-]{16,128}$")+ again = self.reserve("--qty", "3", kind="iphone-esim", plan="annual")+ self.assertEqual(again.returncode, 0, again.stderr)+ first, second = (req[2]["idempotency-key"] for req in FakeApi.requests)+ self.assertNotEqual(first, second) # one key for each invocation+ self.assertEqual(len(FakeApi.rows), 2)++ def test_quantity_defaults_to_one_and_the_api_spelling_of_a_type_is_taken_too(self):+ spelled = self.run_cli("reserve", "--type=iphone_esim", "--plan=monthly", "--use-case=Two words")+ self.assertEqual(spelled.returncode, 0, spelled.stderr)+ self.assertEqual(self.reserve("--quantity", "2", kind="iphone-esim").returncode, 0)+ self.assertEqual([req[3] for req in FakeApi.requests], [+ {"phone_type": "iphone_esim", "plan": "monthly", "quantity": 1, "use_case": "Two words"},+ {"phone_type": "iphone_esim", "plan": "monthly", "quantity": 2, "use_case": USE_CASE}])+ twice = self.reserve("--qty", "1", "--qty", "2") # said twice is not guessed at+ self.assertEqual(twice.returncode, 1)+ self.assertIn("Usage: phone-harness cloud reserve", twice.stderr)+ self.assertEqual(len(FakeApi.requests), 2)++ def test_the_key_can_be_given_so_a_retry_is_the_same_reservation(self):+ key = "retry-key_0123456789"+ first = self.reserve("--idempotency-key", key, "--json")+ again = self.reserve("--idempotency-key", key, "--json")+ self.assertEqual((first.returncode, again.returncode), (0, 0), first.stderr + again.stderr)+ self.assertEqual([req[2]["idempotency-key"] for req in FakeApi.requests], [key, key])+ self.assertEqual(json.loads(first.stdout)["reservation_id"],+ json.loads(again.stdout)["reservation_id"])+ self.assertEqual(len(FakeApi.rows), 1)+ other = self.reserve("--idempotency-key", key, "--qty", "2")+ self.assertEqual(other.returncode, 1)+ self.assertIn("already used for a different request", other.stderr)+ self.assertEqual(len(FakeApi.rows), 1)++ def test_bad_arguments_are_refused_before_anything_is_sent(self):+ use = ["--use-case", "A phone to test on."]+ cases = [+ (["--type", "iphone", "--plan", "monthly", "--qty", "0", *use], "between 1 and 50"),+ (["--type", "iphone", "--plan", "monthly", "--qty", "51", *use], "between 1 and 50"),+ (["--type", "iphone", "--plan", "monthly", "--qty", "-3", *use], "between 1 and 50"),+ (["--type", "iphone", "--plan", "monthly", "--qty", "two", *use], "--qty must be a number"),+ (["--type", "iphone", "--plan", "monthly", "--qty", "1.5", *use], "--qty must be a number"),+ (["--type", "ipad", "--plan", "monthly", *use], "--type must be iphone or iphone-esim, not 'ipad'"),+ (["--plan", "monthly", *use], "--type is required"),+ (["--type", "iphone", "--plan", "weekly", *use], "--plan must be monthly or annual"),+ (["--type", "iphone", *use], "--plan is required"),+ (["--type", "iphone", "--plan", "monthly"], "--use-case is required"),+ (["--type", "iphone", "--plan", "monthly", "--use-case", " "], "--use-case is required"),+ (["--type", "iphone", "--plan", "monthly", "--use-case", "x" * 2001], "the most is 2000"),+ (["--type", "iphone", "--plan", "monthly", "--idempotency-key", "short", *use], "16 to 128"),+ (["--type", "iphone", "--plan", "monthly", "--idempotency-key", "has spaces in the key!", *use],+ "16 to 128"),+ (["--type", "iphone", "--plan", "monthly", "extra", *use], "Usage: phone-harness cloud reserve"),+ ]+ for args, needle in cases:+ with self.subTest(args=args[:6]):+ r = self.run_cli("reserve", *args)+ self.assertEqual(r.returncode, 1, r.stdout)+ self.assertIn(needle, r.stderr)+ self.assertEqual(r.stdout, "")+ unknown = self.run_cli("reserve", "--type", "iphone", "--plan", "monthly", "--pay-now", *use)+ self.assertEqual(unknown.returncode, 2)+ self.assertIn("unrecognized arguments: --pay-now", unknown.stderr)+ self.assertEqual(FakeApi.requests, [])+ self.assertEqual(browser_recorder.recorder.urls(), [])++ def test_an_android_is_not_reserved_and_nothing_is_sent(self):+ said = ("Reservations are for iPhones only (with or without eSIM). "+ "Cloud Android emulators are on the $20 plan and are not reserved.")+ self.assertEqual(cloud.IPHONES_ONLY, said)+ for kind in ("android", "Android", "android-emulator"):+ with self.subTest(kind=kind):+ r = self.reserve("--qty", "2", "--json", "--open", kind=kind)+ self.assertEqual(r.returncode, 1, r.stdout)+ self.assertEqual(r.stderr.splitlines()[0], said)+ self.assertIn("Usage: phone-harness cloud reserve --type iphone|iphone-esim --plan", r.stderr)+ self.assertEqual(r.stdout, "")+ self.assertEqual(FakeApi.requests, [])+ self.assertEqual(browser_recorder.recorder.urls(), [])+ # Nothing the command says about itself offers one either.+ self.assertEqual(sorted(set(cloud.RESERVE_TYPES.values())), ["iphone", "iphone_esim"])+ self.assertNotIn("android", cloud.RESERVE_USAGE.lower())+ self.assertIn("cloud reserve --type iphone|iphone-esim --plan monthly|annual", cloud.CLI_USAGE)+ helped = self.run_cli("reserve", "--help")+ self.assertEqual(helped.returncode, 0, helped.stderr)+ self.assertIn(said, " ".join(helped.stdout.split()))+ self.assertNotRegex(helped.stdout, r"(?i)\|android|or android")++ def test_the_quote_and_the_checkout_link_are_printed_and_nothing_is_called_reserved(self):+ r = self.reserve("--qty", "3")+ self.assertEqual(r.returncode, 0, r.stderr)+ out = r.stdout+ self.assertIn(f"Reservation {rid(1)} started: 3 x iPhone, monthly.", out)+ self.assertIn("holds no place in the queue until the deposit is paid", out)+ self.assertIn("deposit $60.00 due now (3 x $20.00), refundable in full while queued", out)+ self.assertIn("first month 1 x $50.00 intro price, once per customer", out)+ self.assertIn("2 x $80.00 standard price", out)+ self.assertIn("$210.00 in all; $150.00 due at handover, after the deposit", out)+ self.assertIn("pay " + CHECKOUT + "000001", out)+ self.assertIn("the link works for another 24 hours", out)+ self.assertIn(f"phone-harness cloud reservations {rid(1)}", out)+ self.assertNotRegex(out, r"(?i)\breserved\b|\bposition\b|you are in the queue")+ self.assertEqual(browser_recorder.recorder.urls(), []) # only --open opens anything+ self.assertNotIn("\x1b", out)++ def test_an_annual_quote(self):+ annual = self.reserve("--qty", "2", kind="iphone-esim", plan="annual")+ self.assertIn("2 x iPhone with eSIM, annual", annual.stdout)+ self.assertIn("first year 1 x $624.00 intro price, once per customer", annual.stdout)+ self.assertIn("1 x $960.00 standard price", annual.stdout)+ self.assertIn("$1,584.00 in all; $1,544.00 due at handover, after the deposit", annual.stdout)++ def test_json_prints_what_the_api_answered(self):+ r = self.reserve("--qty", "2", "--json")+ self.assertEqual(r.returncode, 0, r.stderr)+ made = json.loads(r.stdout)+ self.assertEqual(made["reservation_id"], rid(1))+ self.assertEqual(made["status"], "pending_payment")+ self.assertEqual(made["checkout_url"], CHECKOUT + "000001")+ self.assertEqual(made["quote"]["deposit"], {"per_phone_cents": 2000, "phones": 2,+ "total_cents": 4000, "refundable": True})+ self.assertEqual(made["status_url"], "https://phone-harness.com/reservation?id=" + rid(1))++ def test_open_opens_the_checkout_link_in_the_browser(self):+ r = self.reserve("--open")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertEqual(browser_recorder.recorder.urls(), [CHECKOUT + "000001"])+ self.assertIn("opened in your browser", r.stdout)+ self.assertIn(CHECKOUT + "000001", r.stdout) # still printed: it may be relayed+ browser_recorder.recorder.reset()+ quiet = self.reserve("--open", "--json", env={"PHONE_HARNESS_CLOUD_WATCH": "0"})+ self.assertEqual(json.loads(quiet.stdout)["reservation_id"], rid(2))+ self.assertEqual(browser_recorder.recorder.urls(), [CHECKOUT + "000002"]) # --open is explicit++ def test_a_link_that_is_not_stripe_checkout_is_neither_shown_nor_opened(self):+ for bad in ("https://checkout.stripe.com.example.net/pay", "http://checkout.stripe.com/c/pay/x",+ "https://[email protected]/pay", "file:///etc/passwd",+ "https://example.net/?next=https://checkout.stripe.com/"):+ with self.subTest(bad=bad):+ FakeApi.checkout = bad+ r = self.reserve("--open")+ self.assertEqual(r.returncode, 1, r.stdout)+ self.assertNotIn(bad, r.stdout + r.stderr)+ self.assertIn("is not a Stripe Checkout page", r.stdout)+ self.assertNotIn("opened in your browser", r.stdout)+ self.assertEqual(browser_recorder.recorder.urls(), [])++ def test_a_name_is_optional_and_overrides_the_accounts_when_given(self):+ plain = self.reserve() # nothing said: the account's name+ self.assertEqual(plain.returncode, 0, plain.stderr)+ self.assertEqual(FakeApi.requests[-1][3], {"phone_type": "iphone", "plan": "monthly", "quantity": 1,+ "use_case": USE_CASE})+ self.assertEqual(FakeApi.names[rid(1)], ["Ada", "King"])+ named = self.reserve("--first-name", " Dana ", "--last-name", "Okafor")+ self.assertEqual(named.returncode, 0, named.stderr)+ self.assertEqual(FakeApi.requests[-1][3], {+ "phone_type": "iphone", "plan": "monthly", "quantity": 1, "use_case": USE_CASE,+ "first_name": "Dana", "last_name": "Okafor"})+ self.assertEqual(FakeApi.names[rid(2)], ["Dana", "Okafor"])+ half = self.reserve("--last-name=Lovelace", "--first-name", " ") # one of the two; a blank is not sent+ self.assertEqual(half.returncode, 0, half.stderr)+ self.assertEqual(FakeApi.requests[-1][3], {+ "phone_type": "iphone", "plan": "monthly", "quantity": 1, "use_case": USE_CASE,+ "last_name": "Lovelace"})+ self.assertEqual(FakeApi.names[rid(3)], ["Ada", "Lovelace"])+ FakeApi.account_name = None # no name on file, and none is needed+ bare = self.reserve()+ self.assertEqual(bare.returncode, 0, bare.stderr)+ self.assertIn(f"Reservation {rid(4)} started", bare.stdout)+ self.assertEqual(FakeApi.names[rid(4)], [None, None])+ for request in FakeApi.requests:+ self.assertNotIn("email", request[3]) # the account's address is the API's to fill in++ def test_a_key_that_was_already_paid_for_shows_where_it_stands(self):+ key = "paid-already_0123456789"+ row = self.hold(reservation(1, quantity=2, status="queued", position=4, paid_days_ago=2))+ FakeApi.keys[key] = ({"phone_type": "iphone", "plan": "monthly", "quantity": 2,+ "use_case": USE_CASE}, row["reservation_id"])+ r = self.reserve("--qty", "2", "--idempotency-key", key, "--open")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn(f"Reservation {rid(1)} already exists for this key", r.stdout)+ self.assertIn("status queued", r.stdout)+ self.assertIn("position 4 in the queue", r.stdout)+ self.assertNotIn(f"Reservation {rid(1)} started", r.stdout)+ self.assertNotIn("checkout.stripe.com", r.stdout)+ self.assertEqual(browser_recorder.recorder.urls(), []) # nothing left to pay+++class ReserveErrors(ReserveCase):+ def test_not_signed_in_sends_nothing(self):+ r = self.reserve(env={"PHONE_HARNESS_API_KEY": ""})+ self.assertEqual(r.returncode, 1)+ self.assertIn("Not signed in. Run: phone-harness cloud login", r.stderr)+ for args in (["reservations"], ["reservations", rid(1)], ["reservations", "cancel", rid(1), "--yes"]):+ r = self.run_cli(*args, env={"PHONE_HARNESS_API_KEY": ""})+ self.assertEqual(r.returncode, 1, args)+ self.assertIn("phone-harness cloud login", r.stderr)+ self.assertEqual(FakeApi.requests, []) # never an anonymous reservation++ def test_the_cli_sign_in_is_the_bearer_and_a_refused_one_says_to_sign_in(self):+ auth = Path(self.home.name) / "config" / "auth.json"+ auth.parent.mkdir(parents=True)+ auth.write_text(json.dumps({"access_token": "at-cli", "expires_at": time.time() + 3600}))+ FakeApi.valid = {"at-cli"}+ r = self.reserve(env={"PHONE_HARNESS_API_KEY": ""})+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertEqual(FakeApi.requests[0][2]["authorization"], "Bearer at-cli")+ FakeApi.valid = set()+ refused = self.reserve(env={"PHONE_HARNESS_API_KEY": ""})+ self.assertEqual(refused.returncode, 1)+ self.assertIn("signed out. Run: phone-harness cloud login", refused.stderr)+ listing = self.run_cli("reservations")+ self.assertEqual(listing.returncode, 1)+ self.assertIn("phone-harness cloud login", listing.stderr)++ def test_api_refusals_are_said_in_the_apis_words(self):+ cases = [+ ((403, {"error": "Reservations are not open yet.", "code": "reservations_closed"}, None),+ ["Reservations are not open yet."]),+ ((403, {"error": "That phone and plan cannot be reserved yet.", "code": "plan_unavailable"}, None),+ ["That phone and plan cannot be reserved yet.", "another --type or --plan"]),+ ((429, {"error": "Too many unfinished reservations. Finish one, or try again in an hour.",+ "code": "rate_limited", "retry_after_seconds": 3600}, {"Retry-After": "3600"}),+ ["Too many unfinished reservations", "Cancelling one does not free a place; paying for one does.",+ "phone-harness cloud reservations"]),+ ((400, {"error": "A first name is too long"}, None), ["A first name is too long"]),+ ((400, {"error": "Choose between 1 and 50 phones"}, None), ["Choose between 1 and 50 phones"]),+ # What the API says of a phone it does not reserve, should this CLI ever offer one it has dropped.+ ((400, {"error": "Cloud Android cannot be reserved. Choose a phone: iphone, iphone_esim",+ "code": "phone_not_reservable"}, None),+ ["Cloud Android cannot be reserved. Choose a phone: iphone, iphone_esim"]),+ ((403, {"error": "this sign-in can drive phones, not manage the account; use the dashboard "+ "or an API key", "code": "scope_limited"}, None), ["use the dashboard or an API key"]),+ ((403, {"error": "account is blocked", "code": "account_blocked"}, None), ["blocked"]),+ ((500, {"error": "The phone service could not complete this request."}, None),+ ["could not complete this request", "HTTP 500"]),+ ]+ for fail, needles in cases:+ with self.subTest(code=fail[1].get("code") or fail[0]):+ FakeApi.fail = fail+ r = self.reserve()+ self.assertEqual(r.returncode, 1, r.stdout)+ for needle in needles:+ self.assertIn(needle, r.stderr)+ # A refusal to reserve is not "your account is not enabled for phones".+ self.assertNotIn("isn't enabled for phones", r.stderr)+ self.assertNotIn("source=cli", r.stderr)+ self.assertEqual(r.stdout, "")+ self.assertEqual(FakeApi.rows, {})++ def test_an_api_from_before_reservations_says_so_from_every_command(self):+ """Signed in, a path the API does not have is a 404. Until reservations are live that is all+ of them, and "no reservation of yours has that id" would be the wrong thing to say."""+ FakeApi.live = False+ for args in (["reserve", "--type", "iphone", "--plan", "monthly", "--use-case", USE_CASE],+ ["reservations"], ["reservations", "--json"], ["reservations", rid(1)],+ ["reservations", "rsv_0000"], ["reservations", "cancel", rid(1)],+ ["reservations", "cancel", rid(1), "--yes"]):+ with self.subTest(args=args[:3]):+ r = self.run_cli(*args)+ self.assertEqual(r.returncode, 1, r.stdout)+ self.assertIn(f"{self.api} does not take reservations yet", r.stderr)+ self.assertIn("Nothing was changed.", r.stderr)+ for wrong in ("No reservation", "no route", "404", "matches 0", "Traceback"):+ self.assertNotIn(wrong, r.stderr)+ self.assertEqual(r.stdout, "")+ self.assertEqual(self.sent("POST", "/cancel"), []) # the read came first and said enough++ def test_a_404_for_one_id_on_an_api_that_has_reservations_is_that_id(self):+ self.hold(reservation(1, status="queued", position=1, paid_days_ago=1))+ unknown = self.run_cli("reservations", rid(9))+ self.assertIn(f"No reservation {rid(9)} on this account", unknown.stderr)+ self.assertEqual(len(FakeApi.requests), 1) # the API's own "No such reservation" needs no second look+ FakeApi.fail = (404, {"error": "no route GET /reservations/" + rid(9)}, None) # a 404 in other words+ odd = self.run_cli("reservations", rid(9))+ self.assertEqual(odd.returncode, 1)+ self.assertIn(f"No reservation {rid(9)} on this account", odd.stderr)+ self.assertNotIn("does not take reservations yet", odd.stderr)+ self.assertEqual([req[:2] for req in FakeApi.requests[1:]],+ [("GET", "/reservations/" + rid(9)), ("GET", "/reservations")])++ def test_a_stripe_outage_says_how_to_retry_the_same_reservation(self):+ FakeApi.fail = (502, {"error": "Stripe could not complete this request; try again shortly.",+ "code": "payments_unavailable"}, None)+ r = self.reserve()+ self.assertEqual(r.returncode, 1)+ key = FakeApi.requests[0][2]["idempotency-key"]+ self.assertIn("Stripe could not complete this request", r.stderr)+ self.assertIn("Nothing was charged", r.stderr)+ self.assertIn(f"--idempotency-key {key}", r.stderr)++ def test_a_lost_answer_is_asked_for_again_under_the_same_key(self):+ FakeApi.drop = 1+ r = self.reserve("--qty", "2")+ self.assertEqual(r.returncode, 0, r.stderr)+ first, second = FakeApi.requests+ self.assertEqual(first[2]["idempotency-key"], second[2]["idempotency-key"])+ self.assertEqual(first[3], second[3])+ self.assertEqual(len(FakeApi.rows), 1) # one reservation, not two+ self.assertIn(f"Reservation {rid(1)} started", r.stdout)++ def test_an_answer_that_is_not_a_reservation_is_not_printed_as_one(self):+ for answer in ({}, {"ok": True}, []):+ with self.subTest(answer=answer):+ FakeApi.fail = (200, answer, None)+ r = self.reserve()+ self.assertEqual(r.returncode, 1, r.stdout)+ self.assertIn("answered with something that is not a reservation", r.stderr)+ self.assertIn("--idempotency-key " + FakeApi.requests[-1][2]["idempotency-key"], r.stderr)+ self.assertEqual(r.stdout, "")+ FakeApi.fail = (200, [], None) # and a list that is not the list+ listing = self.run_cli("reservations")+ self.assertEqual(listing.returncode, 0, listing.stderr)+ self.assertIn("No reservations.", listing.stdout)++ def test_an_unreachable_api_says_so_and_how_to_continue(self):+ FakeApi.drop = 2+ r = self.reserve()+ self.assertEqual(r.returncode, 1)+ self.assertIn(f"Could not reach {self.api}", r.stderr)+ key = FakeApi.requests[0][2]["idempotency-key"]+ self.assertIn(f"--idempotency-key {key}", r.stderr)+ self.assertEqual(r.stdout, "")+ down = self.run_cli("reservations", env={"PHONE_HARNESS_CLOUD_API": "http://127.0.0.1:1"})+ self.assertEqual(down.returncode, 1)+ self.assertIn("Could not reach http://127.0.0.1:1", down.stderr)+++class Reservations(ReserveCase):+ def test_the_list_has_every_column_and_lines_up(self):+ self.hold(+ reservation(1, "iphone", "monthly", 3, "queued", position=4, paid_days_ago=2),+ reservation(2, "iphone_esim", "annual", 1, "pending_payment"),+ reservation(3, "android", "monthly", 2, "cancelled", paid_days_ago=5),+ reservation(4, "iphone", "monthly", 3, "queued", position=1, granted=1, paid_days_ago=9),+ reservation(5, "iphone", "annual", 1, "granted", granted=1, paid_days_ago=30),+ reservation(6, "iphone", "monthly", 2, "cancelling", paid_days_ago=1),+ reservation(7, "iphone", "monthly", 1, "cancelled"),+ reservation(8, "iphone", "monthly", 1, "ended", granted=1, paid_days_ago=90),+ )+ r = self.run_cli("reservations")+ self.assertEqual(r.returncode, 0, r.stderr)+ header, *rows, note = r.stdout.splitlines()+ self.assertEqual(header.split(), ["ID", "TYPE", "PLAN", "QTY", "STATUS", "POSITION", "DEPOSIT", "PAID"])+ self.assertEqual([row.split()[0] for row in rows], [rid(n) for n in (8, 7, 6, 5, 4, 3, 2, 1)]) # newest first+ cells = {row.split()[0]: [row[header.index(name):].split(" ")[0].strip() for name in header.split()]+ for row in rows}+ self.assertEqual(cells[rid(1)], [rid(1), "iphone", "monthly", "3", "queued", "4", "$60.00 paid",+ "2 days ago"])+ self.assertEqual(cells[rid(2)], [rid(2), "iphone-esim", "annual", "1", "pending_payment", "-",+ "$20.00 due", "-"])+ # A phone this CLI does not reserve, made elsewhere: the API's own word for it.+ self.assertEqual(cells[rid(3)][1:], ["android", "monthly", "2", "cancelled", "-", "$40.00 refunded",+ "5 days ago"])+ self.assertEqual(cells[rid(4)][4:], ["queued", "1", "$60.00 paid, $40.00 refundable", "9 days ago"])+ self.assertEqual(cells[rid(5)][4:], ["granted", "-", "$20.00 credited", "30 days ago"])+ self.assertEqual(cells[rid(6)][4:], ["cancelling", "-", "$40.00 refund pending", "1 day ago"])+ self.assertEqual(cells[rid(7)][4:], ["cancelled", "-", "-", "-"])+ self.assertEqual(cells[rid(8)][4:], ["ended", "-", "$20.00 credited", "90 days ago"])+ self.assertIn("pending_payment holds no place until its deposit is paid", note)+ self.assertNotIn(CHECKOUT, r.stdout) # a link is shown with one reservation, not in the list+ [(method, path, headers, _body)] = FakeApi.requests+ self.assertEqual((method, path, headers["authorization"]), ("GET", "/reservations", f"Bearer {KEY}"))++ def test_an_empty_list_and_the_list_as_json(self):+ empty = self.run_cli("reservations")+ self.assertEqual(empty.returncode, 0, empty.stderr)+ self.assertIn("No reservations. `phone-harness cloud reserve` starts one.", empty.stdout)+ self.assertEqual(json.loads(self.run_cli("reservations", "--json").stdout), [])+ self.hold(reservation(1, status="queued", position=2, paid_days_ago=1), reservation(2))+ listed = json.loads(self.run_cli("reservations", "--json").stdout)+ self.assertEqual([row["reservation_id"] for row in listed], [rid(2), rid(1)])+ self.assertEqual(listed[1]["deposit"]["paid_cents"], 2000)+ self.assertEqual(listed[0]["checkout_url"], CHECKOUT + "000002")++ def test_one_reservation_by_id_or_by_a_unique_prefix(self):+ self.hold(reservation(1, quantity=3, status="queued", position=4, paid_days_ago=2),+ reservation(2, "iphone_esim", "annual", 1),+ reservation(FAR, quantity=3, status="queued", position=1, granted=1, paid_days_ago=9))+ r = self.run_cli("reservations", rid(1))+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertEqual(FakeApi.requests[-1][:2], ("GET", "/reservations/" + rid(1)))+ for line in (f"reservation {rid(1)}", "status queued",+ "You are in the queue. Cancel any time and the deposit comes back in full.",+ "phones 3 x iPhone, monthly", "position 4 in the queue",+ "deposit $60.00 paid", "paid 2 days ago",+ "first month 1 x $50.00 intro price, once per customer",+ "$210.00 in all; $150.00 due at handover, after the deposit",+ f"cancel phone-harness cloud reservations cancel {rid(1)}"):+ self.assertIn(line, r.stdout)+ self.assertNotIn("checkout.stripe.com", r.stdout)++ unpaid = self.run_cli("reservations", rid(2))+ self.assertIn("status pending_payment", unpaid.stdout)+ self.assertIn("deposit $20.00 due now (1 x $20.00), refundable in full while queued", unpaid.stdout)+ self.assertIn("pay " + CHECKOUT + "000002", unpaid.stdout)++ partly = self.run_cli("reservations", "rsv_a1") # a prefix: looked up in the list+ self.assertEqual(partly.returncode, 0, partly.stderr)+ self.assertEqual(FakeApi.requests[-1][:2], ("GET", "/reservations"))+ self.assertIn("handed over 1 of 3; 2 still waiting", partly.stdout)+ self.assertNotIn("the plan has ended", partly.stdout)+ self.assertIn("deposit $60.00 paid, $40.00 refundable", partly.stdout)+ self.assertIn("paid 9 days ago", partly.stdout)++ as_json = self.run_cli("reservations", rid(2), "--json")+ self.assertEqual(json.loads(as_json.stdout)["reservation_id"], rid(2))++ several = self.run_cli("reservations", "rsv_0000")+ self.assertEqual(several.returncode, 1)+ self.assertIn("'rsv_0000' matches 2 reservations", several.stderr)+ self.assertIn(rid(2), several.stderr)+ for unknown in (rid(99), "rsv_ffff", "nope"):+ missing = self.run_cli("reservations", unknown)+ self.assertEqual(missing.returncode, 1, unknown)+ self.assertIn("phone-harness cloud reservations` lists them", missing.stderr)+ self.assertIn(f"No reservation {rid(99)} on this account", self.run_cli("reservations", rid(99)).stderr)++ def test_a_reservation_for_a_phone_this_cli_does_not_reserve_is_still_shown_and_cancelled(self):+ # One made while an Android was still offered stays on the account.+ # It has no price, so its quote is the deposit alone.+ self.hold(reservation(1, "android", "monthly", 2, "queued", position=3, paid_days_ago=1))+ one = self.run_cli("reservations", rid(1))+ self.assertEqual(one.returncode, 0, one.stderr)+ for line in ("status queued", "phones 2 x android, monthly", "position 3 in the queue",+ "deposit $40.00 paid", "first month price confirmed before handover"):+ self.assertIn(line, one.stdout)+ self.assertNotIn("in all", one.stdout)+ gone = self.run_cli("reservations", "cancel", rid(1), "--yes")+ self.assertEqual(gone.returncode, 0, gone.stderr)+ self.assertIn(f"Reservation {rid(1)} cancelled. $40.00 is on its way back to the card that paid.",+ gone.stdout)++ def test_usage_for_words_it_does_not_take(self):+ for args in (["reservations", rid(1), rid(2)], ["reservations", "cancel"],+ ["reservations", "cancel", rid(1), rid(2)], ["reservations", "--yes"],+ ["reservations", rid(1), "--yes"]):+ r = self.run_cli(*args)+ self.assertEqual(r.returncode, 1, args)+ self.assertIn("Usage: phone-harness cloud reservations [ID] [--json]", r.stderr)+ self.assertEqual(FakeApi.requests, [])+++class Cancel(ReserveCase):+ def test_cancel_without_yes_says_what_it_would_do_and_does_nothing(self):+ self.hold(reservation(1, quantity=2, status="queued", position=4, paid_days_ago=2))+ r = self.run_cli("reservations", "cancel", rid(1))+ self.assertEqual(r.returncode, 1)+ self.assertIn(f"Reservation {rid(1)}: 2 x iPhone, monthly, position 4 in the queue.", r.stderr)+ self.assertIn("gives up that place and refunds $40.00 to the card that paid", r.stderr)+ self.assertIn(f"Not cancelled. To confirm, run: phone-harness cloud reservations cancel {rid(1)} --yes",+ r.stderr)+ self.assertEqual(self.sent("POST"), [])+ self.assertEqual(FakeApi.rows[rid(1)]["status"], "queued")+ as_json = self.run_cli("reservations", "cancel", rid(1), "--json") # --json never asks+ self.assertEqual((as_json.returncode, as_json.stdout), (1, ""))+ self.assertEqual(self.sent("POST"), [])++ def test_cancel_refunds_the_deposit_and_says_how_much(self):+ self.hold(reservation(1, quantity=2, status="queued", position=4, paid_days_ago=2))+ r = self.run_cli("reservations", "cancel", rid(1), "--yes")+ self.assertEqual(r.returncode, 0, r.stderr)+ [(method, path, headers, body)] = self.sent("POST")+ self.assertEqual((method, path, body), ("POST", f"/reservations/{rid(1)}/cancel", None))+ self.assertEqual(headers["authorization"], f"Bearer {KEY}")+ self.assertIn(f"Reservation {rid(1)} cancelled. $40.00 is on its way back to the card that paid.",+ r.stdout)+ self.assertIn("You left the queue and the deposit was refunded in full.", r.stdout)+ again = self.run_cli("reservations", "cancel", rid(1), "--yes") # twice refunds once+ self.assertEqual(again.returncode, 0, again.stderr)+ self.assertIn(f"Reservation {rid(1)} was already cancelled. Nothing to refund.", again.stdout)++ def test_cancel_by_prefix_and_as_json(self):+ self.hold(reservation(1), reservation(FAR, quantity=1, status="queued", position=1, paid_days_ago=1))+ r = self.run_cli("reservations", "cancel", "rsv_a1", "--yes", "--json")+ self.assertEqual(r.returncode, 0, r.stderr)+ done = json.loads(r.stdout)+ self.assertEqual((done["reservation_id"], done["status"], done["refunded_cents"]),+ (rid(FAR), "cancelled", 2000))+ self.assertEqual([req[:2] for req in FakeApi.requests],+ [("GET", "/reservations"), ("POST", f"/reservations/{rid(FAR)}/cancel")])+ self.assertEqual(FakeApi.rows[rid(1)]["status"], "pending_payment") # the other one is untouched++ def test_an_unpaid_reservation_is_cancelled_with_nothing_to_refund(self):+ self.hold(reservation(1, quantity=3))+ asked = self.run_cli("reservations", "cancel", rid(1))+ self.assertIn("deposit not paid", asked.stderr)+ self.assertIn("Nothing was charged, so nothing is refunded", asked.stderr)+ r = self.run_cli("reservations", "cancel", rid(1), "--yes")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn(f"Reservation {rid(1)} cancelled. Nothing had been charged.", r.stdout)+ self.assertNotIn("on its way back", r.stdout)++ def test_a_cancel_after_the_grant_is_refused_in_the_apis_words(self):+ self.hold(reservation(1, status="granted", granted=1, paid_days_ago=20))+ r = self.run_cli("reservations", "cancel", rid(1)) # nothing to confirm: the API decides+ self.assertEqual(r.returncode, 1)+ self.assertEqual(len(self.sent("POST", "/cancel")), 1)+ self.assertIn("Not cancelled. " + GRANTED_REFUSAL, r.stderr)+ self.assertEqual(r.stdout, "")+ self.assertEqual(FakeApi.rows[rid(1)]["status"], "granted")+ self.assertEqual(FakeApi.rows[rid(1)]["deposit"]["refunded_cents"], 0)++ def test_a_plan_that_has_ended_says_so_and_cannot_be_cancelled(self):+ self.hold(reservation(1, quantity=2, status="ended", granted=2, paid_days_ago=90))+ shown = self.run_cli("reservations", rid(1))+ self.assertEqual(shown.returncode, 0, shown.stderr)+ for line in ("status ended", "The plan for this phone has ended.",+ "handed over 2 of 2; the plan has ended for 2", "deposit $40.00 credited"):+ self.assertIn(line, shown.stdout)+ self.assertNotIn("cancel phone-harness", shown.stdout)+ self.assertNotIn("still waiting", shown.stdout)+ r = self.run_cli("reservations", "cancel", rid(1))+ self.assertEqual(r.returncode, 1)+ self.assertIn("Not cancelled. " + GRANTED_REFUSAL, r.stderr)++ def test_a_grant_in_progress_and_a_refund_stripe_did_not_confirm(self):+ self.hold(reservation(1, quantity=2, status="queued", position=1, paid_days_ago=3))+ busy = (409, {"error": "Your phone is being handed over right now. Try again in a few minutes.",+ "code": "grant_in_progress", "retry_after_seconds": 120}, {"Retry-After": "120"})+ unconfirmed = (502, {**reservation(1, quantity=2, status="cancelling", paid_days_ago=3),+ "code": "refund_unconfirmed",+ "error": "You have left the queue, but the refund could not be started. "+ "Try again in a few minutes."}, None)+ outage = (502, {"error": "Stripe could not complete this request; try again shortly.",+ "code": "payments_unavailable"}, None)+ for fail, needles in ((busy, ["Not cancelled. Your phone is being handed over right now."]),+ (unconfirmed, ["the refund could not be started", "never refunds twice",+ f"phone-harness cloud reservations cancel {rid(1)} --yes"]),+ (outage, ["Stripe could not complete this request", "Nothing changed",+ f"phone-harness cloud reservations cancel {rid(1)} --yes"])):+ with self.subTest(code=fail[1]["code"]):+ r = self._cancel_failing(fail)+ self.assertEqual(r.returncode, 1, r.stdout)+ for needle in needles:+ self.assertIn(needle, r.stderr)+ self.assertEqual(r.stdout, "")++ def _cancel_failing(self, fail):+ """A confirmed cancel whose POST answers `fail`. The read before it still works."""+ original = FakeApi._cancel++ def refused(handler, row):+ return handler._send(*fail)+ FakeApi._cancel = refused+ try:+ return self.run_cli("reservations", "cancel", rid(1), "--yes")+ finally:+ FakeApi._cancel = original++ def test_part_handed_over_refunds_only_the_phones_still_waiting(self):+ self.hold(reservation(1, quantity=3, status="queued", position=1, granted=1, paid_days_ago=9))+ asked = self.run_cli("reservations", "cancel", rid(1))+ self.assertIn("gives up the 2 still waiting and refunds $40.00", asked.stderr)+ self.assertIn("What was already handed over (1 of 3) is not affected.", asked.stderr)+ r = self.run_cli("reservations", "cancel", rid(1), "--yes")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn(f"Left the queue for the phones still waiting on {rid(1)}.", r.stdout)+ self.assertIn("$40.00 is on its way back to the card that paid.", r.stdout)+ self.assertIn("1 phone handed over. You left the queue for the other 2", r.stdout)++ def test_a_refund_still_owed_is_retried_without_asking_again(self):+ self.hold(reservation(1, quantity=2, status="cancelling", paid_days_ago=3))+ r = self.run_cli("reservations", "cancel", rid(1)) # they already said yes once+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertEqual(len(self.sent("POST", "/cancel")), 1)+ self.assertIn("cancelled. $40.00 is on its way back", r.stdout)++ def test_cancelling_someone_elses_or_nobodys_reservation(self):+ r = self.run_cli("reservations", "cancel", rid(42), "--yes")+ self.assertEqual(r.returncode, 1)+ self.assertIn(f"No reservation {rid(42)} on this account", r.stderr)+ self.assertEqual(self.sent("POST"), [])+++class NotFound(BaseHTTPRequestHandler):+ """A stub of an API from before reservations: every request is a 404."""+ # What that 404 can look like. The first is phone-cloud's own (a signed-in+ # request for a path it does not have); the rest are what a proxy or an+ # older server in front of it might say instead.+ KINDS = {+ "the API's own": (b'{"error": "no route %s %s"}', "application/json"),+ "a page": (b"<html><body><h1>404 Not Found</h1></body></html>", "text/html"),+ "nothing": (b"", "text/plain"),+ "other JSON": (b'{"detail": "Not Found"}', "application/json"),+ }+ kind = "the API's own"+ seen = []++ def log_message(self, *a):+ pass++ def _answer(self):+ n = int(self.headers.get("Content-Length") or 0)+ if n:+ self.rfile.read(n)+ NotFound.seen.append((self.command, self.path))+ body, content_type = NotFound.KINDS[NotFound.kind]+ raw = body % (self.command.encode(), self.path.encode()) if b"%s" in body else body+ self.send_response(404)+ self.send_header("Content-Type", content_type)+ self.send_header("Content-Length", str(len(raw)))+ self.end_headers()+ self.wfile.write(raw)++ do_GET = do_POST = do_DELETE = _answer+++class NoReservationsYet(ReserveCase):+ """Until reservations are live, every path under /reservations is a 404. Each command has to+ say that, and never "no reservation of yours has that id"."""++ def setUp(self):+ super().setUp()+ stub = ThreadingHTTPServer(("127.0.0.1", 0), NotFound)+ threading.Thread(target=stub.serve_forever, daemon=True).start()+ self.addCleanup(stub.server_close)+ self.addCleanup(stub.shutdown)+ self.stub = f"http://127.0.0.1:{stub.server_port}"+ self.env["PHONE_HARNESS_CLOUD_API"] = self.stub++ def test_every_command_says_the_api_does_not_take_reservations_yet(self):+ said = f"{self.stub} does not take reservations yet, so a phone cannot be reserved, listed or cancelled through it. Nothing was changed."+ commands = {+ "reserve": (["reserve", "--type", "iphone", "--plan", "monthly", "--use-case", USE_CASE],+ [("POST", "/reservations")]),+ "reserve --json --open": (["reserve", "--type", "iphone-esim", "--plan", "annual", "--qty", "3",+ "--use-case", USE_CASE, "--json", "--open"], [("POST", "/reservations")]),+ "reservations": (["reservations"], [("GET", "/reservations")]),+ "reservations --json": (["reservations", "--json"], [("GET", "/reservations")]),+ "reservations ID": (["reservations", rid(1)],+ [("GET", "/reservations/" + rid(1)), ("GET", "/reservations")]),+ "reservations PREFIX": (["reservations", "rsv_00"], [("GET", "/reservations")]),+ "cancel ID": (["reservations", "cancel", rid(1)],+ [("GET", "/reservations/" + rid(1)), ("GET", "/reservations")]),+ "cancel ID --yes": (["reservations", "cancel", rid(1), "--yes"],+ [("GET", "/reservations/" + rid(1)), ("GET", "/reservations")]),+ "cancel ID --yes --json": (["reservations", "cancel", rid(1), "--yes", "--json"],+ [("GET", "/reservations/" + rid(1)), ("GET", "/reservations")]),+ }+ for kind in NotFound.KINDS:+ for name, (args, asked) in commands.items():+ with self.subTest(kind=kind, command=name):+ NotFound.kind, NotFound.seen = kind, []+ r = self.run_cli(*args)+ self.assertEqual(r.returncode, 1, r.stdout)+ self.assertEqual(r.stderr.strip(), said)+ self.assertEqual(r.stdout, "")+ for wrong in ("No reservation", "on this account", "no route", "404", "Not Found"):+ self.assertNotIn(wrong, r.stderr)+ self.assertEqual(NotFound.seen, asked) # a 404 for one id: is it the id, or the API?+ self.assertEqual(browser_recorder.recorder.urls(), [])+ self.assertEqual(FakeApi.requests, []) # nothing went anywhere else+++class AtATerminal(unittest.TestCase):+ """The confirmation a person gets. In-process: a subprocess has no terminal."""++ def setUp(self):+ self.row = reservation(1, quantity=2, status="queued", position=4, paid_days_ago=2)+ self.calls = []++ def api(self, method, path, body=None, **kw):+ self.calls.append((method, path))+ if method == "GET":+ return self.row+ return {**reservation(1, quantity=2, status="cancelled", paid_days_ago=2), "refunded_cents": 4000}++ def cancel(self, answer, *args):+ terminal = mock.Mock()+ terminal.isatty.return_value = True+ out = io.StringIO()+ with mock.patch.object(cloud, "_api", self.api), mock.patch.object(sys, "stdin", terminal), \+ mock.patch("builtins.input", return_value=answer) as asked, contextlib.redirect_stdout(out):+ code = cloud.cli(["reservations", "cancel", rid(1), *args])+ return code, out.getvalue(), asked++ def test_no_is_the_default_and_leaves_it_alone(self):+ for answer in ("", "n", "no", "maybe"):+ self.calls = []+ code, out, asked = self.cancel(answer)+ self.assertEqual(code, 1, answer)+ asked.assert_called_once_with("Cancel this reservation? [y/N] ")+ self.assertIn("refunds $40.00 to the card that paid", out)+ self.assertIn("Not cancelled.", out)+ self.assertEqual(self.calls, [("GET", "/reservations/" + rid(1))])++ def test_yes_cancels(self):+ for answer in ("y", "YES"):+ self.calls = []+ code, out, _asked = self.cancel(answer)+ self.assertEqual(code, 0, out)+ self.assertEqual(self.calls, [("GET", "/reservations/" + rid(1)),+ ("POST", f"/reservations/{rid(1)}/cancel")])+ self.assertIn("$40.00 is on its way back", out)++ def test_the_flag_skips_the_question(self):+ code, _out, asked = self.cancel("n", "--yes")+ self.assertEqual(code, 0)+ asked.assert_not_called()+ self.assertEqual(len(self.calls), 2)+++class Shapes(unittest.TestCase):+ """What is printed for answers the fake does not make on its own."""++ def test_money_is_whatever_currency_the_api_names(self):+ self.assertEqual(cloud._amount(2000), "$20.00")+ self.assertEqual(cloud._amount(201600, "usd"), "$2,016.00")+ self.assertEqual(cloud._amount(2000, "eur"), "20.00 EUR")+ self.assertEqual(cloud._amount(None), "?")++ def test_a_quote_is_only_what_the_api_sent(self):+ row = reservation(1, quantity=2, intro=False) # the intro phone was used before+ self.assertEqual(cloud._quote_rows(row), [+ ("deposit", "$40.00 due now (2 x $20.00), refundable in full while queued"),+ ("first month", "2 x $80.00 standard price"),+ ("", "$160.00 in all; $120.00 due at handover, after the deposit")])+ bare = {"quote": {"currency": "usd", "interval": "month", "priced": False, "lines": [],+ "deposit": {"per_phone_cents": None, "phones": 1, "total_cents": None}}}+ self.assertEqual(cloud._quote_rows(bare), [("first month", "price confirmed before handover")])+ self.assertEqual(cloud._quote_rows({}), [("first period", "price confirmed before handover")])++ def test_a_checkout_link_has_to_be_stripes(self):+ good = "https://checkout.stripe.com/c/pay/cs_live_a1B2#fragment"+ self.assertEqual(cloud._checkout_url({"checkout_url": good}), good)+ for bad in (None, "", 7, "https://checkout.stripe.com/c/pay/x\n", "https://CHECKOUT.stripe.com.evil.example/",+ "https://[email protected]/pay", "javascript:alert(1)", "https://[bad"):+ self.assertIsNone(cloud._checkout_url({"checkout_url": bad}), bad)++ def test_a_deposit_in_a_few_words_follows_the_money_not_the_status(self):+ later = {**reservation(1, quantity=2, status="granted", granted=2, paid_days_ago=3), "status": "paused"}+ self.assertEqual(cloud._deposit_words(later), "$40.00 credited") # a status this CLI has not met+ odd = {"status": "paused", "deposit": {"paid_cents": 4000, "currency": "usd"}}+ self.assertEqual(cloud._deposit_words(odd), "$40.00 paid")+ self.assertEqual(cloud._deposit_words({"status": "queued"}), "-")+ self.assertEqual(cloud._deposit_words({"status": "pending_payment"}), "due")++ def test_how_far_off_a_time_is(self):+ now = time.time()+ self.assertEqual(cloud._in(now + 86400), "24 hours")+ self.assertEqual(cloud._in(now + 30 * 60), "30 min")+ self.assertEqual(cloud._in(now + 5 * 86400), "5 days")+ self.assertEqual(cloud._in(now - 5), "expired")+ self.assertEqual(cloud._in(None), "?")++ def test_an_expired_link_says_to_reserve_again(self):+ row = {**reservation(1), "expires_at": time.time() - 60}+ self.assertEqual(cloud._pay_rows(row), [+ ("pay", row["checkout_url"]), ("", "the link has expired; if it no longer opens, reserve again")])+ self.assertIn("no payment link yet", cloud._pay_rows({**row, "checkout_url": None})[0][1])+++class Telemetry(unittest.TestCase):+ def test_nothing_a_person_typed_about_a_reservation_is_recorded(self):+ argv = run._telemetry_argv([+ "cloud", "reserve", "--type", "iphone-esim", "--plan", "annual", "--qty", "3",+ "--use-case", "Our secret launch", "--first-name", "Dana", "--last-name=Okafor",+ "--idempotency-key", "retry-key_0123456789", "--open", "--json"])+ self.assertEqual(argv, [+ "cloud", "reserve", "--type", "iphone-esim", "--plan", "annual", "--qty", "3",+ "--use-case", "<redacted>", "--first-name", "<redacted>", "--last-name=<redacted>",+ "--idempotency-key", "<redacted>", "--open", "--json"])+ self.assertEqual(run._telemetry_argv(["cloud", "reservations", "cancel", rid(7), "--yes"]),+ ["cloud", "reservations", "cancel", "<redacted>", "--yes"])+ self.assertEqual(run._telemetry_argv(["--session", "s1", "cloud", "reservations", "rsv_0000"]),+ ["cloud", "reservations", "<redacted>"])+ self.assertEqual(run._telemetry_argv(["cloud", "reserve", "--type=iphone_esim", "--qty=2", "-secret", "x=y"]),+ ["cloud", "reserve", "--type=iphone_esim", "--qty=2", "<redacted>", "<redacted>"])+ # A type these commands do not take is not one of their fixed words.+ self.assertEqual(run._telemetry_argv(["cloud", "reserve", "--type", "android", "--type=android"]),+ ["cloud", "reserve", "--type", "<redacted>", "--type=<redacted>"])+ # Other commands are recorded as they were.+ self.assertEqual(run._telemetry_argv(["cloud", "start", "Saved phone"]), ["cloud", "start", "Saved phone"])++ def test_every_flag_these_commands_take_is_one_telemetry_keeps(self):+ parsers = cloud._cloud_parsers()+ for name in ("reserve", "reservations"):+ for action in parsers[name]._actions:+ for flag in action.option_strings:+ self.assertIn(flag, run._RESERVATION_FLAGS, f"{name} {flag}")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_cloud_reserve_live.py b/tests/test_cloud_reserve_live.pynew file mode 100644index 0000000..0ff02af--- /dev/null+++ b/tests/test_cloud_reserve_live.py@@ -0,0 +1,388 @@+"""`cloud reserve` and `cloud reservations` against a real phone-cloud running on this machine.++Skipped unless PHONE_CLOUD_LOCAL_STATE names the state file that phone-cloud's+tests/local_reservations.py writes. That script is the real API process on a+throwaway PostgreSQL with Stripe faked, so nothing here reaches Stripe, a card+or a phone. Beside the API it gives a "control" address that does what only+Stripe, or a person at Stripe's page, can do: pay a Checkout, let one run out,+end a plan. test_cloud_reserve.py is the same commands against a fake API.++ # in a phone-cloud checkout that has the reservation API+ python3 tests/local_reservations.py --port 8793 --control 8794 --state /tmp/local-cloud.json+ # here+ PHONE_CLOUD_LOCAL_STATE=/tmp/local-cloud.json \\+ python -m unittest discover tests -p test_cloud_reserve_live.py++Every amount asserted is read from the API's own answers; this file names none.+"""+import json+import os+import subprocess+import sys+import tempfile+import unittest+import urllib.error+import urllib.request+import uuid+from pathlib import Path++SRC = str(Path(__file__).resolve().parents[1] / "src")+SUPPORT = str(Path(__file__).resolve().parent / "support")+if SRC not in sys.path:+ sys.path.insert(0, SRC)+if SUPPORT not in sys.path:+ sys.path.insert(0, SUPPORT)+import browser_recorder+browser_recorder.install()++from phone_harness.cloud import _amount # noqa: E402++STATE = os.environ.get("PHONE_CLOUD_LOCAL_STATE")+USE_CASE = "An integration run of the phone-harness CLI."+++class Local:+ """The local phone-cloud: its API, its operator, and the stand-in for Stripe's side."""++ def __init__(self, path):+ self.state = json.loads(Path(path).read_text())+ self.api, self.control = self.state["api"], self.state["control"]++ @staticmethod+ def http(method, url, body=None, headers=None):+ data = json.dumps(body).encode() if body is not None else None+ req = urllib.request.Request(url, data=data, method=method,+ headers={"Content-Type": "application/json", **(headers or {})})+ try:+ with urllib.request.urlopen(req, timeout=60) as r:+ return r.status, json.loads(r.read() or b"{}")+ except urllib.error.HTTPError as e:+ return e.code, json.loads(e.read() or b"{}")++ def operator(self, method, path, body=None, key=None):+ headers = {"Authorization": "Bearer " + self.state["operator_token"],+ "X-Phone-Cloud-Actor": self.state["operator_actor"]}+ if key:+ headers["Idempotency-Key"] = key+ return self.http(method, self.api + path, body, headers)++ def account(self, name=None):+ """A new account and an API key for it. `name` None is an account with no name on file."""+ # An address of its own, at the made-up domain this local cloud's accounts use.+ domain = self.state["accounts"][0]["email"].partition("@")[2]+ code, made = self.operator("POST", "/admin/users", {+ "email": f"cli-{uuid.uuid4().hex[:12]}@{domain}", "name": name})+ assert code == 201, (code, made)+ code, key = self.operator("POST", f"/admin/users/{made['uid']}/keys", {"label": "cli integration"})+ assert code == 201, (code, key)+ return key["key"]++ def pay(self, rid):+ """A person pays the deposit on Stripe's page, and Stripe's webhook lands."""+ code, paid = self.http("POST", f"{self.control}/pay/{rid}")+ assert (code, paid.get("webhook")) == (200, 200), (code, paid)+ return paid["reservation"]++ def expire(self, rid):+ code, gone = self.http("POST", f"{self.control}/expire/{rid}")+ assert (code, gone.get("webhook")) == (200, 200), (code, gone)++ def queue_row(self, rid):+ code, listed = self.operator("GET", "/admin/reservations")+ assert code == 200, (code, listed)+ return next(row for row in listed["queue"] if row["id"] == rid)++ def grant(self, rid, phones=None):+ """The operator hands phones over: the plan starts and their deposit comes off its first bill."""+ body = {"confirm": self.queue_row(rid)["confirm"], "dry_run": False}+ if phones is not None:+ body["phones"] = phones+ code, done = self.operator("POST", f"/admin/reservations/{rid}/grant", body,+ key="cli-grant-" + uuid.uuid4().hex)+ assert code == 200 and done.get("granted") is True, (code, done)+ return done++ def end_plan(self, subscription):+ code, ended = self.http("POST", f"{self.control}/subscription/{subscription}/cancel")+ assert (code, ended.get("webhook")) == (200, 200), (code, ended)++ def refunds(self, rid):+ code, stripe = self.http("GET", self.control + "/stripe")+ assert code == 200, code+ return [r for r in stripe["refunds"] if (r.get("metadata") or {}).get("reservation_id") == rid]++[email protected](STATE, "set PHONE_CLOUD_LOCAL_STATE to the state file of a local phone-cloud "+ "(its tests/local_reservations.py)")+class LiveReservations(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.local = Local(STATE)+ code, health = cls.local.http("GET", cls.local.api + "/health")+ assert (code, health.get("ok")) == (200, True), "the local phone-cloud is not answering"++ def setUp(self):+ self.home = tempfile.TemporaryDirectory()+ self.addCleanup(self.home.cleanup)+ self.key = self.local.account("Dana Okafor")+ browser_recorder.recorder.reset()++ def run_cli(self, *args, key=None, env=None):+ full = {**os.environ, "PYTHONPATH": SUPPORT + os.pathsep + SRC, "PHONE_HARNESS_HOME": self.home.name,+ "PHONE_HARNESS_TELEMETRY": "0", "PHONE_HARNESS_NO_UPDATE_CHECK": "1",+ "PHONE_HARNESS_CLOUD_API": self.local.api,+ "PHONE_HARNESS_API_KEY": self.key if key is None else key, **(env or {})}+ for name in ("PHONE_HARNESS_SESSION", "BROWSER", "NO_COLOR"):+ full.pop(name, None)+ return subprocess.run([sys.executable, "-m", "phone_harness.run", "cloud", *args],+ capture_output=True, text=True, env=full, stdin=subprocess.DEVNULL)++ def reserve(self, *extra, kind="iphone", plan="monthly", key=None):+ r = self.run_cli("reserve", "--type", kind, "--plan", plan, "--use-case", USE_CASE, "--json", *extra,+ key=key)+ self.assertEqual(r.returncode, 0, r.stderr)+ return json.loads(r.stdout)++ def read(self, rid, key=None):+ r = self.run_cli("reservations", rid, "--json", key=key)+ self.assertEqual(r.returncode, 0, r.stderr)+ return json.loads(r.stdout)++ def test_reserve_pay_list_and_cancel_with_the_deposit_refunded(self):+ made = self.reserve("--qty", "2")+ rid = made["reservation_id"]+ quote, deposit = made["quote"], made["quote"]["deposit"]+ total = deposit["total_cents"]+ self.assertEqual(made["status"], "pending_payment")+ self.assertTrue(made["checkout_url"].startswith("https://checkout.stripe.com/"), made["checkout_url"])+ self.assertEqual((made["phone_type"], made["plan"], made["quantity"]), ("iphone", "monthly", 2))+ self.assertGreater(total, 0)+ self.assertEqual(total, deposit["per_phone_cents"] * 2)+ self.assertEqual(sum(line["quantity"] for line in quote["lines"]), 2)+ self.assertEqual(quote["first_period_cents"],+ sum(line["quantity"] * line["unit_cents"] for line in quote["lines"]))+ self.assertEqual(quote["due_at_handover_cents"], quote["first_period_cents"] - total)+ self.assertIsNone(made["paid_at"])+ self.assertIsNone(made["position"])++ # Unpaid, it holds no place: no position anywhere, and the link is still shown.+ shown = self.run_cli("reservations", rid)+ self.assertEqual(shown.returncode, 0, shown.stderr)+ self.assertIn("status pending_payment", shown.stdout)+ self.assertIn(f"deposit {_amount(total)} due now", shown.stdout)+ self.assertIn("pay " + made["checkout_url"], shown.stdout)+ self.assertNotIn("position", shown.stdout)+ listed = json.loads(self.run_cli("reservations", "--json").stdout)+ self.assertEqual([(row["reservation_id"], row["status"], row["position"]) for row in listed],+ [(rid, "pending_payment", None)])++ # A person pays on Stripe's page; only then is there a place in the queue.+ self.local.pay(rid)+ queued = self.read(rid)+ self.assertEqual(queued["status"], "queued")+ self.assertIsInstance(queued["position"], int)+ self.assertGreaterEqual(queued["position"], 1)+ self.assertIsNotNone(queued["paid_at"])+ self.assertEqual(queued["deposit"]["paid_cents"], total)+ self.assertEqual(queued["deposit"]["refundable_cents"], total)+ self.assertIsNone(queued["checkout_url"])+ table = self.run_cli("reservations")+ row = next(line for line in table.stdout.splitlines() if line.startswith(rid))+ self.assertEqual(row.split()[1:6], ["iphone", "monthly", "2", "queued", str(queued["position"])])+ self.assertIn(f"{_amount(total)} paid", row)++ # Cancelling asks first, and changes nothing until it is confirmed.+ asked = self.run_cli("reservations", "cancel", rid)+ self.assertEqual(asked.returncode, 1)+ self.assertIn(f"refunds {_amount(total)} to the card that paid", asked.stderr)+ self.assertIn(f"phone-harness cloud reservations cancel {rid} --yes", asked.stderr)+ self.assertEqual(self.read(rid)["status"], "queued")+ self.assertEqual(self.local.refunds(rid), [])++ done = self.run_cli("reservations", "cancel", rid, "--yes")+ self.assertEqual(done.returncode, 0, done.stderr)+ self.assertIn(f"Reservation {rid} cancelled. {_amount(total)} is on its way back", done.stdout)+ after = self.read(rid)+ self.assertEqual((after["status"], after["position"], after["can_cancel"]), ("cancelled", None, False))+ self.assertEqual(after["deposit"]["refunded_cents"], total)+ self.assertEqual([refund["amount"] for refund in self.local.refunds(rid)], [total])++ again = self.run_cli("reservations", "cancel", rid, "--yes") # twice refunds once+ self.assertEqual(again.returncode, 0, again.stderr)+ self.assertIn("was already cancelled", again.stdout)+ self.assertEqual(len(self.local.refunds(rid)), 1)++ def test_the_printed_quote_and_open(self):+ r = self.run_cli("reserve", "--type", "iphone-esim", "--plan", "annual", "--qty", "3",+ "--use-case", USE_CASE, "--open")+ self.assertEqual(r.returncode, 0, r.stderr)+ [made] = json.loads(self.run_cli("reservations", "--json").stdout)+ quote = made["quote"]+ self.assertEqual((made["phone_type"], made["plan"], made["quantity"]), ("iphone_esim", "annual", 3))+ self.assertIn(f"Reservation {made['reservation_id']} started: 3 x iPhone with eSIM, annual.", r.stdout)+ self.assertIn("holds no place in the queue until the deposit is paid", r.stdout)+ self.assertIn(f"deposit {_amount(quote['deposit']['total_cents'])} due now "+ f"(3 x {_amount(quote['deposit']['per_phone_cents'])}), refundable in full while queued",+ r.stdout)+ for line in quote["lines"]:+ self.assertIn(f"{line['quantity']} x {_amount(line['unit_cents'])} {line['tier']} price", r.stdout)+ self.assertEqual({line["tier"] for line in quote["lines"]}, {"intro", "standard"})+ self.assertIn(f"{_amount(quote['first_period_cents'])} in all; "+ f"{_amount(quote['due_at_handover_cents'])} due at handover", r.stdout)+ self.assertIn("pay " + made["checkout_url"], r.stdout)+ self.assertEqual(browser_recorder.recorder.urls(), [made["checkout_url"]])+ self.assertIn("opened in your browser", r.stdout)++ def test_a_cancel_after_the_grant_is_refused_and_an_ended_plan_says_so(self):+ made = self.reserve()+ rid, total = made["reservation_id"], made["quote"]["deposit"]["total_cents"]+ self.local.pay(rid)+ granted = self.local.grant(rid)+ after = self.read(rid)+ self.assertEqual((after["status"], after["granted"], after["queued"]), ("granted", 1, 0))+ self.assertEqual(after["deposit"]["credited_cents"], total)+ self.assertEqual((after["deposit"]["refundable_cents"], after["can_cancel"]), (0, False))++ refused = self.run_cli("reservations", "cancel", rid, "--yes")+ self.assertEqual(refused.returncode, 1)+ self.assertIn("Not cancelled.", refused.stderr)+ self.assertIn("handed over", refused.stderr) # the API's own sentence+ self.assertEqual(refused.stdout, "")+ self.assertEqual(self.read(rid)["status"], "granted")+ self.assertEqual(self.local.refunds(rid), [])++ self.local.end_plan(granted["subscription"])+ ended = self.read(rid)+ self.assertEqual((ended["status"], ended.get("ended")), ("ended", 1))+ shown = self.run_cli("reservations", rid)+ self.assertIn("status ended", shown.stdout)+ self.assertIn("the plan has ended for 1", shown.stdout)+ still = self.run_cli("reservations", "cancel", rid, "--yes")+ self.assertEqual(still.returncode, 1)+ self.assertIn("Not cancelled.", still.stderr)+ self.assertEqual(self.local.refunds(rid), [])++ def test_part_handed_over_refunds_only_the_phones_still_waiting(self):+ made = self.reserve("--qty", "3")+ rid, each = made["reservation_id"], made["quote"]["deposit"]["per_phone_cents"]+ self.local.pay(rid)+ self.local.grant(rid, phones=1)+ partly = self.read(rid)+ self.assertEqual((partly["status"], partly["granted"], partly["queued"]), ("queued", 1, 2))+ self.assertEqual(partly["deposit"]["refundable_cents"], each * 2)+ asked = self.run_cli("reservations", "cancel", rid)+ self.assertIn(f"gives up the 2 still waiting and refunds {_amount(each * 2)}", asked.stderr)+ done = self.run_cli("reservations", "cancel", rid, "--yes")+ self.assertEqual(done.returncode, 0, done.stderr)+ self.assertIn(f"Left the queue for the phones still waiting on {rid}.", done.stdout)+ self.assertIn(f"{_amount(each * 2)} is on its way back", done.stdout)+ after = self.read(rid)+ self.assertEqual((after["status"], after["granted"], after["queued"]), ("granted", 1, 0))+ self.assertEqual((after["deposit"]["refunded_cents"], after["deposit"]["credited_cents"]), (each * 2, each))+ self.assertEqual([refund["amount"] for refund in self.local.refunds(rid)], [each * 2])++ def test_the_same_key_is_the_same_reservation(self):+ key = "cli-live-" + uuid.uuid4().hex+ first = self.reserve("--qty", "2", "--idempotency-key", key)+ again = self.reserve("--qty", "2", "--idempotency-key", key)+ self.assertEqual(first["reservation_id"], again["reservation_id"])+ self.assertEqual(first["checkout_url"], again["checkout_url"])+ self.assertEqual(len(json.loads(self.run_cli("reservations", "--json").stdout)), 1)+ other = self.run_cli("reserve", "--type", "iphone", "--plan", "monthly", "--qty", "5",+ "--use-case", USE_CASE, "--idempotency-key", key)+ self.assertEqual(other.returncode, 1)+ self.assertIn("already used for a different request", other.stderr)+ # Paid, the same key says where it stands and offers nothing more to pay.+ self.local.pay(first["reservation_id"])+ paid = self.run_cli("reserve", "--type", "iphone", "--plan", "monthly", "--qty", "2",+ "--use-case", USE_CASE, "--idempotency-key", key, "--open")+ self.assertEqual(paid.returncode, 0, paid.stderr)+ self.assertIn("already exists for this key", paid.stdout)+ self.assertIn("status queued", paid.stdout)+ self.assertNotIn("checkout.stripe.com", paid.stdout)+ self.assertEqual(browser_recorder.recorder.urls(), [])++ def test_a_name_is_optional_and_an_override_is_used(self):+ nameless = self.local.account(None)+ bare = self.reserve(key=nameless) # no name on file and none given: still made+ self.assertEqual(bare["status"], "pending_payment")+ named = self.reserve("--first-name", "Grace", "--last-name", "Hopper", key=nameless)+ mine = self.reserve() # this account has "Dana Okafor" on file+ half = self.reserve("--first-name", "Ada") # one of the two; the other stays the account's+ for made in (bare, named, mine, half):+ self.local.pay(made["reservation_id"])+ rows = [self.local.queue_row(made["reservation_id"]) for made in (bare, named, mine, half)]+ self.assertEqual([row["name"] for row in rows], # what the operator reads+ [None, "Grace Hopper", "Dana Okafor", "Ada Okafor"])+ self.assertEqual({row["use_case"] for row in rows}, {USE_CASE})++ def test_one_account_cannot_read_or_cancel_anothers(self):+ made = self.reserve()+ rid = made["reservation_id"]+ self.local.pay(rid)+ stranger = self.local.account("Bo Stranger")+ self.assertEqual(json.loads(self.run_cli("reservations", "--json", key=stranger).stdout), [])+ for args in (["reservations", rid], ["reservations", "cancel", rid, "--yes"]):+ r = self.run_cli(*args, key=stranger)+ self.assertEqual(r.returncode, 1, args)+ self.assertIn(f"No reservation {rid} on this account", r.stderr)+ self.assertEqual(self.read(rid)["status"], "queued")+ self.assertEqual(self.local.refunds(rid), [])++ def test_too_many_unfinished_reservations_are_refused_until_one_is_paid(self):+ made, refused = [], None+ for _ in range(12):+ r = self.run_cli("reserve", "--type", "iphone", "--plan", "monthly", "--use-case", USE_CASE, "--json")+ if r.returncode:+ refused = r+ break+ made.append(json.loads(r.stdout)["reservation_id"])+ self.assertIsNotNone(refused, "twelve unpaid reservations were all accepted")+ self.assertGreaterEqual(len(made), 2)+ self.assertIn("`phone-harness cloud reservations` lists the unfinished ones", refused.stderr)+ self.assertEqual(refused.stdout, "")+ self.assertEqual(len(json.loads(self.run_cli("reservations", "--json").stdout)), len(made))+ # Giving one up is not a way back in. Paying for one is.+ gone = self.run_cli("reservations", "cancel", made[0], "--yes")+ self.assertEqual(gone.returncode, 0, gone.stderr)+ self.assertIn("Nothing had been charged", gone.stdout)+ still = self.run_cli("reserve", "--type", "iphone", "--plan", "monthly", "--use-case", USE_CASE, "--json")+ self.assertEqual(still.returncode, 1, still.stdout)+ self.local.pay(made[1])+ self.reserve()++ def test_an_android_is_not_reserved_and_the_api_is_never_asked(self):+ r = self.run_cli("reserve", "--type", "android", "--plan", "monthly", "--use-case", USE_CASE)+ self.assertEqual(r.returncode, 1, r.stdout)+ self.assertEqual(r.stderr.splitlines()[0],+ "Reservations are for iPhones only (with or without eSIM). "+ "Cloud Android emulators are on the $20 plan and are not reserved.")+ self.assertEqual(r.stdout, "")+ # Refused here, before the API: the account has no reservation, not even an unpaid one.+ self.assertEqual(json.loads(self.run_cli("reservations", "--json").stdout), [])++ def test_a_checkout_that_ran_out_is_cancelled_with_nothing_charged(self):+ made = self.reserve()+ rid = made["reservation_id"]+ self.local.expire(rid)+ gone = self.read(rid)+ self.assertEqual((gone["status"], gone["paid_at"], gone["checkout_url"]), ("cancelled", None, None))+ self.assertEqual(gone["deposit"]["paid_cents"], 0)+ r = self.run_cli("reservations", "cancel", rid, "--yes")+ self.assertEqual(r.returncode, 0, r.stderr)+ self.assertIn("was already cancelled. Nothing to refund.", r.stdout)+ self.assertEqual(self.local.refunds(rid), [])++ def test_no_sign_in_and_a_key_the_api_refuses(self):+ for args in (["reserve", "--type", "iphone", "--plan", "monthly", "--use-case", USE_CASE],+ ["reservations"]):+ missing = self.run_cli(*args, key="")+ self.assertEqual(missing.returncode, 1, args)+ self.assertIn("Not signed in. Run: phone-harness cloud login", missing.stderr)+ refused = self.run_cli(*args, key="pck_not_a_real_key")+ self.assertEqual(refused.returncode, 1, args)+ self.assertIn("signed out. Run: phone-harness cloud login", refused.stderr)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_pricing_copy.py b/tests/test_pricing_copy.pyindex 32f7ce8..837462c 100644--- a/tests/test_pricing_copy.py+++ b/tests/test_pricing_copy.py@@ -7,16 +7,29 @@ This holds the docs still between those runs. Change a price there first.python -m unittest discover tests -p test_pricing_copy.py"""import re+import sysimport unittestfrom pathlib import PathROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "src"))+from phone_harness.cloud import IPHONES_ONLY # noqa: E402+DOCS = ("README.md", "SKILL.md", "install.md", "onboarding.md", "setup/cloud.md","integrations/hermes/README.md")RATE, GRANT, TRIAL_MINUTES = "5¢", "$5", "100"IPHONE = {"$80", "$100", "$768", "$960"}-FIGURES = {RATE, GRANT, *IPHONE}+# What reserving a phone costs up front. The service reads the amount from+# Stripe and sends it in every quote, so the docs state it once each and say+# the quote is what counts.+DEPOSIT = "$20"+# Which phones are reserved: IPHONES_ONLY, the sentence `cloud reserve` answers+# a request for an Android with. Every doc that explains reserving says it in+# those words. It names a price of its own, the Android plan's.+ANDROID_PLAN = "$20"+RESERVING = ("README.md", "SKILL.md", "install.md", "onboarding.md", "setup/cloud.md", "setup/api.md")+FIGURES = {RATE, GRANT, *IPHONE, DEPOSIT, ANDROID_PLAN}FIGURE = re.compile(r"(?<![\w$])\$\d+(?:,\d{3})*(?:\.\d+)?|(?<![\w.])\d+(?:\.\d+)?¢")@@ -44,6 +57,32 @@ class PricingCopy(unittest.TestCase):self.assertNotRegex(text, r"(?i)iphone[^.|]*\b(not charged|is free)\b", name)self.assertLessEqual(IPHONE, set(FIGURE.findall(read("setup/cloud.md"))))+ def test_the_deposit_is_per_phone_and_refundable_and_the_quote_is_what_counts(self):+ for name in RESERVING:+ text = read(name).replace(IPHONES_ONLY, "") # that figure is the Android plan's+ self.assertEqual(text.count(DEPOSIT), 1, name) # said once, so it changes in one place+ self.assertIn(f"{DEPOSIT} per phone refundable deposit", text, name)+ self.assertRegex(text, r"quote\b[^.]*\bauthoritative", name)+ for name in set(DOCS) - set(RESERVING):+ self.assertNotIn(DEPOSIT, read(name), name)++ def test_only_iphones_are_reserved_and_every_doc_says_so_in_the_same_words(self):+ self.assertIn(f"on the {ANDROID_PLAN} plan", IPHONES_ONLY)+ for name in RESERVING:+ text = read(name)+ self.assertEqual(text.count(IPHONES_ONLY), 1, name)+ # and none lists an Android beside the iPhones as a phone to reserve+ self.assertNotRegex(text, r"(?i)iphone[-_]esim`?(?: \([^)]*\))?,? (?:or|\|) `?android|--type android",+ name)+ for name in set(DOCS) - set(RESERVING):+ self.assertNotIn("Reservations are for", read(name), name)++ def test_the_limit_on_unpaid_reservations_is_stated_where_reserving_is_explained(self):+ for name in ("README.md", "SKILL.md", "setup/cloud.md", "setup/api.md"):+ text = read(name).lower()+ self.assertRegex(text, r"five unpaid reservations an hour", name)+ self.assertRegex(text, r"cancelling one does\s+not free a place", name)+if __name__ == "__main__":unittest.main()diff --git a/tests/test_skill.py b/tests/test_skill.pyindex df5b47e..03f0884 100644--- a/tests/test_skill.py+++ b/tests/test_skill.py@@ -12,6 +12,7 @@ sys.path.insert(0, str(SRC))from phone_harness.run import _skill_text, _write_utf8 # noqa: E402from phone_harness.android import CLI_USAGE as ANDROID_USAGE # noqa: E402from phone_harness.cloud import CLI_USAGE as CLOUD_USAGE # noqa: E402+from phone_harness.cloud import IPHONES_ONLY # noqa: E402from phone_harness.config import CLI_USAGE as CONFIG_USAGEfrom phone_harness.run import USAGE # noqa: E402@@ -68,6 +69,28 @@ class SkillOutput(unittest.TestCase):self.assertIn("`screen_info()`", text)self.assertNotIn("ocr()", text)+ def test_skill_says_how_reserving_a_phone_works(self):+ """What an agent has to get right before it reserves or cancels for someone."""+ section = _skill_text().split("\n## Reserving a cloud phone\n", 1)[1].split("\n## ", 1)[0]+ text = " ".join(section.split())+ for rule in (+ "**Which phones.** " + IPHONES_ONLY, # the sentence `cloud reserve` refuses an Android with+ "`--type` is `iphone`, or `iphone-esim` for one with an eSIM",+ "**Signed in first.**", "phone-harness cloud login", "PHONE_HARNESS_API_KEY",+ "phone-harness.com/get-a-phone", # with no account: the website+ "$20 per phone refundable deposit", "quote the command prints is authoritative",+ "do not quote them from memory",+ "**You never pay.**", "**Nothing is held until the deposit is paid.**",+ "**Queue order is paid time.**", "does not move one up",+ "one phone at the intro price when this customer has not had it yet, the rest at the standard price",+ "The refund is automatic, to the card that paid",+ "part handed over refunds only the phones still waiting",+ "became a credit on the first bill and is no longer refundable",+ "**The website has no list.**", "`cloud reservations` is the list",+ "Cancelling one does not free a place"):+ self.assertIn(rule, text)+ self.assertNotIn("`android`", text) # not a --type+def test_screenshot_prints_the_path_it_returns(self):import contextlib