basalt

tests/web.py

"""Framework contract through the public VM and native build entry points."""
from pathlib import Path
import json
import os
import socket
import subprocess
import tempfile
from http_support import listening, exchange

ROOT=Path(__file__).resolve().parents[1]
VM=Path(os.getenv("BASALT", ROOT/"basalt")).resolve()


def request(port, method, path, body=b"", extra=b"", split=False):
    head=(f"{method} {path} HTTP/1.1\r\nHost: localhost\r\nContent-Length: {len(body)}\r\n").encode()
    raw=exchange(port,head+extra+b"\r\n"+body,split)
    first, received=raw.split(b"\r\n\r\n",1)
    status=int(first.split(b" ",2)[1])
    headers={k.lower():v for k,v in (line.split(b": ",1) for line in first.split(b"\r\n")[1:])}
    if method!="HEAD" and status not in (204,304):
        assert int(headers[b"content-length"])==len(received)
    return status,headers,received


APP=(ROOT/"examples/web_api.bas").read_text()
EXTRA='''
FUNCTION Static() AS STRING
    RETURN "fixed"
END FUNCTION
FUNCTION Meta() AS STRING
    CALL WEB_STATUS(201)
    RETURN WEB_HEADER("X-Label","default")
END FUNCTION
FUNCTION RoundTrip() AS STRING
    RETURN WEB_JSON(JSON_PARSE(WEB_BODY() AS Map<String,Int[]>))
END FUNCTION
FUNCTION Broken() AS STRING
    RETURN STRING(3 / INT(WEB_QUERY("n","0")))
END FUNCTION
ROUTE GET "/greet/static" TO Static
ROUTE POST "/meta" TO Meta
ROUTE PUT "/meta" TO Meta
ROUTE PATCH "/meta" TO Meta
ROUTE DELETE "/meta" TO Meta
ROUTE GET "/rank/<label>" TO Greeting
ROUTE GET "/rank/<int:n>" TO Item
ROUTE POST "/json" TO RoundTrip
ROUTE GET "/broken" TO Broken
'''
with tempfile.TemporaryDirectory() as directory:
    work=Path(directory)
    source,binary=work/"service.bas",work/"server"
    source.write_text(APP.replace('CALL WEB_SERVE',EXTRA+'\nCALL WEB_SERVE'))
    subprocess.run(["sh",ROOT/"build-native.sh",source,binary],check=True,
                   env=dict(os.environ,BASALT=str(VM)))
    for cmd in [[VM,"run",source,"0"],[binary,"0"]]:
        with listening(cmd,work) as port:
            assert request(port,"GET","/health")[2]==b"ok"
            assert request(port,"GET","/greet/static")[2]==b"fixed"
            status,h,b=request(port,"GET","/greet/Ada%20L?prefix=Hi+there&prefix=ignored")
            assert status==200 and h[b"content-type"]==b"application/json"
            assert json.loads(b)=={"message":"Hi there, Ada L"}
            assert json.loads(request(port,"GET","/greet/%D7%90")[2])=={"message":"Hello, \u05d0"}
            assert request(port,"GET","/?name=%3Cb%3E%26")[2]==b"<h1>Hello, &lt;b&gt;&amp;</h1>"
            assert request(port,"GET","/items/0004")[2]==b"4"
            assert request(port,"GET","/items/9223372036854775808")[0]==404
            assert request(port,"GET","/items/x")[0]==404
            assert request(port,"GET","/missing")[0]==404
            status,h,b=request(port,"PUT","/health")
            assert status==405 and set(h[b"allow"].split(b", "))=={b"GET",b"HEAD",b"OPTIONS"}
            status,h,b=request(port,"OPTIONS","/sum")
            assert status==204 and b==b"" and h[b"allow"]==b"POST, OPTIONS"
            status,h,b=request(port,"HEAD","/health")
            assert status==200 and b==b"" and h[b"content-length"]==b"2"
            assert request(port,"POST","/meta",extra=b"X-Label: yes\r\n")[::2]==(201,b"yes")
            for verb in ["PUT","PATCH","DELETE"]:
                assert request(port,verb,"/meta")[::2]==(201,b"default")
            assert request(port,"GET","/rank/4")[2]==b"4"
            assert json.loads(request(port,"GET","/rank/abc")[2])=={"message":"Hello, abc"}
            data={'quote"':[1,-2,9223372036854775807],'\x00':[-9223372036854775808]}
            assert json.loads(request(port,"POST","/json",json.dumps(data).encode(),split=True)[2])==data
            assert request(port,"POST","/sum",b"[2,5,-1]",split=True)[2]==b"6"
            for bad in [b"[1,",b'["2"]',b"[9223372036854775808]",b"null",b"true"]:
                assert request(port,"POST","/sum",bad)[0]==400
            assert request(port,"GET","/greet/%GG")[0]==400
            assert request(port,"GET","/broken")[0]==500
            assert request(port,"GET","/broken?n=1")[2]==b"3"
            # Parse a body that arrives after the header section, including 100 Continue.
            with socket.create_connection(("127.0.0.1",port),timeout=5) as s:
                s.sendall(b"POST /sum HTTP/1.1\r\nHost: x\r\nContent-Length: 3\r\nExpect: 100-continue\r\n\r\n")
                with s.makefile("rb") as stream:
                    assert stream.readline()==b"HTTP/1.1 100 Continue\r\n"
                    assert stream.readline()==b"\r\n"
                    s.sendall(b"[3]")
                    assert stream.read().endswith(b"\r\n\r\n3")
            large=json.dumps([1]*10000).encode()
            assert request(port,"POST","/sum",large)[2]==b"10000"
            for n in range(150):
                reply=request(port,"POST","/json",b'{"a":[3,5]}')
                assert json.loads(reply[2])=={"a":[3,5]}
            assert request(port,"GET","/health")[2]==b"ok"

    for declaration,err in [
        ('ROUTE POST "/sum" TO SumNumbers',"duplicate route"),
        ('ROUTE GET "/abc/<int:x>" TO Greeting',"parameter type"),
        ('ROUTE GET "/a/<x>" TO Health',"parameter count"),
        ('ROUTE GET "/a" TO Missing',"handler must"),
        ('ROUTE GET "abc" TO Health',"absolute path"),
        ('ROUTE GET "/bad/<other:x>" TO Greeting',"parameter name")]:
        source.write_text(APP+"\n"+declaration)
        for mode in ["run","emit-c"]:
            p=subprocess.run([VM,mode,source],capture_output=True,text=True,timeout=5)
            assert p.returncode==1 and err in p.stderr, p.stderr
print("PASS: routes, request parsing, JSON, HTML templates, handler recovery, VM and native HTTP")