main_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "image"
  6. "image/color"
  7. "image/jpeg"
  8. "image/png"
  9. "os"
  10. "path/filepath"
  11. "reflect"
  12. "strings"
  13. "testing"
  14. "imuslab.com/arozos/agidocgen/playground"
  15. )
  16. func TestExpandNames(t *testing.T) {
  17. cases := []struct {
  18. in string
  19. want []string
  20. }{
  21. {"filelib.readFile", []string{"filelib.readFile"}},
  22. {"http.put / http.patch / http.delete", []string{"http.put", "http.patch", "http.delete"}},
  23. {"notification.PRIORITY_LOW / PRIORITY_MEDIUM", []string{"notification.PRIORITY_LOW", "notification.PRIORITY_MEDIUM"}},
  24. {"sendResp()", []string{"sendResp"}},
  25. {" ", nil},
  26. }
  27. for _, c := range cases {
  28. if got := expandNames(c.in); !reflect.DeepEqual(got, c.want) {
  29. t.Errorf("expandNames(%q) = %v, want %v", c.in, got, c.want)
  30. }
  31. }
  32. }
  33. func TestSplitFrontMatter(t *testing.T) {
  34. fm, body, err := splitFrontMatter("---\r\ntitle: Files\r\norder: 3\r\n\r\n---\r\n# Hello\r\n")
  35. if err != nil {
  36. t.Fatalf("splitFrontMatter: %v", err)
  37. }
  38. if fm["title"] != "Files" || fm["order"] != "3" {
  39. t.Errorf("front matter = %v", fm)
  40. }
  41. if body != "# Hello\n" {
  42. t.Errorf("body = %q", body)
  43. }
  44. fm, body, err = splitFrontMatter("# No header\n")
  45. if err != nil || len(fm) != 0 || body != "# No header\n" {
  46. t.Errorf("no header: %v %q %v", fm, body, err)
  47. }
  48. if _, _, err := splitFrontMatter("---\ntitle: x\n"); err == nil {
  49. t.Error("an unclosed header should fail")
  50. }
  51. if _, _, err := splitFrontMatter("---\nno colon\n---\n"); err == nil {
  52. t.Error("a line without a colon should fail")
  53. }
  54. }
  55. func TestSplitBlocks(t *testing.T) {
  56. md := "Intro line.\n\n## `a()`\nBody of a.\n```js\n# not a heading\n```\n### Sub\nSub body.\n"
  57. intro, blocks := splitBlocks(md)
  58. if intro != "Intro line." {
  59. t.Errorf("intro = %q", intro)
  60. }
  61. if len(blocks) != 2 {
  62. t.Fatalf("got %d blocks, want 2", len(blocks))
  63. }
  64. if blocks[0].Level != 2 || blocks[0].Heading != "`a()`" {
  65. t.Errorf("first block = %+v", blocks[0])
  66. }
  67. if !strings.Contains(blocks[0].Body, "# not a heading") {
  68. t.Errorf("a # line inside a fence must stay in the body: %q", blocks[0].Body)
  69. }
  70. if blocks[1].Level != 3 || blocks[1].Body != "Sub body." {
  71. t.Errorf("second block = %+v", blocks[1])
  72. }
  73. }
  74. func TestParseHeading(t *testing.T) {
  75. known := map[string]bool{"USERNAME": true}
  76. cases := []struct {
  77. heading string
  78. isFn bool
  79. names []string
  80. ret string
  81. badges []string
  82. }{
  83. {"`filelib.readFile(vpath)` → `string`", true, []string{"filelib.readFile"}, "string", nil},
  84. {"`http.put(url, body)` / `http.patch(url, body)`", true, []string{"http.put", "http.patch"}, "", nil},
  85. {"`createUser(name, pw, group)` (admin only)", true, []string{"createUser"}, "", []string{"admin only"}},
  86. {"`USERNAME`", true, []string{"USERNAME"}, "", nil},
  87. {"`options`", false, nil, "", nil},
  88. {"Pattern 2 — `available()` polling", false, nil, "", nil},
  89. {"Overview", false, nil, "", nil},
  90. }
  91. for _, c := range cases {
  92. b := &Block{Heading: c.heading}
  93. parseHeading(b, known)
  94. if b.IsFn != c.isFn {
  95. t.Errorf("%q: IsFn = %v, want %v", c.heading, b.IsFn, c.isFn)
  96. continue
  97. }
  98. if !c.isFn {
  99. continue
  100. }
  101. if !reflect.DeepEqual(b.Names(), c.names) {
  102. t.Errorf("%q: names = %v, want %v", c.heading, b.Names(), c.names)
  103. }
  104. if b.Ret != c.ret {
  105. t.Errorf("%q: ret = %q, want %q", c.heading, b.Ret, c.ret)
  106. }
  107. if !reflect.DeepEqual(b.Badges, c.badges) {
  108. t.Errorf("%q: badges = %v, want %v", c.heading, b.Badges, c.badges)
  109. }
  110. }
  111. }
  112. func TestSlugs(t *testing.T) {
  113. cases := []struct{ in, github, slug string }{
  114. {"`db.transaction(fn)` → `any`", "dbtransactionfn--any", "dbtransactionfn-any"},
  115. {"Getting started", "getting-started", "getting-started"},
  116. {"[Link](x.md) text", "link-text", "link-text"},
  117. }
  118. for _, c := range cases {
  119. if got := githubSlug(c.in); got != c.github {
  120. t.Errorf("githubSlug(%q) = %q, want %q", c.in, got, c.github)
  121. }
  122. if got := slugify(c.in); got != c.slug {
  123. t.Errorf("slugify(%q) = %q, want %q", c.in, got, c.slug)
  124. }
  125. }
  126. if got := slugify("()"); got != "section" {
  127. t.Errorf("slugify of nothing = %q", got)
  128. }
  129. }
  130. func TestPrepareOutput(t *testing.T) {
  131. dir := t.TempDir()
  132. // A missing folder is created and marked.
  133. out := filepath.Join(dir, "site")
  134. if err := prepareOutput(out); err != nil {
  135. t.Fatalf("new folder: %v", err)
  136. }
  137. if _, err := os.Stat(filepath.Join(out, markerFile)); err != nil {
  138. t.Fatalf("marker not written: %v", err)
  139. }
  140. // A marked folder is cleared.
  141. if err := os.WriteFile(filepath.Join(out, "old.html"), []byte("x"), 0o644); err != nil {
  142. t.Fatal(err)
  143. }
  144. if err := prepareOutput(out); err != nil {
  145. t.Fatalf("marked folder: %v", err)
  146. }
  147. if _, err := os.Stat(filepath.Join(out, "old.html")); !os.IsNotExist(err) {
  148. t.Errorf("old.html survived: %v", err)
  149. }
  150. // Anything else is left alone.
  151. other := filepath.Join(dir, "precious")
  152. if err := os.MkdirAll(other, 0o755); err != nil {
  153. t.Fatal(err)
  154. }
  155. if err := os.WriteFile(filepath.Join(other, "keep.txt"), []byte("x"), 0o644); err != nil {
  156. t.Fatal(err)
  157. }
  158. if err := prepareOutput(other); err == nil {
  159. t.Error("a folder without the marker must be refused")
  160. }
  161. if _, err := os.Stat(filepath.Join(other, "keep.txt")); err != nil {
  162. t.Errorf("keep.txt was removed: %v", err)
  163. }
  164. }
  165. func TestLoadSamplesHeader(t *testing.T) {
  166. dir := t.TempDir()
  167. write := func(name, src string) {
  168. if err := os.WriteFile(filepath.Join(dir, name), []byte(src), 0o644); err != nil {
  169. t.Fatal(err)
  170. }
  171. }
  172. write("01-first.agi", "/*---\ntitle: First\npath: user:/x.agi\nsetup: {\"request\":{\"method\":\"GET\"}}\n---*/\n\nsendResp(1);\n")
  173. write("02-second.agi", "/*---\ntitle: Second\n---*/\nsendResp(2);\n")
  174. got, err := loadSamples(dir)
  175. if err != nil {
  176. t.Fatalf("loadSamples: %v", err)
  177. }
  178. if len(got) != 2 || got[0].ID != "first" || got[1].ID != "second" {
  179. t.Fatalf("ids: %+v", got)
  180. }
  181. if got[0].Path != "user:/x.agi" || got[1].Path != "web:/Playground/second.agi" {
  182. t.Errorf("paths: %q %q", got[0].Path, got[1].Path)
  183. }
  184. if got[0].Code != "sendResp(1);\n" || string(got[0].Setup) != `{"request":{"method":"GET"}}` {
  185. t.Errorf("first sample: %q %s", got[0].Code, got[0].Setup)
  186. }
  187. bad := []string{
  188. "sendResp(1);\n", // no header
  189. "/*---\ntitle: x\nsendResp(1);\n", // not closed
  190. "/*---\nsummary: x\n---*/\nx();\n", // no title
  191. "/*---\ntitle: x\nsetup: {\n---*/\n", // setup is not JSON
  192. }
  193. for i, src := range bad {
  194. d := t.TempDir()
  195. if err := os.WriteFile(filepath.Join(d, "s.agi"), []byte(src), 0o644); err != nil {
  196. t.Fatal(err)
  197. }
  198. if _, err := loadSamples(d); err == nil {
  199. t.Errorf("bad sample %d was accepted", i)
  200. }
  201. }
  202. }
  203. // sampleSetup is the part of a sample's setup header the test needs.
  204. type sampleSetup struct {
  205. Request struct {
  206. Method string `json:"method"`
  207. Form map[string]string `json:"form"`
  208. Query map[string]string `json:"query"`
  209. JSON json.RawMessage `json:"json"`
  210. } `json:"request"`
  211. Mocks playground.Mocks `json:"mocks"`
  212. Files []struct {
  213. Path string `json:"path"`
  214. Text string `json:"text"`
  215. Dir bool `json:"dir"`
  216. } `json:"files"`
  217. }
  218. // workspace is the drive the playground page starts with (defaultFiles in
  219. // static/assets/playground.js), which the samples rely on.
  220. func workspace(t *testing.T) []playground.File {
  221. t.Helper()
  222. img := image.NewRGBA(image.Rect(0, 0, 640, 400))
  223. for y := 0; y < 400; y++ {
  224. for x := 0; x < 640; x++ {
  225. img.Set(x, y, color.RGBA{uint8(x / 3), 90, uint8(y / 2), 255})
  226. }
  227. }
  228. var pngBuf, jpgBuf bytes.Buffer
  229. if err := png.Encode(&pngBuf, img); err != nil {
  230. t.Fatal(err)
  231. }
  232. if err := jpeg.Encode(&jpgBuf, img, nil); err != nil {
  233. t.Fatal(err)
  234. }
  235. text := func(p, s string) playground.File { return playground.File{Path: p, Data: []byte(s)} }
  236. return []playground.File{
  237. text("web:/Playground/main.agi", `sendResp("main");`),
  238. text("web:/Playground/lib/format.js", "function formatBytes(n){ return n + \" B\"; }\n"),
  239. text("user:/Desktop/hello.txt", "Hello from the playground drive.\n"),
  240. text("user:/Documents/notes.md", "# Notes\n\n- one\n- two\n"),
  241. text("user:/Documents/data.json", `{"project": "ArozOS", "tags": ["nas", "agi"], "stars": 1200}`),
  242. text("user:/Documents/scores.csv", "name,score\nAmy,92\n"),
  243. {Path: "user:/Photo/gradient.png", Data: pngBuf.Bytes()},
  244. {Path: "user:/Photo/sunset.jpg", Data: jpgBuf.Bytes()},
  245. }
  246. }
  247. // TestSamplesRun runs every shipped sample through the engine, set up as
  248. // the playground page would, so a sample that no longer works fails here.
  249. func TestSamplesRun(t *testing.T) {
  250. samples, err := loadSamples("samples")
  251. if err != nil {
  252. t.Fatalf("loadSamples: %v", err)
  253. }
  254. if len(samples) == 0 {
  255. t.Fatal("no samples found")
  256. }
  257. seen := map[string]bool{}
  258. for _, s := range samples {
  259. s := s
  260. t.Run(s.ID, func(t *testing.T) {
  261. if seen[s.ID] {
  262. t.Fatalf("duplicate sample id %q", s.ID)
  263. }
  264. seen[s.ID] = true
  265. if s.Group == "" || s.Summary == "" {
  266. t.Errorf("sample needs a group and a summary")
  267. }
  268. var setup sampleSetup
  269. if len(s.Setup) > 0 {
  270. if err := json.Unmarshal(s.Setup, &setup); err != nil {
  271. t.Fatalf("setup: %v", err)
  272. }
  273. }
  274. // The page saves the sample on the drive before it runs it.
  275. files := append(workspace(t), playground.File{Path: s.Path, Data: []byte(s.Code)})
  276. for _, f := range setup.Files {
  277. files = append(files, playground.File{Path: f.Path, Dir: f.Dir, Data: []byte(f.Text)})
  278. }
  279. req := playground.Request{
  280. Script: s.Path,
  281. Code: s.Code,
  282. Method: setup.Request.Method,
  283. Form: setup.Request.Form,
  284. Query: setup.Request.Query,
  285. Mocks: setup.Mocks,
  286. Files: files,
  287. TimeoutSec: 20,
  288. User: playground.User{Username: "developer", Admin: true, QuotaTotal: -1},
  289. }
  290. if len(setup.Request.JSON) > 0 {
  291. req.Body = string(setup.Request.JSON)
  292. req.ContentType = "application/json"
  293. }
  294. res := playground.Run(req, playground.Hooks{})
  295. if res.Error != nil {
  296. t.Fatalf("%s: %s\n%s", res.Error.Kind, res.Error.Message, res.Error.Stack)
  297. }
  298. for _, l := range res.Console {
  299. if strings.Contains(l.Text, "Runtime Error") || strings.Contains(l.Text, "not found") {
  300. t.Errorf("console: %s", l.Text)
  301. }
  302. }
  303. if res.Status != 200 {
  304. t.Errorf("status %d", res.Status)
  305. }
  306. if res.Response == "" && !res.Upgraded {
  307. t.Errorf("empty response")
  308. }
  309. })
  310. }
  311. }
  312. func TestPlayMode(t *testing.T) {
  313. for id, want := range map[string]string{"filelib": "runs", "http": "HTTP", "llm": "LLM", "cnn": "CNN", "git": "Services", "sqlite": "Services"} {
  314. if got := playMode(id); got != want {
  315. t.Errorf("playMode(%q) = %q, want %q", id, got, want)
  316. }
  317. }
  318. // Every library the engine runs natively must be marked as running.
  319. for _, lib := range playground.NativeLibs {
  320. if lib == "http" || lib == "llm" || lib == "cnn" || lib == "sqlite" || lib == "sysinfo" {
  321. continue
  322. }
  323. if playMode(lib) != "runs" {
  324. t.Errorf("%s runs natively but the docs say it is mocked", lib)
  325. }
  326. }
  327. }