testing

package
v1.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package testing is the test model of the editor (SPEC §10.32, D42, D43): the tree of test items by controller, the run profiles, the run requests with their include and exclude lists, the results of the runs with VS Code's precedence of states and its durations (the last 16 runs, saved with the workspace's state of §10.10 with the output trimmed), the continuous runs that start again when a file of their items changes, and the coverage a run measured with its sums.

It has no user interface and imports no Glutter, and it does not know the extension API: the host (internal/gui/exthost) turns the calls of an extension's controller into calls of this package. Nothing here touches the real configuration of the user.

Threads. The Service is safe for use from several goroutines. Changes are announced to the subscribers (Service.Subscribe) one event at a time and in the order they were made, on the goroutine that made them or on the one that delivers the events of another; a subscriber must not block, and the window hands the work over to its UI thread (CLAUDE.md). The functions the controllers give (their run handlers, resolve and refresh functions) are called without any lock held, from the goroutine of the caller.

Ported from VS Code: src/vs/workbench/contrib/testing/common/testService.ts (running the requests, the default profiles of a group), testResult.ts (the results, their tasks, the counts, the output), getComputedState.ts and testingStates.ts (the states and their precedence, the computed states and durations), testResultService.ts (the list of results), testResultStorage.ts (the saved results), testProfileService.ts (the profiles and their defaults), testCoverage.ts (the coverage and its sums) and testingContinuousRunService.ts (the continuous runs), and src/vs/workbench/api/common/extHostTesting.ts (the rules of a request).

Index

Constants

View Source
const (
	// PercentTotal is the combined statement, declaration and branch coverage (the default), PercentStatement the statement coverage
	// and PercentMinimum the lowest of the three.
	PercentTotal     = "totalCoverage"
	PercentStatement = "statement"
	PercentMinimum   = "minimum"
)

The values of testing.displayedCoveragePercent.

View Source
const (
	CoverageRed    = "red"
	CoverageYellow = "yellow"
	CoverageGreen  = "green"
)

Coverage colors, the names CoverageColor gives.

View Source
const (
	// MaxResults is how many results are kept (VS Code's RETAIN_MAX_RESULTS); SPEC §10.32 fixes it.
	MaxResults = 16
	// MaxSavedOutput is how much of the output of a result is saved: the last bytes of it, in all its tasks.
	MaxSavedOutput = 1 << 20
	// MaxLiveOutput is how much output a task keeps while it runs: when more arrives the oldest is dropped.
	MaxLiveOutput = 16 << 20
	// MaxSavedTests is how many tests of a result a saved state may hold, so that a damaged file cannot make the model huge.
	MaxSavedTests = 100000
)

Limits of the model.

View Source
const IDSeparator = "\x00"

