Workhub / tests /e2e.py
ag235772's picture
files Replacement
e298636
Raw History Blame Contribute Delete
9.1 kB
import base64, json, os, re, sys, tempfile, time
import openpyxl, pyotp
from playwright.sync_api import sync_playwright, expect
BASE = "http://localhost:5055"
OUT = os.environ.get("SHOTS", "/tmp/claude-0/shots"); os.makedirs(OUT, exist_ok=True)
tmp = tempfile.mkdtemp()
# ---- messy past-records workbook
wb = openpyxl.Workbook(); ws = wb.active; ws.title = "Sept 2026"
ws.append(["My log"]); ws.append([])
ws.append(["Date", "Ticket ID", "POC ID", "Product", "Issue", "Remarks"])
ws.append(["25/09/2026", "TKT-1001", None, "WAF", "False positive on login", "tuned rule"])
ws.append([None, "TKT-1002", None, "WAS", "Scan stuck at 40%", "restarted scanner"])
ws.append(["27/09/2026", None, "POC-77", "WAF", "Customer POC kickoff", None])
ws.append(["28/09/2026", "TKT-1003", None, None, "Blocked API call", "need product?"])
n = wb.create_sheet("Notes Oct")
for r in (["5 Oct 2026"], ["ticket 4521 - bypass via encoded payload WAF, fixed rule"], ["POC-88 started for acme.com WAS"], ["6/10/2026"], ["Looked into something weird, no id"]):
n.append(r)
past = os.path.join(tmp, "old_log.xlsx"); wb.save(past)
OVERRIDE = """
window.__hubPickerOverride = {
async save(name){ const r = await navigator.storage.getDirectory(); return r.getFileHandle(name,{create:true}); },
async open(){ const r = await navigator.storage.getDirectory(); return r.getFileHandle('WorkHub_asha.xlsx',{create:false}); } };
"""
errors = []
def watch(page):
page.on("pageerror", lambda e: errors.append("PAGEERROR " + str(e)))
page.on("console", lambda m: m.type == "error" and errors.append("CONSOLE " + m.text))
def dev_login(page, email):
page.goto(BASE); page.click("#msBtn"); page.fill("input[name=email]", email); page.click("button")
with sync_playwright() as p:
b = p.chromium.launch()
ctx = b.new_context(viewport={"width": 1280, "height": 900}); ctx.add_init_script(OVERRIDE)
page = ctx.new_page(); watch(page)
# --- wrong domain
dev_login(page, "bob@gmail.com"); expect(page.locator(".err")).to_contain_text("Only @indusface.com")
# --- register
page.goto(BASE); expect(page.locator("#gateCard")).to_contain_text("isn't registered")
dev_login(page, "asha.k@indusface.com")
expect(page.locator("img.qr")).to_be_visible(); page.screenshot(path=f"{OUT}/1_enroll.png")
secret = page.locator("#gateCard code").inner_text().replace(" ", ""); totp = pyotp.TOTP(secret)
page.fill("#code", "000000"); page.click("#go"); expect(page.locator(".err")).to_contain_text("not correct")
page.fill("#code", totp.now()); page.click("#go")
# --- choose where to save the excel
expect(page.locator("#gateCard")).to_contain_text("Where should your Excel file live"); page.screenshot(path=f"{OUT}/2_chooser.png")
page.click("#mk")
expect(page.locator("#gateCard")).to_contain_text("Do you have past records"); page.click("#yes")
# --- import wizard
page.set_input_files("#file", past); expect(page.locator("#found")).to_contain_text("2 sheet"); page.screenshot(path=f"{OUT}/3_upload.png"); page.click("#next")
expect(page.locator("#gateCard")).to_contain_text("Check how I read"); page.screenshot(path=f"{OUT}/4_structure.png"); page.click("#go")
expect(page.locator("#gateCard")).to_contain_text("Review your records"); page.screenshot(path=f"{OUT}/5_review.png")
cards = page.locator(".rev"); print("cards needing answers:", cards.count())
# answer every flagged card
for i in range(cards.count()):
c = cards.nth(i); src = c.locator(".src").inner_text()
if "Remarks" in src or "Blocked API" in src: c.locator('[data-f=product]').select_option("WAF")
elif "POC-88" in src: pass
elif "weird" in src: c.locator('[data-f=workType]').select_option("Ticket"); c.locator('[data-f=itemId]').fill("TKT-5000"); c.locator('[data-f=product]').select_option("WAS")
else: print("unexpected card:", src)
page.screenshot(path=f"{OUT}/6_review_answered.png")
page.click("#save"); expect(page.locator("#gateCard")).to_contain_text("Import finished"); print(page.locator("#gateCard p").first.inner_text()); page.screenshot(path=f"{OUT}/7_done.png")
page.click("#done"); expect(page.locator("#appShell")).to_be_visible()
# --- log a new entry (yesterday), edit date field
page.fill("#f_date", "2026-10-08"); page.select_option("#f_type", "POC"); page.select_option("#f_product", "WAS")
expect(page.locator("#idLabel")).to_have_text("POC ID"); page.fill("#f_id", "POC-901"); page.fill("#f_title", "Auth scan POC"); page.fill("#f_desc", "Configured login script")
page.click("#saveBtn"); expect(page.locator("#toast")).to_contain_text("Saved to your Excel file")
page.click("[data-tab=records]"); page.wait_for_timeout(500); page.screenshot(path=f"{OUT}/8_records.png")
# --- ask / mail / script
page.click("[data-tab=ask]"); page.fill("#askInput", "weekly report"); page.press("#askInput", "Enter"); expect(page.locator("#askOut")).to_contain_text("Weekly breakdown"); page.screenshot(path=f"{OUT}/9_ask.png")
page.click("[data-tab=mail]"); page.fill("#mailReq", "need follow up mail no response\nticket_id: 77\ncustomer_name: Rahul"); page.click("#mailDraftBtn"); expect(page.locator("#mailOut")).to_have_value(re.compile("Rahul"))
page.click("#mailGood"); expect(page.locator("#toast")).to_contain_text("Learned")
page.click("[data-tab=script]"); page.fill("#scReq", "selenium login script https://x.test/login\nusername: admin\npassword: S3cr'et\"x"); page.click("#scFind"); expect(page.locator("#scOut")).to_have_value(re.compile("admin")); print("script escaped:", "S3cr\\'et" in page.input_value("#scOut"))
# --- read the real xlsx
b64 = page.evaluate("""async()=>{const r=await navigator.storage.getDirectory();const f=await(await r.getFileHandle('WorkHub_asha.k.xlsx')).getFile();const a=new Uint8Array(await f.arrayBuffer());let s='';a.forEach(x=>s+=String.fromCharCode(x));return btoa(s)}""")
path = os.path.join(tmp, "result.xlsx"); open(path, "wb").write(base64.b64decode(b64))
w = openpyxl.load_workbook(path); print("sheets:", w.sheetnames)
assert "2026-09" in w.sheetnames and "2026-10" in w.sheetnames and "Summary" in w.sheetnames and "Weekly" in w.sheetnames
ids = sorted(str(r[6]) for s in ("2026-09", "2026-10") for r in w[s].iter_rows(min_row=2, values_only=True)); print("ids:", ids)
assert "POC-901" in ids and "TKT-5000" in ids and "TKT-1003" in ids and len(ids) == 8, len(ids)
# --- reload keeps working (remembered handle), then sign out + known-device login
page.reload(); expect(page.locator("#appShell")).to_be_visible(); page.click("[data-tab=records]"); expect(page.locator("#statCards")).to_contain_text("8")
page.click("#userBtn"); page.click("[data-m=logout]"); expect(page.locator("#gateCard")).to_contain_text("registered to")
expect(page.locator("#msBtn")).to_contain_text("Sign in"); page.screenshot(path=f"{OUT}/10_known_device.png")
page.click("#msBtn"); page.fill("input[name=email]", "asha.k@indusface.com"); page.click("button")
expect(page.locator("#appShell")).to_be_visible(); print("known device -> straight in, no OTP")
# --- another account on this device is refused
page.click("#userBtn"); page.click("[data-m=logout]"); page.click("#msBtn"); page.fill("input[name=email]", "other@indusface.com"); page.click("button")
expect(page.locator(".err")).to_contain_text("registered to a different account")
# --- brand-new device (fresh browser profile): OTP, then pick existing file
ctx2 = b.new_context(viewport={"width": 1280, "height": 900}); ctx2.add_init_script(OVERRIDE); p2 = ctx2.new_page(); watch(p2)
dev_login(p2, "asha.k@indusface.com"); expect(p2.locator("#gateCard")).to_contain_text("New device detected"); p2.screenshot(path=f"{OUT}/11_otp.png")
p2.fill("#code", "123456"); p2.click("#go"); expect(p2.locator(".err")).to_be_visible()
p2.fill("#code", totp.at(time.time() + 30)); p2.click("#go")
expect(p2.locator("#gateCard")).to_contain_text("Where should your Excel file live")
# simulate copying the file to the new computer
p2.evaluate("""async(b64)=>{const bin=atob(b64);const a=new Uint8Array(bin.length);for(let i=0;i<bin.length;i++)a[i]=bin.charCodeAt(i);const r=await navigator.storage.getDirectory();const h=await r.getFileHandle('WorkHub_asha.xlsx',{create:true});const w=await h.createWritable();await w.write(a);await w.close();}""", b64)
p2.click("#op"); expect(p2.locator("#appShell")).to_be_visible()
p2.click("[data-tab=records]"); expect(p2.locator("#statCards")).to_contain_text("8"); print("new device: all 8 past records visible after attaching file")
p2.click("#userBtn"); p2.click("[data-m=devices]"); expect(p2.locator("#devList .tpl")).to_have_count(2); p2.screenshot(path=f"{OUT}/12_devices.png")
b.close()
unexpected = [e for e in errors if "400 (BAD REQUEST)" not in e] # the two wrong-code attempts are deliberate
print("JS errors (excluding 2 deliberate wrong-code 400s):", unexpected); assert not unexpected and len(errors) == 2
print("E2E OK")