| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- package main
- import (
- "bytes"
- "encoding/json"
- "image"
- "image/color"
- "image/jpeg"
- "image/png"
- "os"
- "path/filepath"
- "reflect"
- "strings"
- "testing"
- "imuslab.com/arozos/agidocgen/playground"
- )
- func TestExpandNames(t *testing.T) {
- cases := []struct {
- in string
- want []string
- }{
- {"filelib.readFile", []string{"filelib.readFile"}},
- {"http.put / http.patch / http.delete", []string{"http.put", "http.patch", "http.delete"}},
- {"notification.PRIORITY_LOW / PRIORITY_MEDIUM", []string{"notification.PRIORITY_LOW", "notification.PRIORITY_MEDIUM"}},
- {"sendResp()", []string{"sendResp"}},
- {" ", nil},
- }
- for _, c := range cases {
- if got := expandNames(c.in); !reflect.DeepEqual(got, c.want) {
- t.Errorf("expandNames(%q) = %v, want %v", c.in, got, c.want)
- }
- }
- }
- func TestSplitFrontMatter(t *testing.T) {
- fm, body, err := splitFrontMatter("---\r\ntitle: Files\r\norder: 3\r\n\r\n---\r\n# Hello\r\n")
- if err != nil {
- t.Fatalf("splitFrontMatter: %v", err)
- }
- if fm["title"] != "Files" || fm["order"] != "3" {
- t.Errorf("front matter = %v", fm)
- }
- if body != "# Hello\n" {
- t.Errorf("body = %q", body)
- }
- fm, body, err = splitFrontMatter("# No header\n")
- if err != nil || len(fm) != 0 || body != "# No header\n" {
- t.Errorf("no header: %v %q %v", fm, body, err)
- }
- if _, _, err := splitFrontMatter("---\ntitle: x\n"); err == nil {
- t.Error("an unclosed header should fail")
- }
- if _, _, err := splitFrontMatter("---\nno colon\n---\n"); err == nil {
- t.Error("a line without a colon should fail")
- }
- }
- func TestSplitBlocks(t *testing.T) {
- md := "Intro line.\n\n## `a()`\nBody of a.\n```js\n# not a heading\n```\n### Sub\nSub body.\n"
- intro, blocks := splitBlocks(md)
- if intro != "Intro line." {
- t.Errorf("intro = %q", intro)
- }
- if len(blocks) != 2 {
- t.Fatalf("got %d blocks, want 2", len(blocks))
- }
- if blocks[0].Level != 2 || blocks[0].Heading != "`a()`" {
- t.Errorf("first block = %+v", blocks[0])
- }
- if !strings.Contains(blocks[0].Body, "# not a heading") {
- t.Errorf("a # line inside a fence must stay in the body: %q", blocks[0].Body)
- }
- if blocks[1].Level != 3 || blocks[1].Body != "Sub body." {
- t.Errorf("second block = %+v", blocks[1])
- }
- }
- func TestParseHeading(t *testing.T) {
- known := map[string]bool{"USERNAME": true}
- cases := []struct {
- heading string
- isFn bool
- names []string
- ret string
- badges []string
- }{
- {"`filelib.readFile(vpath)` → `string`", true, []string{"filelib.readFile"}, "string", nil},
- {"`http.put(url, body)` / `http.patch(url, body)`", true, []string{"http.put", "http.patch"}, "", nil},
- {"`createUser(name, pw, group)` (admin only)", true, []string{"createUser"}, "", []string{"admin only"}},
- {"`USERNAME`", true, []string{"USERNAME"}, "", nil},
- {"`options`", false, nil, "", nil},
- {"Pattern 2 — `available()` polling", false, nil, "", nil},
- {"Overview", false, nil, "", nil},
- }
- for _, c := range cases {
- b := &Block{Heading: c.heading}
- parseHeading(b, known)
- if b.IsFn != c.isFn {
- t.Errorf("%q: IsFn = %v, want %v", c.heading, b.IsFn, c.isFn)
- continue
- }
- if !c.isFn {
- continue
- }
- if !reflect.DeepEqual(b.Names(), c.names) {
- t.Errorf("%q: names = %v, want %v", c.heading, b.Names(), c.names)
- }
- if b.Ret != c.ret {
- t.Errorf("%q: ret = %q, want %q", c.heading, b.Ret, c.ret)
- }
- if !reflect.DeepEqual(b.Badges, c.badges) {
- t.Errorf("%q: badges = %v, want %v", c.heading, b.Badges, c.badges)
- }
- }
- }
- func TestSlugs(t *testing.T) {
- cases := []struct{ in, github, slug string }{
- {"`db.transaction(fn)` → `any`", "dbtransactionfn--any", "dbtransactionfn-any"},
- {"Getting started", "getting-started", "getting-started"},
- {"[Link](x.md) text", "link-text", "link-text"},
- }
- for _, c := range cases {
- if got := githubSlug(c.in); got != c.github {
- t.Errorf("githubSlug(%q) = %q, want %q", c.in, got, c.github)
- }
- if got := slugify(c.in); got != c.slug {
- t.Errorf("slugify(%q) = %q, want %q", c.in, got, c.slug)
- }
- }
- if got := slugify("()"); got != "section" {
- t.Errorf("slugify of nothing = %q", got)
- }
- }
- func TestPrepareOutput(t *testing.T) {
- dir := t.TempDir()
- // A missing folder is created and marked.
- out := filepath.Join(dir, "site")
- if err := prepareOutput(out); err != nil {
- t.Fatalf("new folder: %v", err)
- }
- if _, err := os.Stat(filepath.Join(out, markerFile)); err != nil {
- t.Fatalf("marker not written: %v", err)
- }
- // A marked folder is cleared.
- if err := os.WriteFile(filepath.Join(out, "old.html"), []byte("x"), 0o644); err != nil {
- t.Fatal(err)
- }
- if err := prepareOutput(out); err != nil {
- t.Fatalf("marked folder: %v", err)
- }
- if _, err := os.Stat(filepath.Join(out, "old.html")); !os.IsNotExist(err) {
- t.Errorf("old.html survived: %v", err)
- }
- // Anything else is left alone.
- other := filepath.Join(dir, "precious")
- if err := os.MkdirAll(other, 0o755); err != nil {
- t.Fatal(err)
- }
- if err := os.WriteFile(filepath.Join(other, "keep.txt"), []byte("x"), 0o644); err != nil {
- t.Fatal(err)
- }
- if err := prepareOutput(other); err == nil {
- t.Error("a folder without the marker must be refused")
- }
- if _, err := os.Stat(filepath.Join(other, "keep.txt")); err != nil {
- t.Errorf("keep.txt was removed: %v", err)
- }
- }
- func TestLoadSamplesHeader(t *testing.T) {
- dir := t.TempDir()
- write := func(name, src string) {
- if err := os.WriteFile(filepath.Join(dir, name), []byte(src), 0o644); err != nil {
- t.Fatal(err)
- }
- }
- write("01-first.agi", "/*---\ntitle: First\npath: user:/x.agi\nsetup: {\"request\":{\"method\":\"GET\"}}\n---*/\n\nsendResp(1);\n")
- write("02-second.agi", "/*---\ntitle: Second\n---*/\nsendResp(2);\n")
- got, err := loadSamples(dir)
- if err != nil {
- t.Fatalf("loadSamples: %v", err)
- }
- if len(got) != 2 || got[0].ID != "first" || got[1].ID != "second" {
- t.Fatalf("ids: %+v", got)
- }
- if got[0].Path != "user:/x.agi" || got[1].Path != "web:/Playground/second.agi" {
- t.Errorf("paths: %q %q", got[0].Path, got[1].Path)
- }
- if got[0].Code != "sendResp(1);\n" || string(got[0].Setup) != `{"request":{"method":"GET"}}` {
- t.Errorf("first sample: %q %s", got[0].Code, got[0].Setup)
- }
- bad := []string{
- "sendResp(1);\n", // no header
- "/*---\ntitle: x\nsendResp(1);\n", // not closed
- "/*---\nsummary: x\n---*/\nx();\n", // no title
- "/*---\ntitle: x\nsetup: {\n---*/\n", // setup is not JSON
- }
- for i, src := range bad {
- d := t.TempDir()
- if err := os.WriteFile(filepath.Join(d, "s.agi"), []byte(src), 0o644); err != nil {
- t.Fatal(err)
- }
- if _, err := loadSamples(d); err == nil {
- t.Errorf("bad sample %d was accepted", i)
- }
- }
- }
- // sampleSetup is the part of a sample's setup header the test needs.
- type sampleSetup struct {
- Request struct {
- Method string `json:"method"`
- Form map[string]string `json:"form"`
- Query map[string]string `json:"query"`
- JSON json.RawMessage `json:"json"`
- } `json:"request"`
- Mocks playground.Mocks `json:"mocks"`
- Files []struct {
- Path string `json:"path"`
- Text string `json:"text"`
- Dir bool `json:"dir"`
- } `json:"files"`
- }
- // workspace is the drive the playground page starts with (defaultFiles in
- // static/assets/playground.js), which the samples rely on.
- func workspace(t *testing.T) []playground.File {
- t.Helper()
- img := image.NewRGBA(image.Rect(0, 0, 640, 400))
- for y := 0; y < 400; y++ {
- for x := 0; x < 640; x++ {
- img.Set(x, y, color.RGBA{uint8(x / 3), 90, uint8(y / 2), 255})
- }
- }
- var pngBuf, jpgBuf bytes.Buffer
- if err := png.Encode(&pngBuf, img); err != nil {
- t.Fatal(err)
- }
- if err := jpeg.Encode(&jpgBuf, img, nil); err != nil {
- t.Fatal(err)
- }
- text := func(p, s string) playground.File { return playground.File{Path: p, Data: []byte(s)} }
- return []playground.File{
- text("web:/Playground/main.agi", `sendResp("main");`),
- text("web:/Playground/lib/format.js", "function formatBytes(n){ return n + \" B\"; }\n"),
- text("user:/Desktop/hello.txt", "Hello from the playground drive.\n"),
- text("user:/Documents/notes.md", "# Notes\n\n- one\n- two\n"),
- text("user:/Documents/data.json", `{"project": "ArozOS", "tags": ["nas", "agi"], "stars": 1200}`),
- text("user:/Documents/scores.csv", "name,score\nAmy,92\n"),
- {Path: "user:/Photo/gradient.png", Data: pngBuf.Bytes()},
- {Path: "user:/Photo/sunset.jpg", Data: jpgBuf.Bytes()},
- }
- }
- // TestSamplesRun runs every shipped sample through the engine, set up as
- // the playground page would, so a sample that no longer works fails here.
- func TestSamplesRun(t *testing.T) {
- samples, err := loadSamples("samples")
- if err != nil {
- t.Fatalf("loadSamples: %v", err)
- }
- if len(samples) == 0 {
- t.Fatal("no samples found")
- }
- seen := map[string]bool{}
- for _, s := range samples {
- s := s
- t.Run(s.ID, func(t *testing.T) {
- if seen[s.ID] {
- t.Fatalf("duplicate sample id %q", s.ID)
- }
- seen[s.ID] = true
- if s.Group == "" || s.Summary == "" {
- t.Errorf("sample needs a group and a summary")
- }
- var setup sampleSetup
- if len(s.Setup) > 0 {
- if err := json.Unmarshal(s.Setup, &setup); err != nil {
- t.Fatalf("setup: %v", err)
- }
- }
- // The page saves the sample on the drive before it runs it.
- files := append(workspace(t), playground.File{Path: s.Path, Data: []byte(s.Code)})
- for _, f := range setup.Files {
- files = append(files, playground.File{Path: f.Path, Dir: f.Dir, Data: []byte(f.Text)})
- }
- req := playground.Request{
- Script: s.Path,
- Code: s.Code,
- Method: setup.Request.Method,
- Form: setup.Request.Form,
- Query: setup.Request.Query,
- Mocks: setup.Mocks,
- Files: files,
- TimeoutSec: 20,
- User: playground.User{Username: "developer", Admin: true, QuotaTotal: -1},
- }
- if len(setup.Request.JSON) > 0 {
- req.Body = string(setup.Request.JSON)
- req.ContentType = "application/json"
- }
- res := playground.Run(req, playground.Hooks{})
- if res.Error != nil {
- t.Fatalf("%s: %s\n%s", res.Error.Kind, res.Error.Message, res.Error.Stack)
- }
- for _, l := range res.Console {
- if strings.Contains(l.Text, "Runtime Error") || strings.Contains(l.Text, "not found") {
- t.Errorf("console: %s", l.Text)
- }
- }
- if res.Status != 200 {
- t.Errorf("status %d", res.Status)
- }
- if res.Response == "" && !res.Upgraded {
- t.Errorf("empty response")
- }
- })
- }
- }
- func TestPlayMode(t *testing.T) {
- for id, want := range map[string]string{"filelib": "runs", "http": "HTTP", "llm": "LLM", "cnn": "CNN", "git": "Services", "sqlite": "Services"} {
- if got := playMode(id); got != want {
- t.Errorf("playMode(%q) = %q, want %q", id, got, want)
- }
- }
- // Every library the engine runs natively must be marked as running.
- for _, lib := range playground.NativeLibs {
- if lib == "http" || lib == "llm" || lib == "cnn" || lib == "sqlite" || lib == "sysinfo" {
- continue
- }
- if playMode(lib) != "runs" {
- t.Errorf("%s runs natively but the docs say it is mocked", lib)
- }
- }
- }
|