IDSeparator separates the parts of the id of an item: the id of its controller, then the id of the item among the children of the controller, and so on down the tree (VS Code's TestId). An id of a controller alone is the root of its tree.

View Source
const NoDuration time.Duration = -1

NoDuration is the duration of a test that has none (VS Code's undefined).

View Source
const StateVersion = 1

StateVersion is the version of the saved state of the results.

Variables

View Source
var DefaultBarThresholds = BarThresholds{Red: 0, Yellow: 60, Green: 90}

DefaultBarThresholds are VS Code's: red from 0, yellow from 60 and green from 90.

Functions

func BarFill

func BarFill(pct float64) int

BarFill is how many of the 16 pixels of a bar are filled: floored, so that a bar is full only at 100%.

func ClampedPercent

func ClampedPercent(c Count) float64

ClampedPercent is the share that was covered, held between 0 and 1 (VS Code's percent); a count with nothing to cover is full.

func ControllerOf

func ControllerOf(id string) string

ControllerOf is the id of the controller the id belongs to.

func CoverageColor

func CoverageColor(pct float64, t BarThresholds) string

CoverageColor is the color of a bar that is pct full (from 0 to 1): of the colors whose threshold pct reaches, the one with the highest threshold; red when it reaches none. A threshold of 0 is never reached, so a bar below every threshold is red (VS Code's rule).

func DisplayPercent

func DisplayPercent(value float64, precision int) string

DisplayPercent writes a share from 0 to 1 as a percentage with the precision given, never showing 100% for a share that only rounds up to it.

func DisplayedStat

func DisplayedStat(statement Count, branch, declaration *Count, method string) float64

DisplayedStat is the share the bars write as their number, as testing.displayedCoveragePercent says.

func IDsToRoot

func IDsToRoot(id string) []string

IDsToRoot lists the ids from the item up to its controller's id, both included.

func IsAncestorID

func IsAncestorID(ancestor, id string) bool

IsAncestorID reports whether ancestor is an id above id: the controller, or the item some levels up. An id is not its own ancestor.

func JoinID

func JoinID(controllerID string, path ...string) string

JoinID makes the id of the item at the path of ids below a controller.

func ParentID

func ParentID(id string) string

ParentID is the id of the parent of an item, which for a top item is its controller's id; it is empty for the id of a controller.

func SplitID

func SplitID(id string) []string

SplitID splits an id into the id of the controller and the ids of the items down to it.

func TotalPercent

func TotalPercent(statement Count, branch, declaration *Count) float64

TotalPercent is the total coverage of the three counts, from 0 to 1; with nothing to cover it is 1.

Types

type AmbiguousRequest

type AmbiguousRequest struct {
	Group Group
	// Tests are the ids of the items to run; the id of a controller stands for all its tests.
	Tests []string
	// Exclude are the items not to run.
	Exclude       []string
	Continuous    bool
	PreserveFocus bool
}

AmbiguousRequest asks to run tests of a group with whatever profiles the group has for them (VS Code's AmbiguousRunTestsRequest).

type BarThresholds

type BarThresholds struct{ Red, Yellow, Green float64 }

BarThresholds are the lowest percentages (0 to 100) that have the colors of a coverage bar (testing.coverageBarThresholds).

func ThresholdsOf

func ThresholdsOf(v any) BarThresholds

ThresholdsOf reads the value of testing.coverageBarThresholds: an object with the numbers red, yellow and green; a missing or invalid member keeps its default, and a number is held between 0 and 100.

type BranchDetail

type BranchDetail struct {
	Executed int
	Location *Range
	Label    string
}

BranchDetail is a branch of a statement and how many times it ran.

type Capabilities

type Capabilities struct {
	Run, Debug, Coverage                       bool
	HasNonDefault, HasConfigurable, Continuous bool
}

Capabilities are the groups that some profile of a controller can run for an item, as the context keys testing.hasRunnableTests, hasDebuggableTests and hasCoverableTests, and whether some profile is a second one of its group or can be configured or run continuously.

type ChangeReason

type ChangeReason int

ChangeReason says why a test of a result changed.

const (
	// ChangeComputedState is a change of the state or duration the test shows because of its children.
	ChangeComputedState ChangeReason = iota + 1
	// ChangeOwnState is a change of the test's own state or duration.
	ChangeOwnState
	// ChangeNewMessage is a message added to the test.
	ChangeNewMessage
)

type Controller

type Controller struct {
	// contains filtered or unexported fields
}

Controller is a controller registered with a Service.

func (*Controller) AddProfile

func (c *Controller) AddProfile(spec ProfileSpec) (int, error)

AddProfile adds a run profile and returns its id. It fails with TestingProfileInvalid for no label, an unknown group or no Run function.

func (*Controller) Dispose

func (c *Controller) Dispose()

Dispose removes the controller with its items and profiles, and stops the continuous runs of its profiles.

func (*Controller) ID

func (c *Controller) ID() string

ID is the id of the controller.

func (*Controller) Remove

func (c *Controller) Remove(id string)

Remove takes the item and its descendants out of the tree; the results keep what they know of them.

func (*Controller) RemoveProfile

func (c *Controller) RemoveProfile(id int)

RemoveProfile removes a profile, and stops the continuous runs that use it.

func (*Controller) SetLabel

func (c *Controller) SetLabel(label string)

SetLabel renames the controller.

func (*Controller) UpdateProfile

func (c *Controller) UpdateProfile(id int, label *string, isDefault *bool)

UpdateProfile changes the label or the default of a profile; nil leaves the member as it is. A change of the default is remembered as the user's choice (VS Code does the same for an extension that changes it).

func (*Controller) Upsert

func (c *Controller) Upsert(item Item) error

Upsert adds the item to the tree, or replaces the item that has its id, keeping its place among its siblings and its children. ControllerID and ParentID of the item are set by the model from its ID, which must be a JoinID under this controller's id. It fails with TestingItemInvalid for an id that is not under the controller or is the controller's own, and with TestingItemParentUnknown when the parent is not in the tree.

type ControllerInfo

type ControllerInfo struct{ ID, Label string }

ControllerInfo describes a registered controller.

type ControllerOptions

type ControllerOptions struct {
	// ID is the id of the controller: not empty and without the IDSeparator; Label is its name.
	ID, Label string
	// Resolve loads the children of the item with the id, or of the whole tree for the controller's own id (VS Code's resolveHandler);
	// nil when the controller does not load on demand.
	Resolve func(ctx context.Context, id string) error
	// Refresh is called by the Refresh Tests command; nil when the controller cannot be refreshed.
	Refresh func(ctx context.Context) error
}

ControllerOptions are what a controller is registered with.

type Count

type Count struct{ Covered, Total int }

Count is how many of the things of a kind were covered (VS Code's ICoverageCount).

func (Count) Percent

func (c Count) Percent() float64

Percent is the share that was covered, from 0 to 1; a count with no things is fully covered.

type Counts

type Counts [numStates]int

Counts is how many tests are in each state, by state (VS Code's TestStateCount).

func (Counts) MaxState

func (c Counts) MaxState() State

MaxState is the state of the highest priority that has tests, and StateUnset for none (VS Code's maxCountPriority).

func (Counts) Total

func (c Counts) Total() int

Total is the number of tests.

type Coverage

type Coverage struct {
	// contains filtered or unexported fields
}

Coverage is the coverage a task of a run reported: the files, and the sums for the folders above them. It is safe for concurrent use.

func (*Coverage) Append

func (c *Coverage) Append(fc FileCoverage)

Append adds the coverage of a file; a file reported again replaces its numbers, and the sums of the folders above it change by the difference (VS Code's TestCoverage.append). A file with no ID gets one.

func (*Coverage) Computed

func (c *Coverage) Computed(uri string) (FileCoverage, bool)

Computed returns the coverage of the file or folder at the URI: the numbers the controller gave for a file, and the sum of the files below it for a folder (VS Code's getComputedForUri).

func (*Coverage) Details

func (c *Coverage) Details(ctx context.Context, uri string) (Details, error)

Details loads the details of the file at the URI with the loader of the profile that measured it, once: the details are kept until the file is reported again. It fails with TestingCoverageUnknownFile for a URI that is no file of the coverage and with TestingCoverageNoLoader when the profile has no loader.

func (*Coverage) Files

func (c *Coverage) Files() []FileCoverage

Files lists the files that were reported, in the order they were first reported.

func (*Coverage) Total

func (c *Coverage) Total() (FileCoverage, bool)

Total is the sum of all the files, and false when there are none.

func (*Coverage) Tree

func (c *Coverage) Tree() []CoverageNode

Tree is the tree of the files and folders: the nodes under the scheme and the authority of the URIs, so that a single scheme and authority give the folders of the workspace at the top. With several schemes or authorities there is a root for each.

type CoverageLoader

type CoverageLoader func(ctx context.Context, file FileCoverage) (Details, error)

CoverageLoader loads the details of the coverage of a file.

type CoverageNode

type CoverageNode struct {
	// Name is the last part of the path, Coverage the numbers of the node and IsFile says that the controller reported the file.
	Name     string
	Coverage FileCoverage
	IsFile   bool
	Children []CoverageNode
}

CoverageNode is a file or a folder of the coverage tree.

type CoverageService

type CoverageService struct {
	// contains filtered or unexported fields
}

CoverageService keeps which coverage is open and whether the editors show it inline (VS Code's TestCoverageService). A result that ends with coverage opens it, one that ends without closes any; removing the result of the open coverage closes it. It is made over a Service and is safe for concurrent use; the listeners are called on the goroutine that changed it, outside its lock.

func NewCoverageService

func NewCoverageService(svc *Service) *CoverageService

NewCoverageService makes a service that follows the results of svc. Dispose stops it.

func (*CoverageService) Close

func (c *CoverageService) Close()

Close closes the open coverage, if any.

func (*CoverageService) Dispose

func (c *CoverageService) Dispose()

Dispose stops following the results.

func (*CoverageService) OnChange

func (c *CoverageService) OnChange(fn func()) (stop func())

OnChange registers a function called when the open coverage or the inline setting changes; the returned function removes it.

func (*CoverageService) Open

func (c *CoverageService) Open(res *Result, taskID string)

Open opens the coverage of a task of a result, and does nothing when the task has none.

func (*CoverageService) Selected

func (c *CoverageService) Selected() (SelectedCoverage, bool)

Selected is the open coverage, and false when none is open.

func (*CoverageService) SetShowInline

func (c *CoverageService) SetShowInline(on bool)

SetShowInline sets whether the editors show the coverage inline.

func (*CoverageService) ShowInline

func (c *CoverageService) ShowInline() bool

ShowInline says whether the editors show the coverage inline: the ranges of text, the counts and the branches, not only the gutter.

type DeclarationDetail

type DeclarationDetail struct {
	Name     string
	Executed int
	Location Range
}

DeclarationDetail is a function or another declaration and how many times it ran.

type DetailKind

type DetailKind int

DetailKind says what a DetailRange is a range of. The order is the order a tie of two ranges is broken in: a declaration comes first, so that a function of one statement still gets the range of its statement.

const (
	// DetailDeclaration is a function or other declaration.
	DetailDeclaration DetailKind = iota
	// DetailStatement is a statement.
	DetailStatement
	// DetailBranch is a branch of a statement.
	DetailBranch
)

type DetailRange

type DetailRange struct {
	Range Range
	// Primary says that the range is the start of its detail (the first piece, when the detail was cut by one inside it); the count of
	// times it ran is written there.
	Primary bool
	Kind    DetailKind
	// Executed is how many times the statement, branch or declaration ran.
	Executed int
	// Statement is the index in Details.Statements of the statement (and of the statement a branch belongs to) and Branch the index of the
	// branch in it; Declaration is the index in Details.Declarations. The ones that do not apply are -1.
	Statement, Branch, Declaration int
}

DetailRange is a stretch of the text of a file and the detail that covers it.

func BuildDetailRanges

func BuildDetailRanges(d Details) []DetailRange

BuildDetailRanges cuts the details of a file into ranges that do not overlap, in the order of the text: where a detail holds another (a function with its statements, a statement with a nested one) the outer one keeps the pieces around the inner one. A branch with no location is the empty range at the end of its statement.

func (DetailRange) Hit

func (d DetailRange) Hit() bool

Hit says whether the range ran.

type Details

type Details struct {
	Statements   []StatementDetail
	Declarations []DeclarationDetail
}

Details are the lines of a file's coverage.

type Event

type Event struct {
	Kind         EventKind
	ControllerID string
	IDs          []string
	Removed      bool
	Result       *Result
	Change       ResultChange
	Removals     []*Result
	Test         *ItemChange
}

Event is a change of the model.

type EventKind

type EventKind int

EventKind says what an Event is about.

const (
	// EventControllers is a controller added or removed (Event.ControllerID).
	EventControllers EventKind = iota + 1
	// EventTree is a change of the tree of a controller: Event.IDs are the items added, changed or removed (Event.Removed).
	EventTree
	// EventProfiles is a change of the run profiles or of their defaults.
	EventProfiles
	// EventResult is a change of the list of results (Event.Change says what, Event.Result which).
	EventResult
	// EventTest is a change of a test in a result (Event.Test).
	EventTest
	// EventRunning is a change of whether a run is going on (Service.IsRunning).
	EventRunning
	// EventContinuous is a continuous run started or stopped, or a change of the profile of one (Event.IDs has its test, empty for all).
	EventContinuous
	// EventCoverage is coverage added to the result's task (Event.Result).
	EventCoverage
)

type ExternalRun

type ExternalRun struct {
	Request RunRequest
	// Persist keeps the result in the saved state.
	Persist bool
}

ExternalRun is a run a controller starts on its own, without being asked: a watcher that runs tests when files change.

type FileCoverage

type FileCoverage struct {
	// ID identifies the file in its coverage: the model gives one when the controller gave none.
	ID string
	// URI is file:///path of the file or folder.
	URI string
	// Statement is the statement coverage; Branch and Declaration are nil when not measured.
	Statement   Count
	Branch      *Count
	Declaration *Count
	// Data is the value of the controller's own, passed back to the loader of the details.
	Data any
}

FileCoverage is the coverage of a file, or the sum of the files below a folder.

func TotalsFromDetails

func TotalsFromDetails(uri string, d Details) FileCoverage

TotalsFromDetails counts the details: the statements that ran, their branches that ran and the declarations that ran (VS Code's totalFromCoverageDetails; VS Code adds the statements that ran to the total, a slip that this does not copy).

func (FileCoverage) TotalPercent

func (f FileCoverage) TotalPercent() float64

TotalPercent is the coverage of the file as one number: the statements, the branches and the declarations counted together (the formula of Clover, VS Code's getTotalCoveragePercent).

type Group

type Group int

Group is a kind of run profile; the values are VS Code's TestRunProfileBitset.

const (
	// GroupRun runs the tests.
	GroupRun Group = 1 << 1
	// GroupDebug runs them under a debugger.
	GroupDebug Group = 1 << 2
	// GroupCoverage runs them and measures the coverage.
	GroupCoverage Group = 1 << 3
)

The groups of run profiles.

func (Group) Valid

func (g Group) Valid() bool

Valid reports whether the value is one of the three groups.

type Item

type Item struct {
	// ID is the full id (JoinID) and ControllerID the id of the controller; ParentID is the id of the parent, which for a top item is the
	// controller's id.
	ID           string
	ControllerID string
	ParentID     string
	// URI is the file of the item, empty for none, and Range the place in it.
	URI   string
	Range *Range
	// Label, Description and SortText are the texts of the item.
	Label, Description, SortText string
	// Tags are the tags of the item.
	Tags []string
	// Error is the item's error row, Busy says that the controller is working on the item and CanResolveChildren that its children are
	// loaded when it is expanded.
	Error              string
	Busy               bool
	CanResolveChildren bool
}

Item is a test, or a group of tests, in the tree of a controller: a copy of what the controller said.

func (Item) HasTag

func (it Item) HasTag(tag string) bool

HasTag reports whether the item carries the tag.

type ItemChange

type ItemChange struct {
	ResultID string
	TestID   string
	Reason   ChangeReason
	// PreviousState and PreviousOwnDuration are those before an own change.
	PreviousState       State
	PreviousOwnDuration time.Duration
	// Message is the new message of ChangeNewMessage.
	Message *Message
}

ItemChange is a change of a test in a result (VS Code's TestResultItemChange).

type Location

type Location struct {
	// URI is file:///path/to/file.
	URI   string
	Range Range
}

Location is a place in a file.

type Message

type Message struct {
	Type MessageType
	// Text is the message, Markdown says it is Markdown; for an output message it is a preview of the first bytes without ANSI.
	Text     string
	Markdown bool
	// Expected and Actual are shown as a diff when HasDiff is true.
	Expected, Actual string
	HasDiff          bool
	// Location is the place the message belongs to, nil for none.
	Location *Location
	// StackTrace are the frames of the failure, the innermost first.
	StackTrace []StackFrame
	// ContextValue is a value of the controller's for the message's menus.
	ContextValue string
	// Offset and Length are the place of an output message in the output of its task (counted from the start of the run's output,
	// also when the oldest bytes were dropped); TestID is the test it belongs to.
	Offset, Length int64
	TestID         string
}

Message is something a run says about a test: why it failed, or the output that belongs to it (VS Code's ITestMessage and ITestOutputMessage).

type MessageType

type MessageType int

MessageType says what a Message is.

const (
	// MessageError is the message of a failure.
	MessageError MessageType = iota + 1
	// MessageOutput is a piece of the output of the run that belongs to a test or a place.
	MessageOutput
)

type Options

type Options struct {
	// Logger receives the problems that do not stop a run; nil is slog.Default.
	Logger *slog.Logger
	// Now gives the time; nil is time.Now.
	Now func() time.Time
	// CancelDeadline is how long a cancelled run is waited for before it is ended by force (VS Code's RUN_CANCEL_DEADLINE); zero is
	// 10 seconds.
	CancelDeadline time.Duration
	// Marshal encodes the saved state; nil is json.Marshal. It is a seam for the tests of the failure.
	Marshal func(v any) ([]byte, error)
	// NewID makes the ids of results and tasks; nil makes random ones.
	NewID func() string
}

Options are the options of a Service.

type Pos

type Pos struct{ Line, Col int }

Pos is a place in a file, zero-based, with the column in runes as the buffer counts.

type Profile

type Profile struct {
	// ControllerID and ID identify the profile; the id counts from 1 in each controller.
	ControllerID string
	ID           int
	Label        string
	Group        Group
	// IsDefault says that the group runs the profile without asking, Tag limits it to the items with the tag.
	IsDefault          bool
	Tag                string
	SupportsContinuous bool
	// HasConfigure says that the profile can be configured.
	HasConfigure bool
}

Profile is the public view of a run profile.

func (Profile) Ref

func (p Profile) Ref() ProfileRef

Ref is the reference of the profile.

type ProfileRef

type ProfileRef struct {
	ControllerID string
	ID           int
}

ProfileRef names a profile.

type ProfileRequest

type ProfileRequest struct {
	// ResultID is the result the run reports to; the controller makes its tasks with Service.Result(ResultID).AddTask. Empty for none.
	ResultID  string
	ProfileID int
	// Include are the ids of the items to run that are in the tree; the controller's own id is among them when all its tests run.
	Include []string
	// Exclude are the excluded items that are in the tree below an included one.
	Exclude       []string
	Continuous    bool
	PreserveFocus bool
}

ProfileRequest is what a profile's Run function gets: the part of a RunRequest that is its own, with the items checked against the tree (VS Code's runControllerTestRequest).

type ProfileSpec

type ProfileSpec struct {
	// Label is the name of the profile and Group what it does.
	Label string
	Group Group
	// IsDefault makes the profile one of the defaults of its group, unless the user chose otherwise before (Service.SetGroupDefaults).
	IsDefault bool
	// Tag limits the profile to the items with the tag.
	Tag string
	// SupportsContinuous says that Run honors ProfileRequest.Continuous.
	SupportsContinuous bool
	// Run runs the tests of the request; see ProfileRequest. It is called with no lock held.
	Run func(ctx context.Context, req ProfileRequest) error
	// Configure is called when the user asks to configure the profile; nil when there is nothing to configure.
	Configure func()
	// Trigger says whether the change of the file with the URI starts the continuous run of the item again; nil is the item's own URI.
	Trigger func(item Item, uri string) bool
	// LoadCoverage loads the details of a file's coverage; nil when the profile has none.
	LoadCoverage CoverageLoader
}

ProfileSpec describes a run profile.

type Range

type Range struct{ Start, End Pos }

Range is the text from Start up to End.

type Result

type Result struct {
	// contains filtered or unexported fields
}

Result is the result of a run (VS Code's LiveTestResult and HydratedTestResult). It is made by the model; its methods are safe for concurrent use and return copies.

func (*Result) AddTask

func (r *Result) AddTask(spec TaskSpec) (*Run, error)

AddTask starts a task in the result and returns what to report to. It fails with TestingResultComplete when the result ended.

func (*Result) CompletedAt

func (r *Result) CompletedAt() time.Time

CompletedAt is the time the run ended, and the zero time while it runs.

func (*Result) Counts

func (r *Result) Counts() Counts

Counts are the numbers of tests in each state, by their own states.

func (*Result) Coverage

func (r *Result) Coverage(taskID string) *Coverage

Coverage is the coverage the task reported, or nil.

func (*Result) Hydrated

func (r *Result) Hydrated() bool

Hydrated reports whether the result was read from the saved state.

func (*Result) ID

func (r *Result) ID() string

ID is the id of the result.

func (*Result) IsComplete

func (r *Result) IsComplete() bool

IsComplete reports whether the run ended.

func (*Result) LatestCoverage

func (r *Result) LatestCoverage() *Coverage

LatestCoverage is the coverage of the last task that has any, or nil.

func (*Result) Name

func (r *Result) Name() string

Name is the name of the result: "Test run at" and the time it started.

func (*Result) OtherMessages

func (r *Result) OtherMessages(taskID string) []Message

OtherMessages are the output messages of the task that belong to no test.

func (*Result) Output

func (r *Result) Output(taskID string) ([]byte, int64)

Output is the output of the task that is kept, and the offset of its first byte in the output of the run (it is not zero when the oldest bytes were dropped); nil for an unknown task.

func (*Result) Persist

func (r *Result) Persist() bool

Persist reports whether the result is kept in the saved state.

func (*Result) Request

func (r *Result) Request() RunRequest

Request is the request that made the result.

func (*Result) StartedAt

func (r *Result) StartedAt() time.Time

StartedAt is the time the run started; for a saved result it is the zero time.

func (*Result) Tasks

func (r *Result) Tasks() []TaskInfo

Tasks lists the tasks of the result.

func (*Result) Test

func (r *Result) Test(id string) (TestResult, bool)

Test returns the test with the id in the run.

func (*Result) Tests

func (r *Result) Tests() []TestResult

Tests lists the tests of the run, in the order they were added: parents before their children.

type ResultChange

type ResultChange int

ResultChange says what happened to the list of results.

const (
	// ResultStarted is a live result added.
	ResultStarted ResultChange = iota + 1
	// ResultCompleted is a live result that ended.
	ResultCompleted
	// ResultInserted is a result that came from the saved ones.
	ResultInserted
	// ResultRemoved is the results taken away: cleared, or pushed out by newer ones.
	ResultRemoved
)

type Run

type Run struct {
	// contains filtered or unexported fields
}

Run is a task of a result that a controller reports to (VS Code's TestRun, on the model's side). Its methods do nothing once the task ended or the result was completed.

func (*Run) AddCoverage

func (u *Run) AddCoverage(fc FileCoverage)

AddCoverage reports the coverage of a file in this task.

func (*Run) AddMessage

func (u *Run) AddMessage(id string, m Message)

AddMessage adds a message about the failure of the test to this task. The test is added to the result first.

func (*Run) AppendOutput

func (u *Run) AppendOutput(data []byte, loc *Location, testID string)

AppendOutput adds to the output of the task. With a location or a test the text is remembered as a message of its own that the views can jump to; the test is added to the result when it is in the tree.

func (*Run) End

func (u *Run) End()

End ends the task: the tests that are still queued or running in it become skipped. The result completes with its last task when it was made by a controller on its own (a run the user asked for completes when its handlers returned).

func (*Run) Ended

func (u *Run) Ended() bool

Ended reports whether the task ended.

func (*Run) Ensure

func (u *Run) Ensure(id string) bool

Ensure adds the test and the tests above it to the result, as the tree knows them (VS Code's addTestChainToRun); a test already in the result stays as it is. It reports false when the tree does not have the test.

func (*Run) ResultID

func (u *Run) ResultID() string

ResultID and TaskID identify the task.

func (*Run) SetState

func (u *Run) SetState(id string, state State, d time.Duration)

SetState gives the test a state in this task, and the duration or NoDuration. A test that has a terminal state keeps it or takes a terminal state of a higher priority (VS Code's rule: passed, skipped, failed, errored). The test is added to the result first.

func (*Run) TaskID

func (u *Run) TaskID() string

TaskID is the id of the task in its result.

type RunRequest

type RunRequest struct {
	Targets []RunTarget
	// Exclude are the items not to run; only those below an included item reach the profile that runs it.
	Exclude []string
	// Group is the kind of the profiles of the targets.
	Group Group
	// Continuous says that the run starts again when files change (Service.StartContinuous makes such requests).
	Continuous bool
	// PreserveFocus says that the run was not asked for with the Testing view in front.
	PreserveFocus bool
}

RunRequest is what is run (VS Code's ResolvedTestRunRequest): the targets, and the items left out.

type RunTarget

type RunTarget struct {
	ControllerID string
	ProfileID    int
	// TestIDs are the items to run; the id of the controller itself runs all its tests.
	TestIDs []string
}

RunTarget is the tests one profile runs.

type SelectedCoverage

type SelectedCoverage struct {
	// Coverage is the coverage of one task of a result, ResultID and TaskID name that task.
	Coverage         *Coverage
	ResultID, TaskID string
}

SelectedCoverage is the coverage that is open: the one the Test Coverage view, the editors and the Explorer show.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service is the test model of one window tab: the controllers, the results and the continuous runs.

func NewService

func NewService(opts Options) *Service

NewService makes an empty model.

func (*Service) CancelAll

func (s *Service) CancelAll()

CancelAll cancels every run.

func (*Service) CancelRun

func (s *Service) CancelRun(resultID string)

CancelRun cancels the run that makes the result: the context its profiles run with ends. It does nothing for a result that is not being run by RunTests.

func (*Service) Capabilities

func (s *Service) Capabilities(id string) Capabilities

Capabilities reports what the profiles of the controller can do with the item; an empty id is every profile of every controller.

func (*Service) Children

func (s *Service) Children(id string) []Item

Children lists the children of the item, or the top items of a controller for its id, in the order they were added.

func (*Service) ClearResults

func (s *Service) ClearResults()

ClearResults discards the results that ended (VS Code's clear). A run that goes on stays.

func (*Service) Close

func (s *Service) Close()

Close stops the continuous runs and cancels the runs, and waits for the goroutines of the continuous runs to end.

func (*Service) ConfigureProfile

func (s *Service) ConfigureProfile(ref ProfileRef) error

ConfigureProfile calls the configure function of the profile, with no lock held. It fails with TestingProfileUnknown.

func (*Service) ContinuousForAChildOf

func (s *Service) ContinuousForAChildOf(id string) bool

ContinuousForAChildOf reports whether the item, an item below it or all the tests run continuously.

func (*Service) ContinuousForAParentOf

func (s *Service) ContinuousForAParentOf(id string) bool

ContinuousForAParentOf reports whether the item, an item above it or all the tests run continuously.

func (*Service) ContinuousForProfile

func (s *Service) ContinuousForProfile(ref ProfileRef) bool

ContinuousForProfile reports whether some continuous run uses the profile.

func (*Service) ContinuousSpecificallyFor

func (s *Service) ContinuousSpecificallyFor(id string) bool

ContinuousSpecificallyFor reports whether the item itself runs continuously.

func (*Service) Controllers

func (s *Service) Controllers() []ControllerInfo

Controllers lists the controllers, in the order they were registered.

func (*Service) FilesChanged

func (s *Service) FilesChanged(uris []string) int

FilesChanged tells the continuous runs that files changed (file:///path): each run whose items have a changed file starts again with the topmost of those items. It returns how many runs were started again.

func (*Service) GroupDefaults

func (s *Service) GroupDefaults(group Group, controllerID string) []Profile

GroupDefaults are the profiles the group runs without asking (VS Code's getGroupDefaultProfiles): those of the group that are defaults, and when there are none the first profile of the group. With a controller id only its profiles are looked at.

func (*Service) HasAnyResults

func (s *Service) HasAnyResults() bool

HasAnyResults is the context key testing.hasAnyResults.

func (*Service) InvalidateResults

func (s *Service) InvalidateResults(ids ...string)

InvalidateResults marks the tests of the results as retired: the tests with the ids and their descendants, or every test for none.

func (*Service) IsContinuousEnabled

func (s *Service) IsContinuousEnabled() bool

IsContinuousEnabled reports whether some continuous run is going (the context key testing.isContinuousModeOn).

func (*Service) IsRunning

func (s *Service) IsRunning() bool

IsRunning reports whether a result is still being made (the context key testing.isRunning).

func (*Service) Item

func (s *Service) Item(id string) (Item, bool)

Item returns the item with the id.

func (*Service) ItemCount

func (s *Service) ItemCount(controllerID string) int

ItemCount is the number of items in the tree of a controller.

func (*Service) Profiles

func (s *Service) Profiles(controllerID string) []Profile

Profiles lists the profiles of a controller, the defaults first and then by label; for an empty id, those of all controllers.

func (*Service) RefreshTests

func (s *Service) RefreshTests(ctx context.Context, controllerID string) error

RefreshTests asks the controller to read its tests again, or every controller that can be refreshed for an empty id (VS Code's refreshTests). The functions are called on the goroutine of the caller, one after the other, with no lock held; the first error ends the refresh. It fails with TestingControllerUnknown for an id of no controller.

func (*Service) RegisterController

func (s *Service) RegisterController(o ControllerOptions) (*Controller, error)

RegisterController adds a controller with an empty tree. It fails with TestingControllerInvalid for an id that is empty or holds the IDSeparator and for no label, and with TestingControllerDuplicate when the id is in use.

func (*Service) ResolveGroup

func (s *Service) ResolveGroup(req AmbiguousRequest) RunRequest

ResolveGroup chooses the profiles that run the tests (VS Code's TestService.runTests): the default profiles of the group take the tests they can use; when none is taken, each controller's first profile of the group that can run a test takes it. It returns a request with no targets when nothing can run the tests.

func (*Service) ResolveItem

func (s *Service) ResolveItem(ctx context.Context, id string) error

ResolveItem asks the controller to load the children of the item, or of the whole tree for a controller's id (VS Code's resolveChildren). It does nothing for a controller with no resolve function, and fails with TestingControllerUnknown for an id of no controller. The function is called on the goroutine of the caller, with no lock held.

func (*Service) RestoreState

func (s *Service) RestoreState(data []byte) error

RestoreState reads the results of a saved state and adds them to the list, in place of those it read before: the results of a run that goes on are left alone. A state that is not the JSON of this version fails with the tags TestingStateInvalid and TestingStateUnsupported and leaves the model as it was; a result that cannot be used (no id, a state that is none, a test with another parent than a test above it) is dropped.

func (*Service) Result

func (s *Service) Result(id string) *Result

Result returns the result with the id.

func (*Service) Results

func (s *Service) Results() []*Result

Results lists the results: those still running first, then the others, the newest first.

func (*Service) RunTests

func (s *Service) RunTests(ctx context.Context, req RunRequest) (*Result, error)

RunTests runs the request and returns when every profile has returned and every task its profile started has ended. It makes one result for the whole request, runs the targets at the same time and calls their Run functions with no lock held. The result is completed when the call returns, also when a profile failed or the run was cancelled (the tasks left are ended by force Options.CancelDeadline after the cancel). The error is the first failure of a profile, which keeps the result; an error before anything started returns no result. It fails with TestingRunInvalid for a request with no targets or an unknown group, and with TestingProfileUnknown for a target whose profile is not registered.

func (*Service) SaveState

func (s *Service) SaveState() ([]byte, error)

SaveState encodes what is saved with the workspace's UI state. It fails with TestingStateEncodeFailed.

func (*Service) SetGroupDefaults

func (s *Service) SetGroupDefaults(group Group, refs []ProfileRef)

SetGroupDefaults makes the profiles the defaults of the group and the others of the group not (VS Code's setGroupDefaultProfiles); a profile of another group that has the label of one that changed follows it. The choice is saved with the state.

func (*Service) StartContinuous

func (s *Service) StartContinuous(profiles []ProfileRef, testID string) error

StartContinuous starts the continuous run of the tests of the item (all of them for an empty id) with the profiles, and runs them once at once. A profile that already runs the item continuously is left as it is. It fails with TestingProfileUnknown for a profile that is not registered, with TestingContinuousUnsupported for one that does not support continuous runs or is of another controller than the item, and with TestingItemUnknown for an id that is not in the tree.

func (*Service) StartContinuousGroup

func (s *Service) StartContinuousGroup(group Group, testID string) error

StartContinuousGroup starts the continuous run with the default profiles of the group that support it (VS Code's start with a group); with a test id only those of its controller. It fails with TestingContinuousUnsupported when there are none.

func (*Service) StartExternalRun

func (s *Service) StartExternalRun(ext ExternalRun) *Result

StartExternalRun makes a result for a run a controller started (VS Code's $startedExtensionTestRun). The result completes when its last task ends, so the controller adds a task to it with AddTask at once.

func (*Service) StateOf

func (s *Service) StateOf(id string) (*Result, TestResult, bool)

StateOf returns the state of the test in the newest result that gave it one, with that result (VS Code's getStateById).

func (*Service) StopContinuous

func (s *Service) StopContinuous(testID string)

StopContinuous stops the continuous runs of the item and of the items below it; with an empty id, all of them.

func (*Service) StopContinuousProfile

func (s *Service) StopContinuousProfile(ref ProfileRef)

StopContinuousProfile stops the continuous runs that use the profile, wherever they run.

func (*Service) Subscribe

func (s *Service) Subscribe(fn func(Event)) (cancel func())

Subscribe registers a listener of the changes of the model; the returned function removes it. See the package comment for the thread the listener is called on.

func (*Service) Walk

func (s *Service) Walk(id string, fn func(Item) bool)

Walk calls fn for the item with the id and for each of its descendants, parents first; for a controller's id it starts with its top items. fn returning false skips the descendants of that item. The tree may not be changed from fn.

type StackFrame

type StackFrame struct {
	Label string
	URI   string
	Pos   *Pos
}

StackFrame is a line of the stack trace of a failure.

type State

type State int

State is the state of a test in a run (VS Code's TestResultState); the numbers are VS Code's.

const (
	// StateUnset is a test the run knows but did not touch.
	StateUnset State = iota
	// StateQueued is a test waiting for its turn.
	StateQueued
	// StateRunning is a test that runs now.
	StateRunning
	// StatePassed is a test that passed.
	StatePassed
	// StateFailed is a test that failed (an assertion).
	StateFailed
	// StateSkipped is a test that did not run.
	StateSkipped
	// StateErrored is a test that could not run to its end (a crash, a build error).
	StateErrored
)

The states of a test.

func MaxPriority

func MaxPriority(states ...State) State

MaxPriority is the state of the highest priority among the states, and StateUnset for none.

func (State) HasResult

func (s State) HasResult() bool

HasResult reports whether the state is one that has a result: passed, failed or errored.

func (State) IsFailed

func (s State) IsFailed() bool

IsFailed reports whether the state is failed or errored.

func (State) Priority

func (s State) Priority() int

Priority is the order of importance of a state: the highest of the states of the children is the state a parent shows (VS Code's statePriority).

func (State) String

func (s State) String() string

String is the name of the state: unset, queued, running, passed, failed, skipped or errored.

func (State) Valid

func (s State) Valid() bool

Valid reports whether the value is one of the states.

type StatementDetail

type StatementDetail struct {
	Executed int
	Location Range
	Branches []BranchDetail
}

StatementDetail is a statement and how many times it ran.

type TaskInfo

type TaskInfo struct {
	ID, Name, ControllerID string
	Running                bool
	HasCoverage            bool
}

TaskInfo describes a task of a result: one CreateTestRun of an extension, or the run of a controller.

type TaskSpec

type TaskSpec struct {
	// Name is the name of the task, ControllerID the controller that runs it.
	Name, ControllerID string
	// LoadCoverage loads the details of the coverage the task reports.
	LoadCoverage CoverageLoader
}

TaskSpec describes a task.

type TaskState

type TaskState struct {
	State    State
	Duration time.Duration
	Messages []Message
}

TaskState is the state of a test in one task of a run.

type TestResult

type TestResult struct {
	Item Item
	// OwnState is the state the tasks gave the test, the state of the highest priority among them; State is the state the test shows,
	// which also holds the states of its children in the run. Duration and OwnDuration are the same for the durations: the own one is
	// the longest a task gave, the shown one the sum of the children's when the test has none of its own; NoDuration for none.
	OwnState, State       State
	OwnDuration, Duration time.Duration
	// Tasks are the states by task, in the order of the result's tasks.
	Tasks []TaskState
	// Retired says that the controller invalidated the result after the run.
	Retired bool
	// Children are the ids of the children that are in the run.
	Children []string
}

TestResult is a test in a result: the item as it was when the run first knew it, and its states.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL