| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535 |
- package playground
- import (
- "archive/zip"
- "bytes"
- "encoding/json"
- "image"
- "image/color"
- "image/png"
- "strings"
- "testing"
- "time"
- )
- // run is a helper: a WebApp script with the given code and drive.
- func runCode(t *testing.T, code string, files []File, mod func(*Request)) *Result {
- t.Helper()
- req := Request{Script: "web:/Playground/main.agi", Code: code, Files: files, TimeoutSec: 5}
- if mod != nil {
- mod(&req)
- }
- return Run(req, Hooks{})
- }
- func TestResponses(t *testing.T) {
- cases := []struct {
- name, code, want, ctype string
- }{
- {"sendResp", `sendResp("hi")`, "hi", "text/plain"},
- {"echo appends", `echo("a"); echo("b")`, "ab", "text/plain"},
- {"sendOK", `sendOK()`, "ok", "text/plain"},
- {"sendJSONResp object", `sendJSONResp({a:1})`, `{"a":1}`, "application/json"},
- {"sendJSONResp string", `sendJSONResp("[1]")`, `[1]`, "application/json"},
- {"globals", `sendResp(USERNAME + " " + __FILE__)`, "developer web/Playground/main.agi", "text/plain"},
- }
- for _, c := range cases {
- t.Run(c.name, func(t *testing.T) {
- res := runCode(t, c.code, nil, nil)
- if res.Error != nil {
- t.Fatalf("error: %+v", res.Error)
- }
- if res.Response != c.want || res.ContentType != c.ctype {
- t.Errorf("got %q (%s), want %q (%s)", res.Response, res.ContentType, c.want, c.ctype)
- }
- })
- }
- }
- func TestExitKeepsResponse(t *testing.T) {
- res := runCode(t, `sendResp("early"); exit(); sendResp("late")`, nil, nil)
- if !res.Exited || res.Response != "early" {
- t.Fatalf("exit: got %q exited=%v", res.Response, res.Exited)
- }
- }
- func TestScriptErrorAndTimeout(t *testing.T) {
- res := runCode(t, `var a = ; `, nil, nil)
- if res.Error == nil || res.Status != 500 {
- t.Fatalf("syntax error not reported: %+v", res)
- }
- res = runCode(t, `while(true){}`, nil, func(r *Request) { r.TimeoutSec = 1 })
- if res.Error == nil || res.Error.Kind != "timeout" {
- t.Fatalf("timeout not reported: %+v", res.Error)
- }
- }
- func TestConsoleAndRaiseError(t *testing.T) {
- res := runCode(t, `console.log("x", 1); requirelib("filelib"); filelib.readFile("user:/missing.txt");`, nil, nil)
- if len(res.Console) < 2 || res.Console[0].Text != "x 1" {
- t.Fatalf("console: %+v", res.Console)
- }
- if !strings.Contains(res.Console[1].Text, "[AGI] FileLibError: ") {
- t.Errorf("missing RaiseError log: %+v", res.Console[1])
- }
- if res.Error == nil || !strings.HasPrefix(res.Error.Message, "FileLibError: ") {
- t.Errorf("an uncaught failure should end the script with its error: %+v", res.Error)
- }
- }
- func TestFilelib(t *testing.T) {
- files := []File{
- {Path: "user:/Docs/a.txt", Data: []byte("hello")},
- {Path: "user:/Docs/b10.txt", Data: []byte("1234567890")},
- {Path: "user:/Docs/b2.txt", Data: []byte("12")},
- {Path: "user:/Docs/.hidden", Data: []byte("x")},
- }
- code := `requirelib("filelib");
- var out = {};
- out.read = filelib.readFile("user:/Docs/a.txt");
- out.write = filelib.writeFile("user:/Docs/new.txt", "abc");
- try { filelib.writeFile("user:/Nope/new.txt", "abc"); out.noParent = "wrote"; } catch(e) { out.noParent = e.name; }
- out.glob = filelib.glob("user:/Docs/*.txt");
- out.smart = filelib.glob("user:/Docs/b*.txt", "smart");
- out.size = filelib.filesize("user:/Docs/b10.txt");
- out.exists = filelib.fileExists("user:/Docs/a.txt");
- out.mkdir = filelib.mkdir("user:/Made/Deep");
- out.isDir = filelib.isDir("user:/Made");
- out.walk = filelib.walk("user:/Made", "folder");
- out.md5 = filelib.md5("user:/Docs/a.txt");
- out.readdir = filelib.readdir("user:/Docs").map(function(e){ return e.Filename; });
- out.root = filelib.rootName("user:/");
- out.del = filelib.deleteFile("user:/Docs/a.txt");
- out.gone = filelib.fileExists("user:/Docs/a.txt");
- out.hex = filelib.readBinaryFile("user:/Docs/b2.txt");
- out.b64 = filelib.readBinaryFile("user:/Docs/b2.txt", "base64");
- out.writeBin = filelib.writeBinaryFile("user:/Docs/bin.dat", "AAH/", "base64");
- out.binBack = filelib.readBinaryFile("user:/Docs/bin.dat", "hex");
- try { filelib.writeBinaryFile("user:/Docs/bad.dat", "zz", "hex"); out.badHex = "wrote"; } catch(e) { out.badHex = e.name; }
- try { filelib.readFile("web:/Playground/main.agi"); out.web = "read"; } catch(e) { out.web = e.name; }
- try { filelib.readFile("user:/missing.txt"); out.missing = "read"; } catch(e) { out.missing = e.name; }
- out.isDirMissing = filelib.isDir("user:/none");
- sendJSONResp(out);`
- res := runCode(t, code, files, nil)
- if res.Error != nil {
- t.Fatalf("error: %+v", res.Error)
- }
- var out map[string]interface{}
- if err := json.Unmarshal([]byte(res.Response), &out); err != nil {
- t.Fatal(err)
- }
- checks := map[string]string{
- "read": "hello", "write": "true", "noParent": "FileLibError", "size": "10", "exists": "true",
- "mkdir": "true", "isDir": "true", "md5": "5d41402abc4b2a76b9719d911017c592", "root": "User",
- "del": "true", "gone": "false", "hex": "3132", "web": "PermissionDenied", "isDirMissing": "false",
- "b64": "MTI=", "writeBin": "true", "binBack": "0001ff", "badHex": "FileLibError", "missing": "FileLibError",
- "glob": "[user:/Docs/a.txt user:/Docs/b10.txt user:/Docs/b2.txt user:/Docs/new.txt]",
- "smart": "[user:/Docs/b2.txt user:/Docs/b10.txt]",
- "walk": "[user:/Made user:/Made/Deep]",
- "readdir": "[a.txt b10.txt b2.txt new.txt]",
- }
- for k, want := range checks {
- if got := fmtValue(out[k]); got != want {
- t.Errorf("%s = %s, want %s", k, got, want)
- }
- }
- written := map[string]bool{}
- for _, f := range res.Written {
- written[f.Path] = true
- }
- if !written["user:/Docs/new.txt"] || !written["user:/Made/Deep"] {
- t.Errorf("changes missing: %+v", res.Written)
- }
- if len(res.Removed) != 1 || res.Removed[0] != "user:/Docs/a.txt" {
- t.Errorf("removed = %v", res.Removed)
- }
- }
- func fmtValue(v interface{}) string {
- switch x := v.(type) {
- case []interface{}:
- parts := make([]string, len(x))
- for i, e := range x {
- parts[i] = fmtValue(e)
- }
- return "[" + strings.Join(parts, " ") + "]"
- case float64:
- b, _ := json.Marshal(x)
- return string(b)
- case bool:
- if x {
- return "true"
- }
- return "false"
- case string:
- return x
- }
- b, _ := json.Marshal(v)
- return string(b)
- }
- func TestRelativePathsOnlyForDriveScripts(t *testing.T) {
- files := []File{{Path: "user:/Scripts/data.txt", Data: []byte("near")}}
- code := `requirelib("filelib"); sendResp(filelib.readFile("data.txt"));`
- res := Run(Request{Script: "user:/Scripts/run.agi", Code: code, Files: files, TimeoutSec: 5}, Hooks{})
- if res.Response != "near" || res.Mode != "serverless" {
- t.Errorf("drive script: %q (%s)", res.Response, res.Mode)
- }
- res = runCode(t, `requirelib("filelib"); try { filelib.readFile("data.txt"); sendResp("read"); } catch(e) { sendResp(e.name); }`, files, nil)
- if res.Response != "PermissionDenied" {
- t.Errorf("WebApp script reading a relative path: %q", res.Response)
- }
- }
- func TestRequestModes(t *testing.T) {
- res := runCode(t, `sendResp(name + "/" + typeof getPara)`, nil, func(r *Request) {
- r.Form = map[string]string{"name": "amy"}
- })
- if res.Response != "amy/undefined" {
- t.Errorf("webapp form: %q", res.Response)
- }
- res = runCode(t, `sendResp(a + POST_data)`, nil, func(r *Request) {
- r.ContentType = "application/json"
- r.Body = `{"a":"x"}`
- })
- if res.Response != `x{"a":"x"}` {
- t.Errorf("webapp json: %q", res.Response)
- }
- res = Run(Request{Script: "user:/s.agi", Code: `sendResp(REQ_METHOD + getPara("q") + postPara("p") + readBody())`,
- Method: "POST", Query: map[string]string{"q": "1"}, Form: map[string]string{"p": "2"}, TimeoutSec: 5}, Hooks{})
- if res.Response != "POST12p=2" {
- t.Errorf("serverless: %q", res.Response)
- }
- }
- func TestDatabaseState(t *testing.T) {
- code := `newDBTableIfNotExists("notes");
- writeDBItem("notes", "k", "v");
- var bad;
- try { writeDBItem("auth", "k", "v"); bad = "wrote"; } catch(e) { bad = e.name; }
- sendJSONResp({v: readDBItem("notes", "k"), all: listDBTable("notes"), bad: bad, missing: readDBItem("none", "k")});`
- res := runCode(t, code, nil, nil)
- if res.Response != `{"all":{"k":"v"},"bad":"AGIError","missing":false,"v":"v"}` {
- t.Errorf("db: %s", res.Response)
- }
- if res.State.DB["notes"]["k"] != "v" {
- t.Fatalf("state not returned: %+v", res.State.DB)
- }
- res = runCode(t, `sendResp(readDBItem("notes", "k"))`, nil, func(r *Request) { r.State = res.State })
- if res.Response != "v" {
- t.Errorf("state not reused: %q", res.Response)
- }
- }
- func TestIncludesAndExecd(t *testing.T) {
- files := []File{
- {Path: "web:/Playground/lib.js", Data: []byte(`function twice(x){ return x * 2; }`)},
- {Path: "web:/Playground/child.agi", Data: []byte(`requirelib("filelib"); filelib.writeFile("user:/child.txt", PARENT_PAYLOAD + PARENT_DETACHED);`)},
- }
- res := runCode(t, `includes("lib.js"); execd("child.agi", "hi"); sendResp(twice(21));`, files, nil)
- if res.Response != "42" {
- t.Errorf("includes: %q", res.Response)
- }
- found := false
- for _, f := range res.Written {
- if f.Path == "user:/child.txt" && string(f.Data) == "hitrue" {
- found = true
- }
- }
- if !found {
- t.Errorf("execd child did not run: %+v", res.Written)
- }
- res = Run(Request{Script: "user:/x.agi", Code: `sendResp(typeof includes)`, TimeoutSec: 5}, Hooks{})
- if res.Response != "undefined" {
- t.Errorf("includes should only exist for WebApp scripts, got %q", res.Response)
- }
- }
- func TestUserFunctions(t *testing.T) {
- code := `var r = [userIsAdmin(), createUser("bob", "pw", "user"), userExists("bob"), removeUser("bob"), userExists("bob")]; sendResp(r.join(","));`
- res := runCode(t, code, nil, func(r *Request) { r.User.Admin = true })
- if res.Response != "true,true,true,true,false" {
- t.Errorf("admin: %q", res.Response)
- }
- res = runCode(t, `try { createUser("bob","pw","user"); sendResp("created"); } catch(e) { sendResp(e.name + ": " + e.message); }`, nil, nil)
- if res.Response != "AGIError: Permission Denied: createUser require admin permission" {
- t.Errorf("non-admin createUser: %q", res.Response)
- }
- }
- func TestHTTPMock(t *testing.T) {
- mocks := Mocks{HTTP: HTTPMock{Rules: []HTTPRule{
- {Method: "GET", URL: "https://api.example.com/users/*", Body: `{"id":7}`},
- {Method: "POST", URL: "/example\\.com\\/echo$/", Status: 201, Body: "got {{body}}"},
- {URL: "https://down.example.com/", Error: "dial tcp: connection refused"},
- }}}
- code := `requirelib("http");
- var a = JSON.parse(http.get("https://api.example.com/users/7")).id;
- var b = http.request({url: "https://example.com/echo", method: "POST", json: {x: 1}});
- var c, d;
- try { http.request({url: "https://down.example.com/"}); } catch(err) { c = err.name + ": " + err.message; }
- try { http.get("https://nowhere.example.com/"); } catch(err) { d = err.name; }
- var e = http.getCode("https://api.example.com/users/1");
- sendJSONResp({a: a, bStatus: b.status, bBody: b.body, cErr: c, d: d, e: e});`
- res := runCode(t, code, nil, func(r *Request) { r.Mocks = mocks })
- want := `{"a":7,"bBody":"got {\"x\":1}","bStatus":201,"cErr":"HTTPError: dial tcp: connection refused","d":"HTTPError","e":200}`
- if res.Response != want {
- t.Errorf("http:\n got %s\nwant %s", res.Response, want)
- }
- if len(res.Calls) != 5 {
- t.Errorf("calls recorded: %d", len(res.Calls))
- }
- }
- func TestLLMMock(t *testing.T) {
- mocks := Mocks{LLM: LLMMock{Mode: "rules", Reply: "fallback", Rules: []TextRule{{Match: "capital", Reply: "Paris"}}, ChunkSize: 2, ChunkDelayMs: 1}}
- code := `requirelib("llm");
- var parts = [];
- var s = llm.streamRequest([{role:"user", content:"hello"}], {}, function(d){ parts.push(d.content); });
- sendJSONResp({a: llm.chat("What is the capital of France?"), b: llm.request([{role:"user",content:"hi"}]).choices[0].message.content, s: parts.join("|"), u: llm.usage().totalRequests});`
- res := runCode(t, code, nil, func(r *Request) { r.Mocks = mocks })
- if res.Response != `{"a":"Paris","b":"fallback","s":"fa|ll|ba|ck","u":3}` {
- t.Errorf("llm: %s", res.Response)
- }
- mocks.LLM.Error = "quota exceeded"
- res = runCode(t, `requirelib("llm"); try { llm.chat("x") } catch(e) { sendResp(e.name + ": " + e.message) }`, nil, func(r *Request) { r.Mocks = mocks })
- if res.Response != "LLMError: quota exceeded" {
- t.Errorf("llm error: %q", res.Response)
- }
- }
- func TestCNNMock(t *testing.T) {
- files := []File{{Path: "user:/cat.jpg", Data: []byte("x")}}
- code := `requirelib("cnn");
- var r = cnn.classify("user:/cat.jpg", {top_k: 3});
- var j = cnn.detect("user:/cat.jpg", {async: true});
- var j2 = cnn.job(j.id);
- var a = cnn.analyze("user:/cat.jpg", ["detect", "faces"]);
- try { cnn.classify("user:/none.jpg") } catch(e) { var err = e.name }
- sendJSONResp({label: r.data[0].label, status: j2.status, n: j2.result.data.length, faces: a.results.faces.object, err: err});`
- res := runCode(t, code, files, nil)
- if res.Response != `{"err":"CNNError","faces":"face_detection","label":"tabby cat","n":2,"status":"succeeded"}` {
- t.Errorf("cnn: %s (%+v)", res.Response, res.Error)
- }
- }
- func TestSQLiteAndGenericMocks(t *testing.T) {
- mocks := Mocks{
- SQLite: []SQLRule{{Fn: "query", Match: "FROM notes", Result: `[{"id":1,"title":"a"}]`}},
- Generic: map[string]string{"git.status": `{"branch":"main"}`},
- }
- code := `requirelib("sqlite"); requirelib("git");
- var db = sqlite.open("user:/app.db");
- var rows = db.query("SELECT * FROM notes");
- var ins = db.exec("INSERT INTO notes VALUES (?)", ["x"]);
- sendJSONResp({rows: rows, ins: ins.rowsAffected, git: git.status("user:/repo").branch, none: git.log("user:/repo")});`
- res := runCode(t, code, nil, func(r *Request) {
- r.Mocks = mocks
- r.Catalog = map[string][]string{"git": {"git.status", "git.log"}}
- })
- if res.Response != `{"git":"main","ins":0,"none":null,"rows":[{"id":1,"title":"a"}]}` {
- t.Errorf("mocks: %s (%+v)", res.Response, res.Error)
- }
- res = runCode(t, `sendResp(requirelib("nosuchlib"))`, nil, nil)
- if res.Response != "false" {
- t.Errorf("unknown lib: %q", res.Response)
- }
- }
- func TestWebsocket(t *testing.T) {
- mocks := Mocks{WS: WSMock{Script: []WSScripted{{AfterMs: 10, Text: "ping"}, {AfterMs: 10, Text: "bye"}}, CloseAfterMs: 10}}
- code := `requirelib("websocket");
- websocket.upgrade(10);
- var got = [];
- while (true) {
- var m = websocket.read(2000);
- if (m === false) break;
- if (m === null) { got.push("timeout"); break; }
- got.push(m);
- websocket.send("echo:" + m);
- }
- sendResp(got.join(","));`
- res := runCode(t, code, nil, func(r *Request) { r.Mocks = mocks })
- if res.Response != "ping,bye" {
- t.Errorf("ws read: %q", res.Response)
- }
- var out []string
- for _, f := range res.WS {
- if f.Dir == "out" {
- out = append(out, f.Text)
- }
- }
- if strings.Join(out, ",") != "echo:ping,echo:bye" {
- t.Errorf("ws frames: %+v", res.WS)
- }
- live := make(chan WSIn, 2)
- live <- WSIn{Text: "live"}
- code = `requirelib("websocket"); websocket.upgrade(10);
- var got = "";
- websocket.onMessage = function(m){ got += m; };
- delay(200);
- sendResp(got);`
- res = runCode(t, code, nil, func(r *Request) { r.Live = live })
- if res.Response != "live" {
- t.Errorf("onMessage pump: %q", res.Response)
- }
- }
- func pngBytes(w, h int) []byte {
- img := image.NewRGBA(image.Rect(0, 0, w, h))
- for y := 0; y < h; y++ {
- for x := 0; x < w; x++ {
- img.Set(x, y, color.RGBA{uint8(x), uint8(y), 128, 255})
- }
- }
- var buf bytes.Buffer
- png.Encode(&buf, img)
- return buf.Bytes()
- }
- func TestImagelib(t *testing.T) {
- files := []File{{Path: "user:/a.png", Data: pngBytes(200, 100)}}
- code := `requirelib("imagelib");
- var d = imagelib.getImageDimension("user:/a.png");
- imagelib.resizeImage("user:/a.png", "user:/small.jpg", 50, 0);
- var s = imagelib.getImageDimension("user:/small.jpg");
- imagelib.cropImage("user:/a.png", "user:/crop.png", 10, 10, 30, 20);
- var c = imagelib.getImageDimension("user:/crop.png");
- var p = imagelib.renderPreview("user:/a.png", "", 40, 40);
- sendResp([d, s, c, [p.width, p.height], p.dataURL.indexOf("data:image/jpeg")].join(";"));`
- res := runCode(t, code, files, nil)
- if res.Response != "200,100;50,25;30,20;40,20;0" {
- t.Errorf("imagelib: %q (%+v)", res.Response, res.Error)
- }
- }
- func TestZiplib(t *testing.T) {
- files := []File{{Path: "user:/src/a.txt", Data: []byte("A")}, {Path: "user:/src/sub/b.txt", Data: []byte("B")}}
- code := `requirelib("ziplib"); requirelib("filelib");
- var ok = ziplib.createZipFile("user:/src", "user:/out.zip");
- var valid = ziplib.isValidZipFile("user:/out.zip");
- ziplib.extractZipFile("user:/out.zip", "user:/x");
- var tgz = ziplib.createAnyZipFile(["user:/src/a.txt"], "user:/a.tar.gz");
- ziplib.extractAnyFile("user:/a.tar.gz", "user:/y");
- var tree = JSON.parse(ziplib.listZipFileContents("user:/out.zip"));
- sendResp([ok, valid, filelib.readFile("user:/x/src/sub/b.txt"), tgz, filelib.readFile("user:/y/a.txt"), tree.children.src.isDir].join(","));`
- res := runCode(t, code, files, nil)
- if res.Response != "true,true,B,true,A,true" {
- t.Errorf("ziplib: %q (%+v) %+v", res.Response, res.Error, res.Console)
- }
- var zipData []byte
- for _, f := range res.Written {
- if f.Path == "user:/out.zip" {
- zipData = f.Data
- }
- }
- zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
- if err != nil {
- t.Fatal(err)
- }
- var names []string
- for _, f := range zr.File {
- names = append(names, f.Name)
- }
- if strings.Join(names, ",") != "src/,src/a.txt,src/sub/,src/sub/b.txt" {
- t.Errorf("zip entries: %v", names)
- }
- }
- func TestZipSlipRefused(t *testing.T) {
- var buf bytes.Buffer
- zw := zip.NewWriter(&buf)
- w, _ := zw.Create("../../evil.txt")
- w.Write([]byte("x"))
- zw.Close()
- files := []File{{Path: "user:/bad.zip", Data: buf.Bytes()}}
- res := runCode(t, `requirelib("ziplib"); try { ziplib.extractZipFile("user:/bad.zip", "user:/out"); sendResp("extracted"); } catch(e) { sendResp(e.name); }`, files, nil)
- if res.Response != "ZipLibError" {
- t.Errorf("zip slip extracted: %q", res.Response)
- }
- for _, f := range res.Written {
- if strings.Contains(f.Path, "evil") {
- t.Errorf("wrote %s", f.Path)
- }
- }
- }
- func TestShareSchedulerNotification(t *testing.T) {
- files := []File{{Path: "user:/a.txt", Data: []byte("x")}, {Path: "web:/Playground/task.agi", Data: []byte("")}}
- code := `requirelib("share"); requirelib("scheduler"); requirelib("notification");
- var id = share.shareFile("user:/a.txt", 0);
- var r = [share.checkShareExists(id), share.fileIsShared("user:/a.txt"), share.getFileShareUUID("user:/a.txt") == id];
- r.push(scheduler.register("t1", "Playground", 3600, "desc", "task.agi"));
- r.push(scheduler.registered("t1", "Playground"));
- r.push(notification.send("Hello", "World", notification.PRIORITY_HIGH));
- sendResp(r.join(","));`
- res := runCode(t, code, files, nil)
- if res.Response != "true,true,true,true,true,true" {
- t.Errorf("share/scheduler/notification: %q %+v", res.Response, res.Console)
- }
- if len(res.State.Shares) != 1 || len(res.State.Tasks) != 1 || len(res.Notifications) != 1 {
- t.Errorf("state: %+v notifications: %+v", res.State, res.Notifications)
- }
- }
- // TestLibraryErrors checks that each library throws its own named error,
- // which a script can catch, and logs it
- func TestLibraryErrors(t *testing.T) {
- files := []File{{Path: "user:/a.txt", Data: []byte("x")}, {Path: "web:/Playground/task.agi", Data: []byte("")}}
- cases := []struct {
- name, lib, call, want string
- }{
- {"appdata escape", "appdata", `appdata.readFile("../../secret")`, "AppdataError: Path escape detected"},
- {"appdata missing", "appdata", `appdata.readFile("Playground/none.txt")`, "AppdataError: File not exists"},
- {"appdata no dir", "appdata", `appdata.listDir("Nowhere")`, "AppdataError: Directory not exists"},
- {"share missing file", "share", `share.shareFile("user:/none.txt", 0)`, "ShareError: share failed: file not exists"},
- {"share remove unknown", "share", `share.removeShare("nope")`, "ShareError: failed to remove share: share UUID not exists"},
- {"notification no title", "notification", `notification.send()`, "NotificationError: title is undefined"},
- {"notification not admin", "notification", `notification.sendToUser("bob", "hi")`, "NotificationError: Permission Denied: sendToUser require admin permission"},
- {"scheduler no app", "scheduler", `scheduler.register("t1")`, "SchedulerError: app name not given"},
- {"scheduler no script", "scheduler", `scheduler.register("t1", "Playground", 60, "", "none.agi")`, "SchedulerError: app script not found: web:/Playground/none.agi"},
- {"scheduler unregister unknown", "scheduler", `scheduler.unregister("nope")`, "SchedulerError: job not found: nope"},
- {"websocket refused", "websocket", `websocket.upgrade(10)`, "WebSocketError: websocket: the client did not ask for a WebSocket upgrade"},
- }
- for _, c := range cases {
- code := `requirelib("` + c.lib + `"); try { ` + c.call + `; sendResp("no error"); } catch(e) { sendResp(e.name + ": " + e.message); }`
- res := runCode(t, code, files, func(r *Request) { r.Mocks.WS.Refuse = true })
- if res.Response != c.want {
- t.Errorf("%s: got %q, want %q", c.name, res.Response, c.want)
- }
- logged := false
- for _, l := range res.Console {
- if strings.Contains(l.Text, "[AGI] "+c.want) {
- logged = true
- }
- }
- if !logged {
- t.Errorf("%s: error not logged: %+v", c.name, res.Console)
- }
- }
- //Answers that are not failures stay values
- code := `requirelib("share"); requirelib("websocket"); requirelib("imagelib");
- sendJSONResp([share.getFileShareUUID("user:/a.txt"), share.checkSharePermission("nope"), websocket.send("x"), imagelib.loadThumbString("user:/a.txt")]);`
- res := runCode(t, code, files, nil)
- if res.Response != `[null,null,false,false]` {
- t.Errorf("answers: %s %+v", res.Response, res.Error)
- }
- }
- func TestStreamingHooks(t *testing.T) {
- var lines []string
- Run(Request{Script: "web:/P/x.agi", Code: `console.log("a"); console.log("b");`, TimeoutSec: 5}, Hooks{Log: func(l LogLine) { lines = append(lines, l.Text) }})
- if strings.Join(lines, "") != "ab" {
- t.Errorf("hooks: %v", lines)
- }
- }
- func TestDelay(t *testing.T) {
- start := time.Now()
- runCode(t, `delay(120)`, nil, nil)
- if time.Since(start) < 100*time.Millisecond {
- t.Errorf("delay did not wait")
- }
- }
|