cmdtest

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 27 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 cmdtest runs ytrack commands in-process against fake IO, a temp config dir, go-keyring's mock and a fake YouTrack server. Test-only.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Golden added in v0.2.0

func Golden(t *testing.T, name, got string)

Golden compares got with testdata/<name>.golden, after ShowANSI. Run the tests with YTRACK_UPDATE_GOLDEN=1 to rewrite the file.

func ShowANSI added in v0.2.0

func ShowANSI(s string) string

ShowANSI replaces ytrack's ANSI styles in s with tags such as <bold>.

func TwoHosts added in v0.5.2

func TwoHosts(t *testing.T) (env *Env, personal, work *FakeYouTrack)

TwoHosts starts two fake servers, personal and work, each with its own token, and logs in to both; personal, logged in first, is the default host. Both start empty: seed their issues and projects.

Types

type Env

type Env struct {
	IO        *iostreams.IOStreams
	Stdin     *bytes.Buffer
	Stdout    *bytes.Buffer
	Stderr    *bytes.Buffer
	Browser   *browser.Stub
	ConfigDir string
	// CacheDir is $YTRACK_CACHE_DIR, where the project cache lives.
	CacheDir string
	Factory  *cmdutil.Factory
	// contains filtered or unexported fields
}

Env is an isolated ytrack environment.

func New

func New(t *testing.T) *Env

New returns an Env with no TTYs, an empty config dir, an empty mock keyring and every YTRACK_* variable cleared. Tests using it must not run in parallel (the keyring mock and environment are process-global).

func (*Env) Config

func (e *Env) Config() *config.Config

Config loads the config as written to disk.

func (*Env) Interactive

func (e *Env) Interactive()

Interactive marks stdin and stdout as terminals so prompts are allowed.

func (*Env) IsUsageError

func (e *Env) IsUsageError(code clierr.ExitCode) bool

IsUsageError reports whether a run failed as a usage error: exit 1 (as in gh) with the --help hint on stderr.

func (*Env) Login

func (e *Env) Login(yt *FakeYouTrack)

Login stores token for the fake server's host as `auth login --with-token` would.

func (*Env) Reset

func (e *Env) Reset()

Reset clears captured output.

func (*Env) RouteAllTo

func (e *Env) RouteAllTo(yt *FakeYouTrack)

RouteAllTo sends every HTTP connection to the fake server, whatever host the URL names, so tests can use non-loopback host names.

func (*Env) Run

func (e *Env) Run(args ...string) clierr.ExitCode

Run executes ytrack with args and returns the exit code. Output accumulates in Stdout and Stderr; call Reset between runs to inspect one run.

type FakeYouTrack

