Skip to content

Single place to convert your 2D floor plans to 3d model (no LLM)

Python
9.8 KB
Raw Blame
"""The server's guards, without Blender: files outside the web folders stay hidden, a plan that is being read or built
cannot be changed or deleted, bad request bodies get an answer, furniture from the review page reaches Blender only
as known items with plain values, the website zip holds the viewer and the house only, and a cover sheet before the
plan is not taken for a scan, and a house built before the build last changed is marked out of date.  python3 tests/test_server.py"""
import json, os, shutil, subprocess, sys, tempfile, threading, urllib.error, urllib.request, zipfile

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path[:0] = [ROOT, os.path.join(ROOT, "examples")]
import make_sample as M  # noqa: E402
import detect, jobs, server, theme_store, themes  # noqa: E402

jobs.JOBS = tempfile.mkdtemp()            # never touch the real jobs folder
themes.DIR, theme_store.THUMBS = tempfile.mkdtemp(), tempfile.mkdtemp()     # nor the real themes and their pictures
theme_store.refresh_thumbs = lambda tid, again=True: None               # (pictures need Blender)
httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), server.H)
threading.Thread(target=httpd.serve_forever, daemon=True).start()
URL = f"http://127.0.0.1:{httpd.server_port}"


def call(method, path, body=None):
    req = urllib.request.Request(URL + path, data=body, method=method)
    try:
        with urllib.request.urlopen(req) as r:
            return r.status, r.read()
    except urllib.error.HTTPError as e:
        return e.code, e.read()


def job(stage):
    jid = os.urandom(6).hex()
    os.makedirs(jobs.jdir(jid))
    jobs.status(jid, stage=stage)
    return jid


