312 lines
9.4 KiB
Bash
Executable file
312 lines
9.4 KiB
Bash
Executable file
#!/usr/bin/env bash
|
|
# Creates the fixtures used by tests/e2e/basic-sanity.yaml.
|
|
#
|
|
# Usage:
|
|
# ./tests/e2e/basic-sanity-setup.sh
|
|
#
|
|
# Optional environment variables:
|
|
# ADMIN_TOKEN admin bearer token (defaults to /tmp/dev_admin_token)
|
|
# RUN_ID unique suffix for fixture names (defaults to UTC timestamp)
|
|
# IMAGE image uploaded for every product/tag
|
|
# API admin tRPC base URL
|
|
# LOCAL_API local test-support base URL
|
|
#
|
|
# Writes tests/e2e/.basic-sanity.env and tests/e2e/.basic-sanity-state.json.
|
|
# Neither file contains credentials.
|
|
|
|
set -euo pipefail
|
|
|
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
|
cd "$ROOT"
|
|
|
|
API="${API:-https://devbackend.freshyo.in/api/trpc}"
|
|
LOCAL_API="${LOCAL_API:-http://localhost:8787}"
|
|
RUN_ID="${RUN_ID:-$(date -u +%y%m%d%H%M%S)}"
|
|
IMAGE="${IMAGE:-$ROOT/apps/user-ui/assets/images/icon.png}"
|
|
ENV_FILE="$ROOT/tests/e2e/.basic-sanity.env"
|
|
STATE_FILE="$ROOT/tests/e2e/.basic-sanity-state.json"
|
|
DB="$(ls apps/backend/.wrangler/state/v3/d1/miniflare-D1DatabaseObject/*.sqlite 2>/dev/null | head -n 1)"
|
|
TOKEN="${ADMIN_TOKEN:-$(cat /tmp/dev_admin_token 2>/dev/null || true)}"
|
|
|
|
if [[ -z "$TOKEN" ]]; then
|
|
echo "ADMIN_TOKEN is required (or put the token in /tmp/dev_admin_token)" >&2
|
|
exit 1
|
|
fi
|
|
|
|
if [[ ! -f "$IMAGE" ]]; then
|
|
echo "Image not found: $IMAGE" >&2
|
|
exit 1
|
|
fi
|
|
|
|
export API LOCAL_API RUN_ID IMAGE ENV_FILE STATE_FILE DB TOKEN
|
|
|
|
python3 - <<'PY'
|
|
import json
|
|
import os
|
|
import sqlite3
|
|
import urllib.error
|
|
import urllib.request
|
|
from datetime import datetime, timedelta, timezone
|
|
from pathlib import Path
|
|
|
|
API = os.environ["API"].rstrip("/")
|
|
LOCAL_API = os.environ["LOCAL_API"].rstrip("/")
|
|
RUN_ID = os.environ["RUN_ID"]
|
|
IMAGE = os.environ["IMAGE"]
|
|
ENV_FILE = Path(os.environ["ENV_FILE"])
|
|
STATE_FILE = Path(os.environ["STATE_FILE"])
|
|
DB = os.environ["DB"]
|
|
TOKEN = os.environ["TOKEN"]
|
|
|
|
# Drop cart rows left by a previous SANITY run so the new flow starts clean.
|
|
if DB:
|
|
try:
|
|
with sqlite3.connect(DB, timeout=10) as conn:
|
|
conn.execute(
|
|
"DELETE FROM cart_items WHERE sku_id IN ("
|
|
"SELECT id FROM product_skus WHERE product_id IN ("
|
|
"SELECT id FROM product_info WHERE name LIKE 'SANITY-%'))"
|
|
)
|
|
except sqlite3.Error as exc:
|
|
print(f"warning: could not clear stale SANITY cart rows: {exc}")
|
|
|
|
|
|
def request(url, *, method="GET", payload=None, headers=None, raw=None):
|
|
body = raw
|
|
hdrs = {"User-Agent": "freshyo-basic-sanity/1.0"}
|
|
if headers:
|
|
hdrs.update(headers)
|
|
if payload is not None:
|
|
body = json.dumps(payload).encode()
|
|
hdrs["content-type"] = "application/json"
|
|
req = urllib.request.Request(url, data=body, headers=hdrs, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
return resp.status, resp.read()
|
|
except urllib.error.HTTPError as exc:
|
|
detail = exc.read().decode(errors="replace")
|
|
raise SystemExit(f"{method} {url} failed ({exc.code}): {detail}") from exc
|
|
|
|
|
|
def trpc(procedure, payload):
|
|
status, data = request(
|
|
f"{API}/{procedure}",
|
|
method="POST",
|
|
payload=payload,
|
|
headers={"authorization": f"Bearer {TOKEN}"},
|
|
)
|
|
parsed = json.loads(data)
|
|
if "error" in parsed:
|
|
raise SystemExit(f"{procedure} failed: {json.dumps(parsed['error'])}")
|
|
return parsed["result"]["data"]
|
|
|
|
|
|
def upload(url):
|
|
data = Path(IMAGE).read_bytes()
|
|
status, _ = request(
|
|
url,
|
|
method="PUT",
|
|
raw=data,
|
|
headers={"content-type": "image/png"},
|
|
)
|
|
if status not in (200, 201):
|
|
raise SystemExit(f"upload failed with HTTP {status}")
|
|
|
|
|
|
def iso(dt):
|
|
return dt.strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
|
|
|
|
|
product_name = f"SANITY-{RUN_ID}-A"
|
|
combo_name = f"SANITY-{RUN_ID}-COMBO"
|
|
tag_name = f"SANITY-{RUN_ID}"
|
|
|
|
# 1. Three product images.
|
|
uploads = trpc(
|
|
"common.generateUploadUrls",
|
|
{"contextString": "product_info", "mimeTypes": ["image/png"] * 3},
|
|
)["uploadUrls"]
|
|
for url in uploads:
|
|
upload(url)
|
|
|
|
# 2. Product A with two SKUs (500g flash-eligible, 1kg regular).
|
|
product_a = trpc(
|
|
"admin.product.createProduct",
|
|
{
|
|
"name": product_name,
|
|
"shortDescription": "Basic sanity product A",
|
|
"longDescription": "Created by tests/e2e/basic-sanity-setup.sh",
|
|
"storeId": 1,
|
|
"incrementStep": 1,
|
|
"productType": "item",
|
|
"skus": [
|
|
{
|
|
"price": 199,
|
|
"marketPrice": 249,
|
|
"images": [uploads[0]],
|
|
"isFlashAvailable": True,
|
|
"flashPrice": 149,
|
|
"isOutOfStock": False,
|
|
"isOffer": True,
|
|
"isComboOnly": False,
|
|
"isDeleted": False,
|
|
"isSuspended": False,
|
|
"features": [{"featureName": "quantity", "featureValue": "500g"}],
|
|
"comboItems": [],
|
|
},
|
|
{
|
|
"price": 349,
|
|
"marketPrice": 399,
|
|
"images": [uploads[1]],
|
|
"isFlashAvailable": False,
|
|
"flashPrice": None,
|
|
"isOutOfStock": False,
|
|
"isOffer": True,
|
|
"isComboOnly": False,
|
|
"isDeleted": False,
|
|
"isSuspended": False,
|
|
"features": [{"featureName": "quantity", "featureValue": "1kg"}],
|
|
"comboItems": [],
|
|
},
|
|
],
|
|
},
|
|
)["product"]
|
|
sku_500g, sku_1kg = [sku["id"] for sku in product_a["skus"]]
|
|
product_a_id = product_a["id"]
|
|
|
|
# 3. Combo product containing both A variants.
|
|
combo = trpc(
|
|
"admin.product.createProduct",
|
|
{
|
|
"name": combo_name,
|
|
"shortDescription": "Basic sanity combo",
|
|
"longDescription": "Combo of the two product A variants",
|
|
"storeId": 1,
|
|
"incrementStep": 1,
|
|
"productType": "combo",
|
|
"skus": [
|
|
{
|
|
"price": 499,
|
|
"marketPrice": 549,
|
|
"images": [uploads[2]],
|
|
"isFlashAvailable": True,
|
|
"flashPrice": 399,
|
|
"isOutOfStock": False,
|
|
"isOffer": False,
|
|
"isComboOnly": False,
|
|
"isDeleted": False,
|
|
"isSuspended": False,
|
|
"features": [{"featureName": "quantity", "featureValue": "1 combo"}],
|
|
"comboItems": [{"skuId": sku_500g}, {"skuId": sku_1kg}],
|
|
}
|
|
],
|
|
},
|
|
)["product"]
|
|
sku_combo = combo["skus"][0]["id"]
|
|
combo_id = combo["id"]
|
|
|
|
# 4. Dashboard tag. createProductTag's productIds are product_skus ids.
|
|
try:
|
|
tag = trpc(
|
|
"admin.product.createProductTag",
|
|
{
|
|
"tagName": tag_name,
|
|
"tagDescription": "Basic sanity dashboard tag",
|
|
"isDashboardTag": True,
|
|
"relatedStores": [1],
|
|
"productIds": [sku_500g, sku_1kg, sku_combo],
|
|
"uploadUrls": [],
|
|
},
|
|
)["tag"]
|
|
except SystemExit as exc:
|
|
if "already exists" not in str(exc):
|
|
raise
|
|
existing = trpc("admin.product.getProductTags", {"storeId": 1})
|
|
tags = existing.get("tags", existing) if isinstance(existing, dict) else existing
|
|
tag = next(t for t in tags if t["tagName"] == tag_name)
|
|
tag = trpc(
|
|
"admin.product.updateProductTag",
|
|
{
|
|
"id": tag["id"],
|
|
"productIds": [sku_500g, sku_1kg, sku_combo],
|
|
"relatedStores": [1],
|
|
"isDashboardTag": True,
|
|
},
|
|
)["tag"]
|
|
tag_id = tag["id"]
|
|
|
|
# 5. Slot: delivery in 2 hours, freeze 15 minutes before delivery.
|
|
delivery = datetime.now(timezone.utc) + timedelta(hours=2)
|
|
freeze = delivery - timedelta(minutes=15)
|
|
slot = trpc(
|
|
"admin.slots.createSlot",
|
|
{
|
|
"deliveryTime": iso(delivery),
|
|
"freezeTime": iso(freeze),
|
|
"isActive": True,
|
|
"skuIds": [sku_500g, sku_1kg, sku_combo],
|
|
"vendorSnippets": [],
|
|
"groupIds": [],
|
|
},
|
|
)["slot"]
|
|
slot_id = slot["id"]
|
|
|
|
# 6. Flash on, then rebuild every cache synchronously.
|
|
trpc(
|
|
"admin.region.updateBoundSettings",
|
|
{
|
|
"boundId": 1,
|
|
"settings": [{"key": "isFlashDeliveryEnabled", "value": "true"}],
|
|
},
|
|
)
|
|
|
|
status, rebuild_body = request(
|
|
f"{LOCAL_API}/api/test/rebuild?regionId=1",
|
|
method="POST",
|
|
headers={"authorization": f"Bearer {TOKEN}"},
|
|
)
|
|
if status != 200:
|
|
raise SystemExit(f"cache rebuild failed: {rebuild_body.decode(errors='replace')}")
|
|
|
|
state = {
|
|
"runId": RUN_ID,
|
|
"productName": product_name,
|
|
"comboName": combo_name,
|
|
"tagName": tag_name,
|
|
"productAId": product_a_id,
|
|
"sku500g": sku_500g,
|
|
"sku1kg": sku_1kg,
|
|
"comboId": combo_id,
|
|
"skuCombo": sku_combo,
|
|
"tagId": tag_id,
|
|
"slotId": slot_id,
|
|
"slotDeliveryTime": iso(delivery),
|
|
"slotFreezeTime": iso(freeze),
|
|
"imageUrl": uploads[0],
|
|
"comboImageUrl": uploads[2],
|
|
}
|
|
STATE_FILE.write_text(json.dumps(state, indent=2) + "\n")
|
|
|
|
env_lines = [
|
|
f"RUN_ID={RUN_ID}",
|
|
f"PRODUCT_NAME={product_name}",
|
|
f"COMBO_NAME={combo_name}",
|
|
f"TAG_NAME={tag_name}",
|
|
f"PRODUCT_A_ID={product_a_id}",
|
|
f"SKU_500G={sku_500g}",
|
|
f"SKU_1KG={sku_1kg}",
|
|
f"COMBO_ID={combo_id}",
|
|
f"SKU_COMBO={sku_combo}",
|
|
f"TAG_ID={tag_id}",
|
|
f"SLOT_ID={slot_id}",
|
|
]
|
|
ENV_FILE.write_text("\n".join(env_lines) + "\n")
|
|
|
|
print("Fixtures ready")
|
|
for key, value in state.items():
|
|
if key in {"imageUrl", "comboImageUrl"}:
|
|
continue
|
|
print(f" {key}: {value}")
|
|
print(f" state: {STATE_FILE}")
|
|
print(f" env: {ENV_FILE}")
|
|
PY
|