Files
openchamber-android-native/third_party/mygo/internal/tsgen/tsgen_test.go
T
OpenChamber 6c0ee61750 feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
2026-11-18 13:22:59 +08:00

299 lines
10 KiB
Go

package tsgen
import (
"context"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/egoist/mygo/internal/tsgen/internal/fixture"
)
func modelOf(name string, svc any) Service {
t := reflect.TypeOf(svc)
s := Service{Name: name, Type: t}
ctxType := reflect.TypeFor[context.Context]()
errType := reflect.TypeFor[error]()
for i := range t.NumMethod() {
m := t.Method(i)
ft := m.Type
meth := Method{Name: m.Name, Variadic: ft.IsVariadic()}
start := 1
if ft.NumIn() > 1 && ft.In(1) == ctxType {
meth.HasCtx, start = true, 2
}
for j := start; j < ft.NumIn(); j++ {
meth.Params = append(meth.Params, ft.In(j))
}
if ft.NumOut() > 0 && ft.Out(0) != errType {
meth.Result = ft.Out(0)
}
if vm, ok := t.Elem().MethodByName(m.Name); ok {
meth.PC = vm.Func.Pointer()
} else {
meth.PC = m.Func.Pointer()
}
s.Methods = append(s.Methods, meth)
}
return s
}
func generate(t *testing.T) string {
t.Helper()
tasks := modelOf("Tasks", &fixture.Tasks{})
for i, m := range tasks.Methods {
if m.Name == "Watch" {
tasks.Methods[i].Channels = []bool{false, true}
}
}
out, err := Generate(Model{
Services: []Service{tasks},
Events: []Event{{Name: "task-added", Type: reflect.TypeFor[fixture.Task]()}},
})
if err != nil {
t.Fatal(err)
}
return string(out)
}
func TestGenerate(t *testing.T) {
src := generate(t)
for _, want := range []string{
`import { bind, event, type Channel } from "mygo-runtime";`,
`export type Status = "todo" | "done";`,
`export type Priority = 0 | 1 | 2;`,
"export interface FixtureChannel {\n name: string;\n}",
"export interface FixtureRecord {\n values: Record<string, string>;\n}",
"export interface FixturePromise {\n done: boolean;\n}",
"/** Task is a unit of work. */\nexport interface Task {",
" id: number;\n",
" /** Title of the task. */\n title: string;\n",
" status: Status;\n",
" priority: Priority;\n",
" tags: string[];\n",
" due: string | null;\n",
" meta?: Record<string, unknown>;\n",
" parent?: Task;\n",
" channel?: FixtureChannel;\n",
" record?: FixtureRecord;\n",
" promise?: FixturePromise;\n",
" count: string;\n",
" countPtr: string | null;\n",
" raw: unknown;\n",
" data: string;\n",
" scores: Record<number, number>;\n",
" matrix: number[][];\n",
" children: (Task | null)[];\n",
" extra: { A: boolean };\n",
" NoTag: string;\n",
" createdAt: string;\n",
"export interface PageTask {\n items: Task[];\n next?: string;\n}",
"/** Tasks manages tasks. */\nexport const Tasks = {",
" /** List returns tasks with the given status. */\n list: bind<[Status, number], PageTask>(\"Tasks.List\", (status: Status, limit: number) => [status, limit]),",
" * It fails when a task has no title.\n",
" add: bind<[...Task[]], void>(\"Tasks.Add\", (...tasks: Task[]) => [...tasks]),",
" count: bind<[], number>(\"Tasks.Count\", () => []),",
" delete: bind<[number], void>(\"Tasks.Delete\", (arg0: number) => [arg0]),",
" dispatch: bind<[string, string], void>(\"Tasks.Dispatch\", (call_: string, call__: string) => [call_, call__]),",
" dispatchMany: bind<[...string[]], void>(\"Tasks.DispatchMany\", (...call_: string[]) => [...call_]),",
" watch: bind<[Status, Channel<Task>], void>(\"Tasks.Watch\", (status: Status, updates: Channel<Task>) => [status, updates]),",
` taskAdded: event<Task>("task-added"),`,
} {
if !strings.Contains(src, want) {
t.Errorf("generated code is missing:\n%s", want)
}
}
for _, unwanted := range []string{"Secret", "internal:", "ctx", "function call", "declare global"} {
if strings.Contains(src, unwanted) {
t.Errorf("generated code should not contain %q", unwanted)
}
}
if t.Failed() {
t.Log(src)
}
}
// TestGeneratedCodeTypeChecks runs tsc on the output, against the
// mygo-runtime package of the workspace, when the repository's dev
// dependencies are installed (bun install).
func TestGeneratedCodeTypeChecks(t *testing.T) {
tsc, err := filepath.Abs("../../node_modules/.bin/tsc")
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(tsc); err != nil {
t.Skip("tsc not installed; run bun install")
}
runtimePkg, err := filepath.Abs("../../packages/runtime")
if err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(runtimePkg, "dist", "index.d.ts")); err != nil {
t.Skip("mygo-runtime not built; run bun run build")
}
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, "node_modules"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink(runtimePkg, filepath.Join(dir, "node_modules", "mygo-runtime")); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "client.ts"), []byte(generate(t)), 0o644); err != nil {
t.Fatal(err)
}
usage := `import { Channel, runtime } from "mygo-runtime";
import { Tasks, events, type Task, type Status, type FixtureChannel, type PageTask } from "./client";
const s: Status = "todo";
const page = await Tasks.list(s, 10);
const ac = new AbortController();
const canceled: Promise<PageTask> = Tasks.list.with({ signal: ac.signal })(s, 10);
void canceled;
const first: Task | undefined = page.items[0];
const channel: FixtureChannel | undefined = first?.channel;
channel?.name.toUpperCase();
first?.record?.values["key"]?.toUpperCase();
const done: boolean | undefined = first?.promise?.done;
await Tasks.add({ id: 1, title: "x", status: "done", priority: 2, tags: [], due: null, count: "1", countPtr: "9007199254740993", raw: null, data: "", scores: {}, matrix: [], children: [], extra: { A: true }, NoTag: "", createdAt: "" });
await Tasks.dispatch("first", "second");
await Tasks.dispatchMany("first", "second");
const off = events.taskAdded.on((t) => t.title.toUpperCase());
off();
runtime().window.minimize();
const updates = new Channel<Task>();
const watching = Tasks.watch("todo", updates);
for await (const task of updates) task.title.toUpperCase();
updates.onmessage = (task) => task.id.toFixed();
updates.close();
await watching;
// @ts-expect-error a channel of another type
Tasks.watch("todo", new Channel<string>());
// @ts-expect-error invalid enum value
Tasks.list("nope", 1);
`
if err := os.WriteFile(filepath.Join(dir, "usage.ts"), []byte(usage), 0o644); err != nil {
t.Fatal(err)
}
cmd := exec.Command(tsc, "--noEmit", "--strict", "--noUncheckedIndexedAccess", "--target", "es2022",
"--module", "esnext", "--moduleResolution", "bundler", "--lib", "es2022,dom", "client.ts", "usage.ts")
cmd.Dir = dir
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("tsc failed: %v\n%s", err, out)
}
}
// Without streaming parameters, an app's Channel keeps its original name.
func TestChannelNameWithoutStreaming(t *testing.T) {
out, err := Generate(Model{Events: []Event{{Name: "channel", Type: reflect.TypeFor[fixture.Channel]()}}})
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"export interface Channel {", `channel: event<Channel>("channel")`} {
if !strings.Contains(string(out), want) {
t.Errorf("client lacks %s:\n%s", want, out)
}
}
}
func TestNames(t *testing.T) {
for in, want := range map[string]string{"Greet": "greet", "GetUserByID": "getUserByID", "URLFor": "urlFor", "ID": "id", "already": "already"} {
if got := camel(in); got != want {
t.Errorf("camel(%q) = %q, want %q", in, got, want)
}
}
for in, want := range map[string]string{"progress": "progress", "file-changed": "fileChanged", "app:ready": "appReady", "a b": "aB", "123": `"123"`} {
if got := eventKey(in); got != want {
t.Errorf("eventKey(%q) = %q, want %q", in, got, want)
}
}
for in, want := range map[string]string{"User": "User", "Page[github.com/x/app.User]": "PageUser", "Pair[main.A,main.B]": "PairAB"} {
if got := typeName(in); got != want {
t.Errorf("typeName(%q) = %q, want %q", in, got, want)
}
}
if safeName("new") != "new_" || safeName("x") != "x" {
t.Error("safeName")
}
}
func TestMethodNameCollision(t *testing.T) {
service := Service{Name: "Links", Type: reflect.TypeFor[struct{}](), Methods: []Method{{Name: "URL"}, {Name: "Url"}}}
out, err := Generate(Model{Services: []Service{service}})
if err == nil || !strings.Contains(err.Error(), "URL") || !strings.Contains(err.Error(), "Url") || !strings.Contains(err.Error(), "url") {
t.Fatalf("Generate = %s, %v; want an error identifying the colliding methods", out, err)
}
if len(out) != 0 {
t.Error("a collision returned a partial client")
}
}
func TestEventNameCollision(t *testing.T) {
out, err := Generate(Model{Events: []Event{
{Name: "file-changed", Type: reflect.TypeFor[string]()},
{Name: "file_changed", Type: reflect.TypeFor[string]()},
}})
if err == nil || !strings.Contains(err.Error(), "file-changed") || !strings.Contains(err.Error(), "file_changed") || !strings.Contains(err.Error(), "fileChanged") {
t.Fatalf("Generate = %s, %v; want an error identifying the colliding events", out, err)
}
if len(out) != 0 {
t.Error("a collision returned a partial client")
}
}
func TestMethodNamesAreScopedToServices(t *testing.T) {
out, err := Generate(Model{Services: []Service{
{Name: "First", Type: reflect.TypeFor[struct{}](), Methods: []Method{{Name: "URL"}}},
{Name: "Second", Type: reflect.TypeFor[struct{}](), Methods: []Method{{Name: "Url"}}},
}})
if err != nil {
t.Fatal(err)
}
for _, want := range []string{`bind<[], void>("First.URL", () => [])`, `bind<[], void>("Second.Url", () => [])`} {
if !strings.Contains(string(out), want) {
t.Errorf("client lacks %s", want)
}
}
}
func TestValidate(t *testing.T) {
type bad struct {
F func()
}
type ok struct {
F func() `json:"-"`
C chan int
}
for _, typ := range []reflect.Type{reflect.TypeFor[chan int](), reflect.TypeFor[bad](), reflect.TypeFor[map[struct{}]int](), reflect.TypeFor[[]complex64]()} {
if Validate(typ) == nil {
t.Errorf("Validate(%v) should fail", typ)
}
}
if err := Validate(reflect.TypeFor[fixture.Task]()); err != nil {
t.Errorf("Validate(Task) = %v", err)
}
_ = ok{}
}
func TestStructFieldConflicts(t *testing.T) {
type A struct{ Name, OnlyA string }
type B struct {
Name string
Tag string `json:"Name2"`
}
type C struct {
A
B
Own string `json:"own"`
}
var names []string
for _, f := range structFields(reflect.TypeFor[C]()) {
names = append(names, f.name)
}
// Name is ambiguous at the same depth and dropped, like encoding/json.
if got := strings.Join(names, ","); got != "OnlyA,Name2,own" {
t.Errorf("fields = %s", got)
}
}