try:
    assert call("GET", "/web/..%2fserver.py")[0] == 404
    assert call("GET", "/jobs/" + job("done") + "/..%2f..%2fserver.py")[0] == 404
    busy = job("detecting")
    assert call("DELETE", f"/api/jobs/{busy}")[0] == 409 and os.path.isdir(jobs.jdir(busy))
    assert call("POST", f"/api/jobs/{busy}/plan", b'{"floors": [{}]}')[0] == 409
    done = job("done")
    assert call("POST", f"/api/jobs/{done}/plan", b"[]")[0] == 400
    assert call("POST", f"/api/jobs/{done}/plan", b"not json")[0] == 400
    assert call("POST", f"/api/jobs/{done}/plan", b'{"floors": [{"name": "G"}]}')[0] == 200
    assert json.load(open(os.path.join(jobs.jdir(done), "plan.json")))["floors"][0]["name"] == "G"
    # room finishes and wall colour reach Blender as material names and colours: only known values pass
    plan = lambda room, **kw: json.dumps({"floors": [{"rooms": [room]}], **kw}).encode()
    for bad in (plan({"floor": "lava"}), plan({"floor": ["wood"]}), plan({}, wall_color="red"), plan({}, wall_color="#12345g"),
                plan({}, wall_color="#123456\n"), plan({}, wall_color=None)):
        assert call("POST", f"/api/jobs/{done}/plan", bad)[0] == 400, bad
    assert call("POST", f"/api/jobs/{done}/plan", plan({"floor": "wood"}, wall_color="#C3cdb4"))[0] == 200
    saved = json.load(open(os.path.join(jobs.jdir(done), "plan.json")))
    assert saved["floors"][0]["rooms"][0]["floor"] == "wood" and saved["wall_color"] == "#C3cdb4"
    assert call("POST", f"/api/jobs/{done}/export")[0] == 400           # nothing built yet
    assert call("POST", f"/api/jobs/{done}/site")[0] == 400             # nothing built yet
    assert call("DELETE", f"/api/jobs/{done}")[0] == 200 and not os.path.exists(jobs.jdir(done))
    print("ok   server: hidden files, busy plans, bad bodies, room finishes")

    # furniture: the rules' list until the review page sends its own; an empty list is an empty floor
    jid = job("detected")
    assert call("GET", f"/api/jobs/{jid}/furniture")[0] == 404          # not read yet
    plan = detect.detect(os.path.join(ROOT, "examples", "sample_plan.pdf"))
    json.dump(plan, open(os.path.join(jobs.jdir(jid), "plan.json"), "w"))
    code, out = call("GET", f"/api/jobs/{jid}/furniture")
    out = json.loads(out)
    assert code == 200 and len(out["floors"]) == len(plan["floors"]) and "bed" in out["catalog"], out
    rules = out["floors"][0]
    assert {"bed", "kitchen_run", "wall_cab2"} <= {it["fn"] for it in rules}
    post = lambda p: call("POST", f"/api/jobs/{jid}/plan", json.dumps(p).encode())[0]
    plan["floors"][0]["items"] = rules                                   # the rules' own items pass as they are
    assert post(plan) == 200
    plan["floors"][0]["items"] = []
    assert post(plan) == 200 and json.loads(call("GET", f"/api/jobs/{jid}/furniture")[1])["floors"][0] == []
    bed = next(it for it in rules if it["fn"] == "bed")
    for bad in (dict(bed, fn="model", args=["../../x", 1, 1, 0]), dict(bed, fn="nope"), dict(bed, args=[1, "../x", 0]),
                dict(bed, args=[1, float("nan"), 0]), dict(bed, box=[0, 1, 2]), dict(bed, kw={"w": [5]}),
                dict(bed, kw={"a/b": 1}), dict(bed, kw={"m": "rug\n"}), dict(bed, kw=None), dict(bed, fn=[]), "bed"):
        plan["floors"][0]["items"] = [bad]
        assert post(plan) == 400, bad
    plan["floors"][0]["items"] = [bed] * 401
    assert post(plan) == 400
    plan["floors"][0]["items"] = [dict(bed, args=[1, 2, 90])]
    assert post(plan) == 200
    plan["furnish"] = False
    assert post(plan) == 200 and json.loads(call("GET", f"/api/jobs/{jid}/furniture")[1])["floors"] == [[]] * len(plan["floors"])
    print("ok   server: furniture lists, item checks")

    # the website zip: the viewer, the three.js it loads and the house, and nothing else from the job folder
    built = job("done")
    for f, data in (("meta.json", b'{"lightmaps": {"bake_level_0": "lm_bake_level_0.webp"}}'), ("house.glb", b"glTF"),
                    ("lm_bake_level_0.webp", b"RIFF"), ("source.pdf", b"%PDF"), ("plan.json", b"{}")):
        open(os.path.join(jobs.jdir(built), f), "wb").write(data)
    code, body = call("POST", f"/api/jobs/{built}/site")
    assert code == 200, body
    names = zipfile.ZipFile(os.path.join(jobs.jdir(built), "house_site.zip")).namelist()
    for f in ("index.html", "view.js", "walk.js", "three/build/three.module.js", "three/examples/jsm/libs/draco/draco_decoder.wasm",
              "house/meta.json", "house/house.glb", "house/lm_bake_level_0.webp"):
        assert f in names, f
    assert not [f for f in names if f.endswith(("source.pdf", "plan.json", "status.json"))], names
    print("ok   server: website zip")

    # a title sheet with no drawing before the plan: the plan on page 2 is found, and its page is the one drawn
    cover = os.path.join(jobs.JOBS, "cover.pdf")
    open(cover, "wb").write(M.pdf_page(b""))
    jid = job("uploaded")
    subprocess.run(["pdfunite", cover, os.path.join(ROOT, "examples", "sample_plan.pdf"),
                    os.path.join(jobs.jdir(jid), "source.pdf")], check=True)
    jobs.run_detect(jid)
    st = jobs.read_status(jid)
    assert st["stage"] == "detected", st
    assert sorted(os.listdir(jobs.jdir(jid))) == ["page-2.png", "plan.json", "source.pdf", "status.json"]
    shutil.copy(cover, os.path.join(jobs.jdir(jid), "source.pdf"))
    jobs.run_detect(jid)
    assert "scan" in jobs.read_status(jid)["message"]
    print("ok   server: a cover sheet before the plan, a PDF without lines")

    # interior themes: the built-in ones are listed and fixed; own ones are checked, take .glb models, and can be chosen
    code, out = call("GET", "/api/themes")
    out = json.loads(out)
    assert code == 200 and {"contemporary", "minimalist", "royal", "rustic"} <= {t["id"] for t in out["themes"]}, out
    assert "GothicBed_01" in out["choices"]["bed"]
    for bad in (b"[]", b"{}", b'{"label": "x", "slots": {"bed": "../x"}}', b'{"label": "x", "colours": {"wood": "red"}}'):
        assert call("POST", "/api/themes", bad)[0] == 400, bad
    assert call("POST", "/api/themes/royal", b'{"label": "Mine"}')[0] == 400                 # built-in: not changed
    code, out = call("POST", "/api/themes", b'{"label": "My Royal", "slots": {"bed": "GothicBed_01"}}')
    tid = json.loads(out)["id"]
    assert code == 200 and tid == "my-royal" and os.path.exists(os.path.join(themes.DIR, tid + ".json"))
    assert json.loads(call("POST", "/api/themes", b'{"label": "My Royal"}')[1])["id"] == "my-royal-2"
    assert call("POST", f"/api/themes/{tid}/model/sofa", b"not a glb")[0] == 400
    assert call("POST", f"/api/themes/{tid}/model/sink", b"glTF")[0] == 404                 # not a slot
    assert call("POST", "/api/themes/royal/model/sofa", b"glTF")[0] == 404                   # not your own theme
    assert call("POST", f"/api/themes/{tid}/model/sofa", b"glTF\x02")[0] == 200
    assert themes.load(tid)["slots"]["sofa"] == "upload" and os.path.exists(themes.upload_path(tid, "sofa"))
    assert call("DELETE", f"/api/themes/{tid}/model/sofa")[0] == 200 and themes.load(tid)["slots"]["sofa"] == "@contemporary"
    jid = job("detected")
    for bad in (b'{"floors": [{}], "theme": "nope"}', b'{"floors": [{}], "theme": ["royal"]}', b'{"floors": [{}], "theme": "../x"}'):
        assert call("POST", f"/api/jobs/{jid}/plan", bad)[0] == 400, bad
    assert call("POST", f"/api/jobs/{jid}/plan", json.dumps({"floors": [{}], "theme": tid}).encode())[0] == 200
    assert call("DELETE", "/api/themes/royal")[0] == 404
    assert call("DELETE", f"/api/themes/{tid}")[0] == 200 and tid not in themes.custom_ids()
    print("ok   server: interior themes")

    # a house built before the build last changed is out of date; before a build, each quality says how long it takes
    old, new = job("done"), job("done")
    jobs.status(new, engine=jobs.ENGINE, quality="high", build_seconds=300, floors=["G"])
    get = lambda jid: json.loads(call("GET", f"/api/jobs/{jid}")[1])
    assert get(old)["outdated"] and not get(new)["outdated"]
    assert get(old)["eta"]["high"] == 300           # the last high-quality build here, scaled by storeys (1 + the site)
    assert "outdated" not in get(job("building"))
    print("ok   server: out-of-date houses, build estimates")
finally:
    httpd.shutdown()
    shutil.rmtree(jobs.JOBS)