diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 0c2002ae40127..3b451efeffc90 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -43,6 +43,13 @@ instead. API tests are not run by `npx hereby validate` without `--api`. If as part of your change you edit tools, benchmarks, or other ancillary parts of the repository, you should instead run `npx hereby validate --all` to ensure *everything* is working correctly. This will most accurately approximate the results of a full CI run. +## Go Concurrency Tests + +Prefer `testing/synctest` over wall-clock sleeps, polling loops, or `time.After` watchdogs in in-memory concurrency tests. +Create the test's goroutines, channels, timers, and mocks inside `synctest.Test`, and use `synctest.Wait()` before asserting that work remains blocked. +Use the bubble's fake clock when testing deadlines or timer behavior; do not rely on elapsed wall time to distinguish slow execution from a deadlock. +Keep real-time waits where tests depend on external processes, real network I/O, or OS file-watcher events that synctest cannot control. + ## Compiler Features, Fixes, and Tests When fixing a bug or implementing a new feature, at least one minimal test case should always be added in advance to verify the fix. diff --git a/tsc/internal/api/session_completion_test.go b/tsc/internal/api/session_completion_test.go index 4e1a217030e99..a2e5790772893 100644 --- a/tsc/internal/api/session_completion_test.go +++ b/tsc/internal/api/session_completion_test.go @@ -2,7 +2,7 @@ package api import ( "testing" - "time" + "testing/synctest" "github.com/microsoft/TypeScript/tsc/internal/api/requestfilesystem" "github.com/microsoft/TypeScript/tsc/internal/bundled" @@ -497,65 +497,54 @@ func TestCompletionWithSymbolsAndExistingImportDoesNotDeadlock(t *testing.T) { t.Skip("bundled files are not embedded") } - const fileName = "/home/projects/p/src/index.ts" - const content = "import { otherValue } from \"./export\";\nsomeV" - projectSession, _ := projecttestutil.Setup(map[string]any{ - "/home/projects/p/tsconfig.json": `{ "compilerOptions": { "module": "esnext", "target": "esnext" } }`, - "/home/projects/p/src/export.ts": "export const otherValue = 0; export const someValue = 1;", - fileName: content, - }) - defer projectSession.Close() - projectSession.Configure(lsutil.UserPreferences{ - IncludeCompletionsForModuleExports: core.TSTrue, - IncludeCompletionsForImportStatements: core.TSTrue, - }) + // Detect blocked goroutines rather than treating slow race builds as deadlocks. + synctest.Test(t, func(t *testing.T) { + const fileName = "/home/projects/p/src/index.ts" + const content = "import { otherValue } from \"./export\";\nsomeV" + projectSession, _ := projecttestutil.Setup(map[string]any{ + "/home/projects/p/tsconfig.json": `{ "compilerOptions": { "module": "esnext", "target": "esnext" } }`, + "/home/projects/p/src/export.ts": "export const otherValue = 0; export const someValue = 1;", + fileName: content, + }) + defer projectSession.Close() + projectSession.Configure(lsutil.UserPreferences{ + IncludeCompletionsForModuleExports: core.TSTrue, + IncludeCompletionsForImportStatements: core.TSTrue, + }) - session := NewLSPSession(projectSession, nil) - defer session.Close() + session := NewLSPSession(projectSession, nil) + defer session.Close() - snapshotResp, err := session.handleCreateSnapshot(t.Context(), &CreateSnapshotParams{ - OpenFiles: []DocumentIdentifier{{FileName: fileName}}, - PrepareAutoImports: &DocumentIdentifier{FileName: fileName}, - }) - assert.NilError(t, err) - proj, err := session.handleGetDefaultProjectForFile(t.Context(), &GetDefaultProjectForFileParams{ - Snapshot: snapshotResp.Snapshot, - File: DocumentIdentifier{FileName: fileName}, - }) - assert.NilError(t, err) - assert.Assert(t, proj != nil, "file should resolve to a default project") + snapshotResp, err := session.handleCreateSnapshot(t.Context(), &CreateSnapshotParams{ + OpenFiles: []DocumentIdentifier{{FileName: fileName}}, + PrepareAutoImports: &DocumentIdentifier{FileName: fileName}, + }) + assert.NilError(t, err) + proj, err := session.handleGetDefaultProjectForFile(t.Context(), &GetDefaultProjectForFileParams{ + Snapshot: snapshotResp.Snapshot, + File: DocumentIdentifier{FileName: fileName}, + }) + assert.NilError(t, err) + assert.Assert(t, proj != nil, "file should resolve to a default project") - // IncludeSymbol pins completion to the single persistent API checker. When - // ranking the auto-import completion, the existing import makes the view - // consult that checker. This used to try to acquire the same checker again - // and deadlock. - type completionResult struct { - completions *CompletionInfoResponse - err error - } - result := make(chan completionResult, 1) - go func() { - completions, e := session.handleGetCompletionsAtPosition(t.Context(), &GetCompletionsAtPositionParams{ + // IncludeSymbol pins completion to the single persistent API checker. When + // ranking the auto-import completion, the existing import makes the view + // consult that checker. This used to try to acquire the same checker again + // and deadlock. + completions, err := session.handleGetCompletionsAtPosition(t.Context(), &GetCompletionsAtPositionParams{ Snapshot: snapshotResp.Snapshot, Project: proj.Handle, File: DocumentIdentifier{FileName: fileName}, Position: uint32(len(content)), IncludeSymbol: true, }) - result <- completionResult{completions: completions, err: e} - }() - - select { - case completion := <-result: - assert.NilError(t, completion.err) - assert.Assert(t, completion.completions != nil, "expected a completion list") - for _, entry := range completion.completions.Entries { + assert.NilError(t, err) + assert.Assert(t, completions != nil, "expected a completion list") + for _, entry := range completions.Entries { if entry.Name == "someValue" { return } } t.Fatal("expected auto-import completion for someValue") - case <-time.After(10 * time.Second): - t.Fatal("completion request deadlocked while examining an existing import") - } + }) } diff --git a/tsc/internal/contentmapper/host_test.go b/tsc/internal/contentmapper/host_test.go index fea31f26df558..b51c5032e1781 100644 --- a/tsc/internal/contentmapper/host_test.go +++ b/tsc/internal/contentmapper/host_test.go @@ -11,7 +11,7 @@ import ( "sync" "sync/atomic" "testing" - "time" + "testing/synctest" "github.com/microsoft/TypeScript/tsc/internal/ast" "github.com/microsoft/TypeScript/tsc/internal/contentmapper" @@ -341,57 +341,54 @@ func TestRunnerTransformResponseValidation(t *testing.T) { func TestHostClosesProcessWhenReadLoopFails(t *testing.T) { t.Parallel() - closed := make(chan struct{}, 1) - spawner := contentmapper.SpawnerFunc(func(command []string, dir string, stderr io.Writer) (io.ReadWriteCloser, error) { - client, server := net.Pipe() - go func() { - defer server.Close() - protocol := ipc.NewJSONRPCProtocol(server) - message, err := protocol.ReadMessage() - assert.NilError(t, err) - assert.Equal(t, message.Method, contentmapper.MethodInitialize) - assert.NilError(t, protocol.WriteResponse(message.ID, contentmapper.InitializeResult{ - PositionEncoding: contentmapper.PositionEncodingUTF8, - DiagnosticSource: "mapper", - })) - _, err = server.Write([]byte("oops\n")) - assert.NilError(t, err) - }() - return &closeSignalReadWriteCloser{ReadWriteCloser: client, closed: closed}, nil + synctest.Test(t, func(t *testing.T) { + closed := make(chan struct{}, 1) + spawner := contentmapper.SpawnerFunc(func(command []string, dir string, stderr io.Writer) (io.ReadWriteCloser, error) { + client, server := net.Pipe() + go func() { + defer server.Close() + protocol := ipc.NewJSONRPCProtocol(server) + message, err := protocol.ReadMessage() + assert.NilError(t, err) + assert.Equal(t, message.Method, contentmapper.MethodInitialize) + assert.NilError(t, protocol.WriteResponse(message.ID, contentmapper.InitializeResult{ + PositionEncoding: contentmapper.PositionEncodingUTF8, + DiagnosticSource: "mapper", + })) + _, err = server.Write([]byte("oops\n")) + assert.NilError(t, err) + }() + return &closeSignalReadWriteCloser{ReadWriteCloser: client, closed: closed}, nil + }) + host := contentmapper.NewHost(t.Context(), spawner, locale.Default) + defer host.Close() + mapper := &contentmapper.Mapper{Name: "mapper", Exec: []string{"mapper"}} + _, err := host.Transform(mapper, contentmapper.Request{FileName: "/a.vue", Content: ""}) + assert.Assert(t, err != nil) + <-closed }) - host := contentmapper.NewHost(t.Context(), spawner, locale.Default) - defer host.Close() - mapper := &contentmapper.Mapper{Name: "mapper", Exec: []string{"mapper"}} - _, err := host.Transform(mapper, contentmapper.Request{FileName: "/a.vue", Content: ""}) - assert.Assert(t, err != nil) - processClosed := false - select { - case <-closed: - processClosed = true - case <-time.After(time.Second): - processClosed = false - } - assert.Assert(t, processClosed, "mapper process was not closed after its read loop failed") } func TestHostReportsInitializationTimeoutBeforeClosingProcess(t *testing.T) { t.Parallel() - spawner := contentmapper.SpawnerFunc(func(command []string, dir string, stderr io.Writer) (io.ReadWriteCloser, error) { - client, server := net.Pipe() - go func() { - defer server.Close() - _, _ = ipc.NewJSONRPCProtocol(server).ReadMessage() - <-t.Context().Done() - }() - return &exitOnCloseReadWriteCloser{ReadWriteCloser: client}, nil + synctest.Test(t, func(t *testing.T) { + spawner := contentmapper.SpawnerFunc(func(command []string, dir string, stderr io.Writer) (io.ReadWriteCloser, error) { + client, server := net.Pipe() + go func() { + defer server.Close() + _, _ = ipc.NewJSONRPCProtocol(server).ReadMessage() + <-t.Context().Done() + }() + return &exitOnCloseReadWriteCloser{ReadWriteCloser: client}, nil + }) + host := contentmapper.NewHost(t.Context(), spawner, locale.Default) + defer host.Close() + mapper := &contentmapper.Mapper{Name: "mapper", Exec: []string{"mapper"}} + _, err := host.Transform(mapper, contentmapper.Request{FileName: "/a.vue", Content: ""}) + initializeError, ok := errors.AsType[*contentmapper.InitializeError](err) + assert.Assert(t, ok, "expected InitializeError, got %v", err) + assert.Equal(t, initializeError.Kind, contentmapper.InitializeErrorKindNoResponse) }) - host := contentmapper.NewHost(t.Context(), spawner, locale.Default) - defer host.Close() - mapper := &contentmapper.Mapper{Name: "mapper", Exec: []string{"mapper"}} - _, err := host.Transform(mapper, contentmapper.Request{FileName: "/a.vue", Content: ""}) - initializeError, ok := errors.AsType[*contentmapper.InitializeError](err) - assert.Assert(t, ok, "expected InitializeError, got %v", err) - assert.Equal(t, initializeError.Kind, contentmapper.InitializeErrorKindNoResponse) } func TestHostReportsProcessExitBeforeInitialization(t *testing.T) { diff --git a/tsc/internal/execute/build/graph_test.go b/tsc/internal/execute/build/graph_test.go index a283a59921556..93e12e5d84752 100644 --- a/tsc/internal/execute/build/graph_test.go +++ b/tsc/internal/execute/build/graph_test.go @@ -6,7 +6,7 @@ import ( "slices" "strings" "testing" - "time" + "testing/synctest" "github.com/microsoft/TypeScript/tsc/internal/core" "github.com/microsoft/TypeScript/tsc/internal/execute/build" @@ -50,50 +50,47 @@ func TestBuildScheduling(t *testing.T) { } { t.Run(operation.name, func(t *testing.T) { t.Parallel() - sys := newSchedulingTestSystem() - independentStarted := make(chan struct{}) - sys.fs.onRead = func(path tspath.RootedFilePath) { - if path.BaseName() != "index.ts" { - return - } - switch path.Directory().BaseName() { - case "Leaf": - // Independent must start while Leaf is still occupying a builder. - select { - case <-independentStarted: + synctest.Test(t, func(t *testing.T) { + sys := newSchedulingTestSystem() + independentStarted := make(chan struct{}) + sys.fs.onRead = func(path tspath.RootedFilePath) { + if path.BaseName() != "index.ts" { return - case <-time.After(30 * time.Second): - t.Error("Independent was queued behind a builder waiting on Leaf") } - case "Independent": - close(independentStarted) + switch path.Directory().BaseName() { + case "Leaf": + // Independent must start while Leaf is still occupying a builder. + <-independentStarted + case "Independent": + close(independentStarted) + } } - } - command := tsoptions.ParseBuildCommandLine([]string{"--build", "--verbose", "--builders", "2", "Root", "Other"}, sys.FS(), sys.GetCurrentDirectory()) - orchestrator := build.NewOrchestrator(build.Options{Sys: sys, Command: command}) - var result *build.OrchestratorResult - if operation.refsOnly { - result = orchestrator.BuildReferences(t.Context(), operation.project) - } else { - result = orchestrator.Build(t.Context(), operation.project) - } - assert.Equal(t, result.Result.Status, tsc.ExitStatusSuccess) - assert.Equal(t, result.Statistics.Projects, len(operation.order)) - assert.Equal(t, result.Statistics.ProjectsBuilt, len(operation.order)) - reported := []string{} - for line := range strings.SplitSeq(sys.output.String(), "\n") { - if strings.Contains(line, "Building project") { - for _, project := range operation.order { - if strings.Contains(line, "'"+project+"/tsconfig.json'") { - reported = append(reported, project) + command := tsoptions.ParseBuildCommandLine([]string{"--build", "--verbose", "--builders", "2", "Root", "Other"}, sys.FS(), sys.GetCurrentDirectory()) + orchestrator := build.NewOrchestrator(build.Options{Sys: sys, Command: command}) + var result *build.OrchestratorResult + if operation.refsOnly { + result = orchestrator.BuildReferences(t.Context(), operation.project) + } else { + result = orchestrator.Build(t.Context(), operation.project) + } + assert.Equal(t, result.Result.Status, tsc.ExitStatusSuccess) + assert.Equal(t, result.Statistics.Projects, len(operation.order)) + assert.Equal(t, result.Statistics.ProjectsBuilt, len(operation.order)) + reported := []string{} + for line := range strings.SplitSeq(sys.output.String(), "\n") { + if strings.Contains(line, "Building project") { + for _, project := range operation.order { + if strings.Contains(line, "'"+project+"/tsconfig.json'") { + reported = append(reported, project) + } } } } - } - assert.DeepEqual(t, reported, operation.order) - for _, project := range []string{"Leaf", "Middle", "Independent", "Root", "Other"} { - assert.Equal(t, sys.FS().FileExists(sys.GetCurrentDirectory().ResolveFile(project+"/dist/index.js")), slices.Contains(operation.order, project)) - } + assert.DeepEqual(t, reported, operation.order) + for _, project := range []string{"Leaf", "Middle", "Independent", "Root", "Other"} { + assert.Equal(t, sys.FS().FileExists(sys.GetCurrentDirectory().ResolveFile(project+"/dist/index.js")), slices.Contains(operation.order, project)) + } + }) }) } } diff --git a/tsc/internal/execute/tsctests/contentmapper_watch_test.go b/tsc/internal/execute/tsctests/contentmapper_watch_test.go index 14257005a5139..8f5b6b96b234f 100644 --- a/tsc/internal/execute/tsctests/contentmapper_watch_test.go +++ b/tsc/internal/execute/tsctests/contentmapper_watch_test.go @@ -7,7 +7,7 @@ import ( "sync" "sync/atomic" "testing" - "time" + "testing/synctest" "github.com/microsoft/TypeScript/tsc/internal/contentmapper" "github.com/microsoft/TypeScript/tsc/internal/execute" @@ -241,65 +241,60 @@ func TestContentMapperWatchLifecycle(t *testing.T) { } { t.Run(test.name, func(t *testing.T) { t.Parallel() - const configFileName = "/home/src/workspaces/project/tsconfig.json" - input := &tscInput{files: FileMap{ - configFileName: `{ + synctest.Test(t, func(t *testing.T) { + const configFileName = "/home/src/workspaces/project/tsconfig.json" + input := &tscInput{files: FileMap{ + configFileName: `{ "compilerOptions": { "composite": true }, "contentMappers": [{ "package": "mapper-a", "extensions": [".vue"] }] }`, - "/home/src/workspaces/project/app.vue": `export const app = 1;`, - "/home/src/workspaces/project/node_modules/mapper-a/package.json": contentmappertest.PackageJSON(contentmappertest.VerbatimMapper), - "/home/src/workspaces/project/node_modules/mapper-b/package.json": strings.Replace(contentmappertest.PackageJSON(contentmappertest.VerbatimMapper), `"version": "1.0.0"`, `"version": "2.0.0"`, 1), - }} - testSys := newTestSys(input, false) - closed := make(chan struct{}, 3) - spawner := &recordingContentMapperSpawner{inner: contentmappertest.NewSpawner(), closed: closed} - sys := &recordingContentMapperSystem{TestSys: testSys, spawner: spawner} - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - - result := execute.CommandLine(ctx, sys, test.args, testSys) - assert.Assert(t, result.Watcher != nil) - assert.Equal(t, spawner.spawns.Load(), int32(1)) - assert.Equal(t, spawner.closes.Load(), int32(0)) - - testSys.writeFileNoError(configFileName, `{ + "/home/src/workspaces/project/app.vue": `export const app = 1;`, + "/home/src/workspaces/project/node_modules/mapper-a/package.json": contentmappertest.PackageJSON(contentmappertest.VerbatimMapper), + "/home/src/workspaces/project/node_modules/mapper-b/package.json": strings.Replace(contentmappertest.PackageJSON(contentmappertest.VerbatimMapper), `"version": "1.0.0"`, `"version": "2.0.0"`, 1), + }} + testSys := newTestSys(input, false) + closed := make(chan struct{}, 3) + spawner := &recordingContentMapperSpawner{inner: contentmappertest.NewSpawner(), closed: closed} + sys := &recordingContentMapperSystem{TestSys: testSys, spawner: spawner} + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + + result := execute.CommandLine(ctx, sys, test.args, testSys) + assert.Assert(t, result.Watcher != nil) + assert.Equal(t, spawner.spawns.Load(), int32(1)) + assert.Equal(t, spawner.closes.Load(), int32(0)) + + testSys.writeFileNoError(configFileName, `{ "compilerOptions": { "composite": true }, "contentMappers": [{ "package": "mapper-b", "extensions": [".vue"] }] }`) - testSys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: configFileName}}) - result.Watcher.DoCycle() + testSys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: configFileName}}) + result.Watcher.DoCycle() - assert.Equal(t, spawner.spawns.Load(), int32(2)) - assert.Equal(t, spawner.closes.Load(), int32(1)) - <-closed + assert.Equal(t, spawner.spawns.Load(), int32(2)) + assert.Equal(t, spawner.closes.Load(), int32(1)) + <-closed - testSys.writeFileNoError(configFileName, `{ "compilerOptions": { "composite": true } }`) - testSys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: configFileName}}) - result.Watcher.DoCycle() + testSys.writeFileNoError(configFileName, `{ "compilerOptions": { "composite": true } }`) + testSys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: configFileName}}) + result.Watcher.DoCycle() - assert.Equal(t, spawner.closes.Load(), int32(2)) - <-closed + assert.Equal(t, spawner.closes.Load(), int32(2)) + <-closed - testSys.writeFileNoError(configFileName, `{ + testSys.writeFileNoError(configFileName, `{ "compilerOptions": { "composite": true }, "contentMappers": [{ "package": "mapper-a", "extensions": [".vue"] }] }`) - testSys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: configFileName}}) - result.Watcher.DoCycle() - - assert.Equal(t, spawner.spawns.Load(), int32(3)) - assert.Equal(t, spawner.closes.Load(), int32(2)) - cancel() - closedAfterCancellation := false - select { - case <-closed: - closedAfterCancellation = true - case <-time.After(time.Second): - closedAfterCancellation = false - } - assert.Assert(t, closedAfterCancellation, "content mapper process was not closed after cancellation") - assert.Equal(t, spawner.closes.Load(), int32(3)) + testSys.mockWatchBackend.SendEvents([]fswatch.Event{{Kind: fswatch.EventUpdate, Path: configFileName}}) + result.Watcher.DoCycle() + + assert.Equal(t, spawner.spawns.Load(), int32(3)) + assert.Equal(t, spawner.closes.Load(), int32(2)) + cancel() + <-closed + assert.Equal(t, spawner.closes.Load(), int32(3)) + }) }) } } diff --git a/tsc/internal/execute/tsctests/watcher_race_test.go b/tsc/internal/execute/tsctests/watcher_race_test.go index 39ff61f3c6b85..351a2a0b1e040 100644 --- a/tsc/internal/execute/tsctests/watcher_race_test.go +++ b/tsc/internal/execute/tsctests/watcher_race_test.go @@ -6,7 +6,7 @@ import ( "strings" "sync" "testing" - "time" + "testing/synctest" "github.com/microsoft/TypeScript/tsc/internal/execute" "github.com/microsoft/TypeScript/tsc/internal/execute/tsc" @@ -270,28 +270,20 @@ func TestWatcherAlternatingModifyAndDoCycle(t *testing.T) { func TestBuildWatchStopsWhenContextIsCancelled(t *testing.T) { t.Parallel() - - sys := newTestSys(&tscInput{ - files: FileMap{ - "/home/src/workspaces/project/tsconfig.json": `{"compilerOptions":{"composite":true},"files":["index.ts"]}`, - "/home/src/workspaces/project/index.ts": `export const x = 1;`, - }, - }, false) - ctx, cancel := context.WithCancel(context.Background()) - cancel() - - resultCh := make(chan tsc.CommandLineResult, 1) - go func() { - resultCh <- execute.CommandLine(ctx, sys, []string{"--build", "--watch"}, sys) - }() - - select { - case result := <-resultCh: + synctest.Test(t, func(t *testing.T) { + sys := newTestSys(&tscInput{ + files: FileMap{ + "/home/src/workspaces/project/tsconfig.json": `{"compilerOptions":{"composite":true},"files":["index.ts"]}`, + "/home/src/workspaces/project/index.ts": `export const x = 1;`, + }, + }, false) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + result := execute.CommandLine(ctx, sys, []string{"--build", "--watch"}, sys) assert.Equal(t, result.Status, tsc.ExitStatusSuccess) assert.Assert(t, result.Watcher != nil) - case <-time.After(2 * time.Second): - t.Fatal("build watch did not stop after context cancellation") - } + }) } func TestWatcherStartsFromExistingBuildInfo(t *testing.T) { diff --git a/tsc/internal/ipc/conn_async_test.go b/tsc/internal/ipc/conn_async_test.go index 2218cc2652634..a3ac8b02d3397 100644 --- a/tsc/internal/ipc/conn_async_test.go +++ b/tsc/internal/ipc/conn_async_test.go @@ -8,6 +8,7 @@ import ( "strings" "sync" "testing" + "testing/synctest" "time" "github.com/microsoft/TypeScript/tsc/internal/ipc" @@ -119,20 +120,13 @@ func TestAsyncConnRunWaitsForHandlers(t *testing.T) { func TestAsyncConnRunCancelsHandlersOnEOF(t *testing.T) { t.Parallel() + synctest.Test(t, func(t *testing.T) { + id := jsonrpc.NewIDString("1") + protocol := &queuedProtocol{messages: []*ipc.Message{{ID: id, Method: "request"}}} + conn := ipc.NewAsyncConnWithProtocol(nil, protocol, contextHandler{}) - id := jsonrpc.NewIDString("1") - protocol := &queuedProtocol{messages: []*ipc.Message{{ID: id, Method: "request"}}} - conn := ipc.NewAsyncConnWithProtocol(nil, protocol, contextHandler{}) - - runDone := make(chan error, 1) - go func() { runDone <- conn.Run(t.Context()) }() - - select { - case err := <-runDone: - assert.NilError(t, err) - case <-time.After(time.Second): - t.Fatal("Run did not cancel active handlers after EOF") - } + assert.NilError(t, conn.Run(t.Context())) + }) } func TestAsyncConnResponseWriteFailureWithNilTransport(t *testing.T) { @@ -223,25 +217,27 @@ func TestAsyncConnCallReturnsWhenPeerCloses(t *testing.T) { func TestAsyncConnCallAfterReadLoopFailureReturnsImmediately(t *testing.T) { t.Parallel() - client, server := net.Pipe() - defer client.Close() - defer server.Close() - conn := ipc.NewAsyncConn(client, noOpHandler{}) - runDone := make(chan error, 1) - go func() { runDone <- conn.Run(t.Context()) }() - - _, err := server.Write([]byte("oops\n")) - assert.NilError(t, err) - assert.ErrorContains(t, <-runDone, "invalid header") - go func() { _, _ = io.Copy(io.Discard, server) }() - - ctx, cancel := context.WithTimeout(t.Context(), time.Second) - defer cancel() - _, err = conn.Call(ctx, "transform", nil) - assert.Assert(t, errors.Is(err, ipc.ErrConnClosed), "expected ErrConnClosed, got %v", err) - assert.Assert(t, !errors.Is(err, context.DeadlineExceeded), "call waited for its context deadline: %v", err) - err = conn.Notify(ctx, "changed", nil) - assert.Assert(t, errors.Is(err, ipc.ErrConnClosed), "expected ErrConnClosed, got %v", err) + synctest.Test(t, func(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + conn := ipc.NewAsyncConn(client, noOpHandler{}) + runDone := make(chan error, 1) + go func() { runDone <- conn.Run(t.Context()) }() + + _, err := server.Write([]byte("oops\n")) + assert.NilError(t, err) + assert.ErrorContains(t, <-runDone, "invalid header") + go func() { _, _ = io.Copy(io.Discard, server) }() + + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + _, err = conn.Call(ctx, "transform", nil) + assert.Assert(t, errors.Is(err, ipc.ErrConnClosed), "expected ErrConnClosed, got %v", err) + assert.Assert(t, !errors.Is(err, context.DeadlineExceeded), "call waited for its context deadline: %v", err) + err = conn.Notify(ctx, "changed", nil) + assert.Assert(t, errors.Is(err, ipc.ErrConnClosed), "expected ErrConnClosed, got %v", err) + }) } func TestAsyncConnTerminalErrorIncludesResponseWriteFailure(t *testing.T) { @@ -263,52 +259,44 @@ func TestAsyncConnTerminalErrorIncludesResponseWriteFailure(t *testing.T) { func TestAsyncConnRunWaitsForRequestAfterPeerCloses(t *testing.T) { t.Parallel() - client, server := net.Pipe() - defer server.Close() - handler := &blockingHandler{ - started: make(chan struct{}, 1), - release: make(chan struct{}), - } - defer func() { + synctest.Test(t, func(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + handler := &blockingHandler{ + started: make(chan struct{}, 1), + release: make(chan struct{}), + } + defer func() { + select { + case <-handler.release: + return + default: + close(handler.release) + } + }() + conn := ipc.NewAsyncConn(server, handler) + runDone := make(chan error, 1) + go func() { runDone <- conn.Run(t.Context()) }() + + clientProtocol := ipc.NewJSONRPCProtocol(client) + assert.NilError(t, clientProtocol.WriteRequest(jsonrpc.NewIDInt(1), "transform", nil)) + <-handler.started + assert.NilError(t, client.Close()) + + synctest.Wait() select { - case <-handler.release: - return + case err := <-runDone: + t.Fatalf("connection stopped while request handler was blocked: %v", err) default: close(handler.release) } - }() - conn := ipc.NewAsyncConn(server, handler) - runDone := make(chan error, 1) - go func() { runDone <- conn.Run(t.Context()) }() - - clientProtocol := ipc.NewJSONRPCProtocol(client) - assert.NilError(t, clientProtocol.WriteRequest(jsonrpc.NewIDInt(1), "transform", nil)) - select { - case <-handler.started: - // Request handler started. - case <-time.After(time.Second): - t.Fatal("request handler did not start") - } - assert.NilError(t, client.Close()) - - handlerBlocked := false - select { - case err := <-runDone: - t.Fatalf("connection stopped while request handler was blocked: %v", err) - case <-time.After(100 * time.Millisecond): - handlerBlocked = true - } - assert.Assert(t, handlerBlocked) - close(handler.release) - select { - case err := <-runDone: + err := <-runDone assert.ErrorContains(t, err, "ipc: failed to write response") _, err = conn.Call(t.Context(), "transform", nil) assert.ErrorContains(t, err, "ipc: failed to write response") err = conn.Notify(t.Context(), "changed", nil) assert.ErrorContains(t, err, "ipc: failed to write response") - case <-time.After(time.Second): - t.Fatal("connection did not stop after request handler completed") - } + }) } diff --git a/tsc/internal/project/background/queue_test.go b/tsc/internal/project/background/queue_test.go index 9a1392c7d5885..71c78447f0eeb 100644 --- a/tsc/internal/project/background/queue_test.go +++ b/tsc/internal/project/background/queue_test.go @@ -5,7 +5,7 @@ import ( "sync" "sync/atomic" "testing" - "time" + "testing/synctest" "github.com/microsoft/TypeScript/tsc/internal/project/background" "gotest.tools/v3/assert" @@ -92,35 +92,35 @@ func TestQueue(t *testing.T) { t.Run("CloseWaitsForActiveTasks", func(t *testing.T) { t.Parallel() - q := background.NewQueue() - started := make(chan struct{}) - finish := make(chan struct{}) - closeStarted := make(chan struct{}) - closed := make(chan struct{}) + synctest.Test(t, func(t *testing.T) { + q := background.NewQueue() + started := make(chan struct{}) + finish := make(chan struct{}) + closed := make(chan struct{}) - q.Enqueue(context.Background(), func(ctx context.Context) { - close(started) - <-finish + q.Enqueue(context.Background(), func(ctx context.Context) { + close(started) + <-finish + }) + <-started + + go func() { + q.Close() + close(closed) + }() + + synctest.Wait() + var closeReturned bool + select { + case <-closed: + closeReturned = true + default: + closeReturned = false + } + assert.Check(t, !closeReturned, "Close returned before the active task completed") + + close(finish) + <-closed }) - <-started - - go func() { - close(closeStarted) - q.Close() - close(closed) - }() - - <-closeStarted - var closeReturned bool - select { - case <-closed: - closeReturned = true - case <-time.After(100 * time.Millisecond): - closeReturned = false - } - assert.Check(t, !closeReturned, "Close returned before the active task completed") - - close(finish) - <-closed }) }