type FakeYouTrack struct {
	Server   *httptest.Server
	Prefix   string
	Token    string
	Login    string
	FullName string
	Issues   []map[string]any
	// Comments holds each issue's comments by readable ID, oldest first.
	Comments map[string][]map[string]any
	// Attachments holds each issue's issue-level attachments by readable ID.
	Attachments map[string][]map[string]any
	// DropUploads names files that an upload, to the issue or a comment,
	// accepts but does not keep, as a server that loses them would.
	DropUploads []string
	// CommentUploadsToIssue makes an upload to a comment keep its files on
	// the issue only, as a server that ignores the comment would.
	CommentUploadsToIssue bool
	// RejectCommentUploads answers an upload to a comment with a 404, as a
	// server without that endpoint would.
	RejectCommentUploads bool
	// MissingFiles names attachment IDs that are listed but whose file is
	// gone: downloading one is a 404.
	MissingFiles []string
	// WorkItems holds each issue's work items by readable ID.
	WorkItems map[string][]map[string]any
	// TimeTracking holds project time tracking settings by project ID.
	TimeTracking map[string]map[string]any
	// Projects, ProjectFields (by project ID) and Tags back issue writes.
	Projects      []map[string]any
	ProjectFields map[string][]map[string]any
	Tags          []map[string]any
	// HideFieldSettings answers the project settings' custom field list
	// with an empty list and a single field with a 403, as YouTrack does
	// for a user who may read the project's issues but not its settings.
	// The definitions stay readable through an issue's
	// customFields(projectCustomField(...)).
	HideFieldSettings bool
	// IgnoreFieldWrites names custom fields whose REST writes YouTrack
	// accepts (200) but leaves unchanged, as a workflow can.
	IgnoreFieldWrites []string
	// ForbidSilentCommands answers a command with "silent": true with a
	// 403, as for a user without Apply Commands Silently.
	ForbidSilentCommands bool
	// Localized makes the search keyword "for:" match nothing, as on a
	// non-English instance, where keywords are translated but field names
	// such as Assignee are not.
	Localized bool
	// KnownUsers, when set, are the only logins an "Assignee:" search term
	// may name besides Login; any other is a 400 invalid_query, as YouTrack
	// answers a search for a user it does not have.
	KnownUsers []string
	// MaxTop caps $top like a server limit would (0 means no cap).
	MaxTop int
	// HubTokenPage makes the instance's token page 404, as on a Server
	// install with an external Hub.
	HubTokenPage bool
	// CommandHTML makes command previews describe each part in HTML, as
	// YouTrack does: values HTML-escaped inside <span class="bold">.
	CommandHTML bool
	// CommandDescriptions, when set, replaces the description of each parsed
	// command part, in order, exactly as given (for hostile previews).
	CommandDescriptions []string
	// contains filtered or unexported fields
}

FakeYouTrack is a minimal YouTrack REST API:

GET  /api/users/me          the token's user
GET  /api/issues                Issues, paged with $skip/$top (default $top 42)
                                and restricted by customFields= when given
POST /api/issues                creates an issue (see SeedSampleProjects); echoes
                                the JSON body back when no projects are seeded
POST /api/issues/{id}           updates summary, description and customFields
POST|DELETE /api/issues/{id}/tags[/{tag}]  tags and untags an issue
GET  /api/admin/projects        Projects, paged
GET  /api/admin/projects/{id}/customFields  ProjectFields[project id], paged
                                (empty when HideFieldSettings)
GET  /api/admin/projects/{id}/customFields/{field}  one of them
GET  /api/tags                  Tags, paged
POST /api/commands[/assist]     applies or previews a small subset of the
                                YouTrack command language (see command)
GET  /api/issues/{id}           the issue in Issues with that idReadable or id,
                                with commentsCount; 404 with a YouTrack body if none
GET  /api/issues/{id}/comments  Comments[idReadable], paged with $skip/$top
POST /api/issues/{id}/comments  appends {"text"} to Comments and returns it;
                                like YouTrack, it ignores an "attachments" field
GET  /api/issues/{id}/comments/{comment}  one of Comments, with a
                                textPreview that resolves ![](name) and
                                [label](name) against the issue's Attachments
POST /api/issues/{id}/comments/{comment}/attachments  stores multipart files
                                as the comment's attachments (also listed in
                                Attachments) and returns them; see
                                CommentUploadsToIssue, RejectCommentUploads
POST /api/issues/{id}/attachments  stores multipart files in Attachments and
                                returns them (neither upload keeps DropUploads)
GET  /api/issues/{id}/attachments  Attachments[idReadable], paged, each with a
                                signed url ({Prefix}/api/files/{id}?sign=...)
GET  /api/files/{id}            an attachment's content at its signed URL; 404
                                for an unknown file or a wrong sign
GET  /api/issues/{id}/timeTracking/workItems         WorkItems[idReadable], paged
POST /api/issues/{id}/timeTracking/workItems         creates a work item from
                                {duration{minutes}, date, text, type{id}}; 400 for
                                a missing duration or a type the project lacks
