Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/headless-fuzz-package-2268.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Limit headless fuzz testing to the named package (#2268 by @J4ck1e2000).
54 changes: 52 additions & 2 deletions cmd/nsgo/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,14 @@ func runTests(ctx context.Context, p *project, opts testOptions) error {
return err
}
}
pattern := "./..."
fuzz := opts.target == "" && testFuzzEnabled(opts.args)
if fuzz {
// Go only fuzzes one package. Prepare and probe only that package too.
pattern = "."
}
p.Build.LDFlags = append(p.Build.LDFlags, opts.ldflags...)
if err := p.prepareCatalogs(ctx, "./...", false); err != nil {
if err := p.prepareCatalogs(ctx, pattern, false); err != nil {
return err
}
if opts.fps && !slices.Contains([]string{"macos", "windows", "linux", "ios_simulator", "web", "android"}, opts.target) {
Expand Down Expand Up @@ -226,11 +232,14 @@ func runTests(ctx context.Context, p *project, opts testOptions) error {
if profile != "" {
runFlags = append([]string{"-coverprofile=" + profile}, flags...)
}
cmd, err := command("./...", uniqueTags(append(runTags, "nsgocheck")), runFlags)
cmd, err := command(pattern, uniqueTags(append(runTags, "nsgocheck")), runFlags)
if err != nil {
return err
}
runs := []testCommand{{cmd: cmd}}
if fuzz {
return reportTests(opts, runs...)
}
// As check does, NSGo's own repository also tests the dev client, whose files build only with nsgodev, unless the run's tags already include it; there are no automation-only dev tests. Its coverage profile goes to a file of its own, appended to the run's once both have ended, since go test would overwrite the first run's.
var cover, devCover string
if dev, ok := devClientPattern(p.Dir); ok && p.steps == nil && !slices.Contains(runTags, "nsgodev") {
Expand Down Expand Up @@ -282,6 +291,47 @@ func devClientPattern(dir string) (string, bool) {
return "./" + sub, true
}

// testFuzzEnabled reports whether the forwarded flags ask cmd/go to fuzz, not
// whether the test binary's arguments contain the spelling of a fuzz flag.
func testFuzzEnabled(args []string) bool {
var enabled bool
for len(args) > 0 {
arg := args[0]
args = args[1:]
if arg == "-args" || arg == "--args" || arg == "--" {
break
}
flag, ok := strings.CutPrefix(arg, "-")
if !ok {
continue
}
flag, value, hasValue := strings.Cut(strings.TrimPrefix(flag, "-"), "=")
name, testPrefix := strings.CutPrefix(flag, "test.")
switch name {
case "bench", "benchtime", "blockprofile", "blockprofilerate", "count", "coverprofile", "cpu", "cpuprofile",
"fuzz", "fuzzminimizetime", "fuzztime", "list", "memprofile", "memprofilerate", "mutexprofile",
"mutexprofilefraction", "outputdir", "parallel", "run", "shuffle", "skip", "timeout", "trace":
case "C", "asmflags", "buildmode", "compiler", "covermode", "coverpkg", "debug-actiongraph",
"debug-runtime-trace", "debug-trace", "exec", "gccgoflags", "gcflags", "installsuffix",
"ldflags", "mod", "modfile", "o", "overlay", "p", "pgo", "pkgdir", "tags", "toolexec", "vet":
if testPrefix {
continue
}
default:
continue
}
// Unlike an unknown test-binary flag, a known value flag can
// consume the next token even when it starts with a dash.
if !hasValue && len(args) > 0 {
value, args = args[0], args[1:]
}
if name == "fuzz" {
enabled = value != ""
}
}
return enabled
}

// testTagArgs lets command-line tags replace earlier ones without dropping the tool's tags.
// It separates flags needed by go list and resolves the coverage path against -outputdir and dir.
func testTagArgs(dir string, tags, args []string) (runTags, flags, listFlags []string, cover string) {
Expand Down
97 changes: 96 additions & 1 deletion cmd/nsgo/test_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"hash/crc32"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
Expand Down Expand Up @@ -223,7 +224,12 @@ func TestRunTestsKeepsTheTreeWithFlags(t *testing.T) {
if err != nil {
t.Fatal(err)
}
for i, args := range [][]string{{"-count", "1"}, {"-count=1", "-update", "golden"}, {"-count=1", "-args", "-update=golden"}} {
for i, args := range [][]string{
{"-count", "1"},
{"-count=1", "-update", "golden"},
{"-count=1", "-args", "-update=golden"},
{"-count=1", "-skip", "-fuzz=not-a-flag", "-args", "--", "-test.fuzz=not-a-go-flag"},
} {
mark := filepath.Join(t.TempDir(), "mark")
if err := runTests(t.Context(), p, testOptions{args: args, env: []string{"TREE_MARK=" + mark}}); err != nil {
t.Errorf("%d: runTests with %q: %v", i, args, err)
Expand All @@ -234,6 +240,95 @@ func TestRunTestsKeepsTheTreeWithFlags(t *testing.T) {
}
}

func TestTestFuzzEnabled(t *testing.T) {
for _, c := range []struct {
args []string
want bool
}{
{nil, false},
{[]string{"-fuzz", "FuzzX"}, true},
{[]string{"--fuzz=FuzzX"}, true},
{[]string{"--test.fuzz", "FuzzX"}, true},
{[]string{"-test.fuzz=FuzzX"}, true},
{[]string{"-fuzz="}, false},
{[]string{"-fuzz", "FuzzX", "--test.fuzz="}, false},
{[]string{"-run", "-fuzz=literal"}, false},
{[]string{"-ldflags", "-test.fuzz=literal"}, false},
{[]string{"-test.run", "-args", "-fuzz=FuzzX"}, true},
{[]string{"-v", "-short", "-custom", "-fuzz=FuzzX"}, true},
{[]string{"-args", "-fuzz=FuzzX"}, false},
{[]string{"--args", "-test.fuzz=FuzzX"}, false},
{[]string{"--", "-fuzz=FuzzX"}, false},
{[]string{"-fuzz=FuzzX", "-args", "-test.fuzz="}, true},
{[]string{"-fuzztime=3s", "-fuzzminimizetime=1x"}, false},
} {
if got := testFuzzEnabled(c.args); got != c.want {
t.Errorf("testFuzzEnabled(%q) = %t, want %t", c.args, got, c.want)
}
}
}

func TestRunTestsFuzzesOnlyNamedPackage(t *testing.T) {
if testing.Short() {
t.Skip("runs go test")
}
dir := t.TempDir()
// The named package has a child and is also eligible for the extra dev-client run.
writeFiles(t, dir, map[string]string{
"go.mod": "module " + nsgoModule + "\n\ngo 1.26\n",
"internal/dev/dev.go": "package dev\n",
"internal/dev/fuzz_test.go": `//go:build nsgocheck

package dev

import ("os"; "testing")

func FuzzX(f *testing.F) {
// Without an explicit seed, the body only runs when Go actually fuzzes.
f.Fuzz(func(t *testing.T, _ string) {
if err := os.WriteFile(os.Getenv("FUZZ_MARK"), []byte("fuzzed"), 0o600); err != nil {
t.Fatal(err)
}
})
}
`,
"internal/dev/sub/sub_test.go": `package sub

import "testing"

func TestSub(t *testing.T) { t.Fatal("fuzz run included a subpackage") }
`,
})
exe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
mark := filepath.Join(dir, "fuzzed")
cmd := exec.CommandContext(t.Context(), exe, "-test.run=^TestCLIProcess$", "--", "test", "./internal/dev",
"-fuzz", "^FuzzX$", "-fuzztime=16x", "-parallel=1", "-timeout=1m")
cmd.Dir = dir
cmd.Env = append(os.Environ(), "GOWORK=off", "GOFLAGS=", "NSGO_CLI_PROCESS=1", "FUZZ_MARK="+mark)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("headless fuzz: %v\n%s", err, out)
}
if strings.Contains(string(out), "testing the dev client with nsgodev") {
t.Errorf("fuzz run repeated the dev-client tests:\n%s", out)
}
if got, err := os.ReadFile(mark); err != nil || string(got) != "fuzzed" {
t.Fatalf("the nsgocheck fuzz target did not run: %q, %v\n%s", got, err, out)
}
}

func TestTargetTestsRejectFuzzFlags(t *testing.T) {
for _, args := range [][]string{{"-fuzz", "FuzzX"}, {"-test.fuzz=FuzzX"}} {
err := runTests(t.Context(), nil, testOptions{target: "web", args: args})
if err == nil || !strings.Contains(err.Error(), "target runs cannot accept") {
t.Errorf("target flags %q: %v, want an explicit argument error", args, err)
}
}
}

// Repository tests must exercise the dev-only code as well as the normal build, under their own suite, from the root and from the dev client's directory alike, and a dev-only failure must fail the command and its combined report.
func TestRunTestsIncludesTheDevClient(t *testing.T) {
if testing.Short() {
Expand Down
4 changes: 3 additions & 1 deletion docs/architecture/tool.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ If the process exits without ending its running tests, as a panic on another gor

Given a TSX entry rather than a directory, it runs `TestSteps` instead, which opens the entry on the network, lets it run 1.2 s and takes the steps standard input holds, none from a terminal (`tsxtest.RunSteps`, NSH's `nsh test <entry>`). A directory without `nsgo.yaml` runs every package under it, and one ending in `/...` names its tree, so the tool alone tests libraries and this repository, on a simulator or phone too, where the app the tests run in takes the ID `generatedID` makes of the directory's name, `dev.nsgo.` and its ASCII letters and digits, since Android's packages refuse hyphens and Apple's bundle IDs underscores; the TSX tests it adds skip `testdata` and directories holding an `nsgo.yaml` or `go.mod` of their own. `-bench` passes `-bench` and, unless `-run` is given, `-run '^$'`; `go test -json` ends benchmarks with no event, so each result line it prints counts as a passed test. `-run` filters; `-trace` sets `NSGO_TEST_TRACE`, under which `nsgotest` prints each batch under its step with its items and the commit's time.

In NSGo's own repository, a headless run of the root, `internal` or `internal/dev` then tests `internal/dev` again with `nsgodev`, as `nsgo check` vets it, unless the run's tags already include it, so the dev client's tests run in CI: with the same filters, flags and environment, a later `-tags` taking the earlier's place as in Go, and its packages named with ` [nsgodev]` in the shared tally and JUnit report. It runs after the first fails, as go test goes on past a failing package, but not after an interruption, and its `-coverprofile` is appended to the first run's.
An active headless `-fuzz` (or `-test.fuzz`) selects `.` instead of `./...` for catalog preparation, the `go list` probe for the JSON policy, and `go test`, because Go can fuzz only one package. Flags passed to the test binary after `-args` do not select fuzzing.

In NSGo's own repository, a headless run of the root, `internal` or `internal/dev` then tests `internal/dev` again with `nsgodev`, as `nsgo check` vets it, unless the run fuzzes or already has that tag. This covers the dev client's tests in CI with the same filters, flags and environment, a later `-tags` taking the earlier's place as in Go, and with ` [nsgodev]` after package names in the shared tally and JUnit report. It runs after the first fails, as go test goes on past a failing package, but not after an interruption, and its `-coverprofile` is appended to the first run's.

After the path and optional `--`, headless runs forward Go test arguments. Target runs forward `-short`, `-count`, `-cpu`, `-parallel`, `-failfast` and `-fullpath` as test-binary flags, accepting their `-test.` aliases too; unsupported arguments fail before listing, building or finding a device (`parseTargetTestFlags`). On a target `-run` and `-timeout` belong before the path so discovery and the process deadline agree. Discovery uses the top-level part of a subtest filter and receives the supported runtime flags too. A group whose children all skipped is reported and counted as skipped, recursively, unless the group itself failed; a group with a passing child stays passed. This applies to headless and target runs, and its JUnit skip message includes the children's reasons. Each target process yields one result that counts in the tally whatever its name (`parseTestOutput`): a run whose `-run` reached exactly one subtest at the depth it selects, as `Test/sub` or `Test/sub/leaf` does, reports that subtest unless the test failed outside it, and otherwise the top-level test reports its own result, never its first subtest's. Libraries keep Go's in-process `-count` and `-cpu` repetitions, whose results combine elapsed time and preserve a failure over a pass or skip. A package that links the native host launches a fresh process for each count and CPU combination, because phone and web hosts can open only one app per process; repeated results carry `[run N]`, screenshots go into `run-N` subdirectories, and each invocation has its own timeout. A nonpositive count reports zero tests, and `-failfast` stops launching further tests and repetitions after the first failure.

Expand Down
2 changes: 2 additions & 0 deletions docs/public/en/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ go tool nsgo test

Given a directory without `nsgo.yaml`, such as a library or the module's root, `test` takes every package under it; a directory may also end in `/...`, as Go's patterns do. It takes one directory, and stops with an error at a second: to test several, give it a directory above them, or run it once for each. `go tool nsgo check` takes packages the same way and vets them.

To fuzz headless, pass `-fuzz` (or `-test.fuzz`) after the directory: `go tool nsgo test ./pkg -fuzz FuzzX -fuzztime 3s`. Go fuzzes one package at a time, so this selects only the directory's own package, not its subpackages.

Go tests and `check` use the same JSON policy as `build`: they select the first `encoding/json` implementation unless a package or dependency imports `encoding/json/v2` or `encoding/json/jsontext`, or `GOEXPERIMENT` already selects either mode. Mini program target checks always use the first implementation, as their builds do.

Tests check reactive graph ownership: access signals and scopes on the app's goroutine, and use `cx.Post` from workers. A call from another goroutine that lands while the app is idle panics with a `Scope.Post` diagnostic; `-race` catches the rest. Internal engine panics still fail tests; in a shipped app they stop the affected engine and report its stack to the host. Development builds also check ownership; release builds omit the check; WebAssembly development and test builds omit the goroutine-ID assertion because browser callbacks may resume on a browser-managed goroutine; the other test checks still run there.
Expand Down
2 changes: 2 additions & 0 deletions docs/public/zh/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,8 @@ go tool nsgo test

传入没有 `nsgo.yaml` 的目录(例如库或模块根目录)时,`test` 会处理其下的所有包;目录也可以像 Go 的包模式那样以 `/...` 结尾。它只接受一个目录,遇到第二个会报错退出:要测试多个目录,就传入它们共同的上级目录,或逐个运行。`go tool nsgo check` 以同样的方式选取并检查包。

要无头运行模糊测试,在目录之后传入 `-fuzz`(或 `-test.fuzz`):`go tool nsgo test ./pkg -fuzz FuzzX -fuzztime 3s`。Go 每次只能对一个包进行模糊测试,因此该命令只选取目录自身的包,不包含子包。

测试会检查响应式图的 goroutine 归属:信号和作用域应在应用的 goroutine 上访问,工作 goroutine 通过 `cx.Post` 调度。在应用空闲时从其他 goroutine 发起的调用会 panic,并提示使用 `Scope.Post`;其余情况由 `-race` 检出。引擎内部 panic 仍会使测试失败;发布的应用则停止受影响的引擎,并把堆栈报告给宿主。开发构建也检查归属,发布构建不包含这项检查;WebAssembly 的开发构建和测试构建不使用 goroutine ID 检查,因为浏览器回调可能在浏览器管理的 goroutine 上恢复;其他测试检查照常进行。

`app.Post(func() { state.Set(value) })` 把工作排到应用的响应式图所在的 goroutine 上,在下一个步骤或等待稳定时运行:无头运行时是测试 goroutine,在目标平台上是引擎 goroutine。可以从测试或桩出来的工作 goroutine 调用它,再用 `app.Settle()` 或等待读取结果视图。函数可以继续投递,同一个步骤会一并运行;它不执行步骤,也不调用 `t.Fatal`,因为在目标平台上它不在测试 goroutine 上运行。
Expand Down
1 change: 1 addition & 0 deletions skills/nsgo/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ Use `app.Surface("title:Settings")` for the same view queries, input steps, resi
```sh
go tool nsgo check # vet; -target web,android vets those targets instead, all every available one
go tool nsgo test # headless; -run as go test's, -target macos|ios|ios_simulator|android|web|all on a platform
go tool nsgo test ./pkg -fuzz FuzzX -fuzztime 3s # headless fuzzing of ./pkg only, not its subpackages
```

Vetting and tests use the same Go JSON policy as `build`. Headless `nsgo test -- -c` compiles tests without running them; compiler failures remain visible in the console and JUnit report.
Expand Down
Loading