GET|POST|DELETE /api/issues/{id}/timeTracking/workItems/{item}
                                reads, updates (merging the body) or deletes one,
                                found by ID across all issues (any {id})
GET  /api/admin/projects/{id}/timeTrackingSettings   TimeTracking[project id]
GET  /api/plain                 a text/plain body
GET  /users/me                  the web token page (no auth; 404 if HubTokenPage)

Like YouTrack, a request with a body that is not JSON (or multipart for attachments) is a 415.

Like YouTrack, JSON responses keep only the attributes named in fields= (plus $type), when fields= is given. Every /api route requires "Authorization: Bearer <Token>".

func NewFakeYouTrack

func NewFakeYouTrack(t *testing.T, prefix string) *FakeYouTrack

NewFakeYouTrack starts a fake server mounted at prefix ("" or e.g. "/youtrack").

func (*FakeYouTrack) AddAttachment added in v0.5.4

func (yt *FakeYouTrack) AddAttachment(issue, name, content string) string

AddAttachment adds a file with that name and content to an issue's attachments and returns its ID.

func (*FakeYouTrack) AddProject added in v0.5.2

func (yt *FakeYouTrack) AddProject(shortName string)

AddProject adds a project with shortName and no custom fields.

func (*FakeYouTrack) Key

func (yt *FakeYouTrack) Key() string

Key is the host key ytrack derives from URL.

func (*FakeYouTrack) LastRequest

func (yt *FakeYouTrack) LastRequest(t *testing.T) Request

LastRequest returns the most recent request.

func (*FakeYouTrack) ProjectLookups added in v0.5.2

func (yt *FakeYouTrack) ProjectLookups() int

ProjectLookups counts the project list reads (GET /api/admin/projects).

func (*FakeYouTrack) RedirectUploads added in v0.5.0

func (yt *FakeYouTrack) RedirectUploads()

RedirectUploads makes yt answer an issue upload with a 307 to the same URL, as a proxy that wants the request resent, unless it was already redirected.

func (*FakeYouTrack) Requests

func (yt *FakeYouTrack) Requests() []Request

Requests returns the requests received so far.

func (*FakeYouTrack) SeedIssues

func (yt *FakeYouTrack) SeedIssues(n int)

SeedIssues fills Issues with n issues APP-1..APP-n.

func (*FakeYouTrack) SeedSampleAttachments added in v0.5.4

func (yt *FakeYouTrack) SeedSampleAttachments()

SeedSampleAttachments gives NSR-40 two attachments, trace.log on the issue and shot.png on comment 4-2.

func (*FakeYouTrack) SeedSampleIssues

func (yt *FakeYouTrack) SeedSampleIssues()

SeedSampleIssues replaces Issues with NSR-40 and NSR-41 and gives NSR-40 three comments.

func (*FakeYouTrack) SeedSampleProjects

func (yt *FakeYouTrack) SeedSampleProjects()

SeedSampleProjects adds the NSR, OPS and (archived) OLD projects, NSR's custom field definitions and three tags. With Projects set, POST /api/issues creates issues instead of echoing the body.

func (*FakeYouTrack) SeedSampleWorkItems

func (yt *FakeYouTrack) SeedSampleWorkItems()

SeedSampleWorkItems gives NSR-40 three work items and the NSR project (0-12) time tracking with the types Development, Testing and Documentation. Seed the issues first.

func (*FakeYouTrack) URL

func (yt *FakeYouTrack) URL() string

URL is the service URL, including the prefix.

type Projection

type Projection map[string]Projection

Projection is a parsed fields= value: attribute name to its nested projection (nil for a leaf).

func ParseProjection

func ParseProjection(s string) (Projection, error)

ParseProjection parses YouTrack's fields syntax, e.g. "id,project(name)".

type Request

type Request struct {
	Method   string
	Path     string
	RawQuery string
	Header   http.Header
	Body     string
}

Request is a request the fake server received.

Jump to

Keyboard shortcuts

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