fakeupstream

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 26 Imported by: 0

README

Controlled upstreams

fakeupstream is a chi HTTP/HTTPS test server for remote transport, cache and adapter contracts. It uses loopback listeners and no public registry. New registers cleanup; Close also interrupts blocked handlers. Store ecosystem documents alongside their adapter tests rather than adding npm, Maven or other schemas to this package.

clock := fakeupstream.NewClock(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
upstream := fakeupstream.New(t, fakeupstream.Options{Now: clock.Now})
upstream.Set("/artifact.bin", fakeupstream.Resource{Body: []byte("version one")})
upstream.Set("/index.json", fakeupstream.Resource{
    Body: []byte(`{"versions":["1.0.0"]}`),
    Header: http.Header{"Content-Type": {"application/json"},
        "Cache-Control": {"max-age=60"}},
})
// Configure the application repository with upstream.URL. Give the same clock.Now
// to the cache. Configure the native client only with the application endpoint.
// After each client operation, assert upstream.Count("GET", "/index.json").
clock.Advance(61 * time.Second)
upstream.Set("/artifact.bin", fakeupstream.Resource{Body: []byte("version two")})

Resource snapshots copy their body and headers. A request already using an older snapshot completes with those bytes even if Set or Delete runs concurrently. Modified defaults to the injected time and ETag to the quoted SHA-256. Normal responses use http.ServeContent for HEAD, conditional requests and byte ranges. Header supplies MIME, cache controls, cookies, checksum headers or deliberately bad values; malformed metadata is simply a malformed Body. Explicit Status returns that status and body, including 401/403/404/429/5xx. Redirect points to another fixture and defaults to 302; set Status for another redirect code.

Fault.BeforeHeaders and Fault.BeforeBody take a zero-value Barrier. Wait for Reached() before inspecting counts, replacing a resource or cancelling a request; Release() releases all waiters. A body barrier flushes headers before waiting. Barriers observe cancellation, and server cleanup releases blocked handlers through their contexts. No network timing depends on sleeps. Clock controls timestamps, not timers. DropConnection, TruncateAfter and LengthDelta exercise dropped, partial and incorrectly sized transfers. HTTP clients may retry a dropped request on an existing connection; use a fresh transport when an exact single attempt matters.

Options.Auth supports Basic or Bearer challenges. Options.TLS enables HTTPS; Client() trusts the server certificate, and Certificate() exposes its public certificate for the transport under test. ClientIdentity(t) returns a client certificate and CA pool for tls.RequireAndVerifyClientCert. Test missing and untrusted certificates as well as success. NewProxy(t, auth, upstream...) supports HTTP forwarding and HTTPS CONNECT, records requests, strips proxy credentials from forwarded HTTP requests and refuses destinations outside the supplied fixtures. Use an http.CookieJar to exercise the returned Set-Cookie headers.

Requests() returns independent redacted snapshots. Query values, credentials, cookies and unknown header values are redacted; bodies and URL userinfo are never recorded. HeaderMatches(name, value) checks a known candidate using a keyed hash without putting its plaintext in assertion output. Register fixture secrets embedded in paths or ordinarily visible headers in Options.Secrets. Counts include denied, missing and interrupted requests. Empty method/path arguments mean all requests; counts never reset implicitly. Closing a server twice is safe, and closing a proxy closes its live tunnels.

For native-client acceptance, use a fresh client cache and only the application URL. Run a first fetch, a cache hit and a forced expiry/mutation; assert upstream counts and downloaded hashes at each step. A direct registry fallback or a populated client cache must fail those assertions. TestAccApplicationEndpointOnly checks this fixture wiring; TestAccMutableArtifactAndMetadata checks expiry, mutation, interruption and retry for both fixture kinds. Actual ecosystem/native remote acceptance belongs to the adapter tickets, after their production handlers exist. This harness is not a claim about a live Artifactory response.

Documentation

Overview

Package fakeupstream provides deterministic, loopback-only HTTP fixtures for remote repository tests. It models upstream mechanics, not observed Artifactory behavior. Keep ecosystem documents in the adapter tests that understand their schemas.

Index

Constants

View Source
const Redacted = "[REDACTED]"

Variables

This section is empty.

Functions

func ClientIdentity

func ClientIdentity(t testing.TB) (tls.Certificate, *x509.CertPool)

ClientIdentity creates a test-only CA and client certificate for mTLS. Configure Options.TLS with the returned pool and RequireAndVerifyClientCert, then place the certificate in the client's TLS config. No keys are written to disk or logs.

Types

type Auth

type Auth struct{ Username, Password, Token string }

Auth requires either a bearer Token or a basic Username/Password. An empty policy permits anonymous requests. A token takes precedence over basic credentials.

type Barrier

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

Barrier holds requests until Release. Reached closes when the first waiter arrives. Both releasing repeatedly and sharing one barrier across requests are safe.

func (*Barrier) Reached

func (b *Barrier) Reached() <-chan struct{}

func (*Barrier) Release

func (b *Barrier) Release()

func (*Barrier) Wait

func (b *Barrier) Wait(ctx context.Context) error

type Clock

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

Clock supplies the same controllable time to the upstream and the cache under test. It does not replace timers: use barriers for network scheduling.

func NewClock

func NewClock(now time.Time) *Clock

func (*Clock) Advance

func (c *Clock) Advance(d time.Duration)

func (*Clock) Now

func (c *Clock) Now() time.Time

type Fault

type Fault struct {
	BeforeHeaders  *Barrier
	BeforeBody     *Barrier
	DropConnection bool
	TruncateAfter  int64
	LengthDelta    int64
}

Fault interrupts a normal resource without sleeps. TruncateAfter > 0 aborts the connection after that many body bytes. LengthDelta falsifies Content-Length. BeforeBody flushes headers first, allowing clients to observe a stalled body.

type Options

type Options struct {
	TLS  *tls.Config
	Now  func() time.Time
	Auth Auth
	// Secrets also redacts fixture-specific secrets embedded in paths or safe headers.
	// Query values, credentials, cookies and unrecognized headers are always redacted.
	Secrets []string
}

Options are fixed before starting the server. TLS enables HTTPS; ClientCAs and ClientAuth can require a client certificate. Now defaults to time.Now.

type Request

type Request struct {
	Method                    string
	Path                      string
	Host                      string
	Header                    http.Header
	Query                     url.Values
	At                        time.Time
	Authorized                bool
	VerifiedClientCertificate bool
	// contains filtered or unexported fields
}

Request is safe to include in assertion failures. It never contains a request body, URL userinfo, raw query values or credential/cookie header values. HeaderMatches compares a candidate without storing its plaintext in the record.

func (Request) HeaderMatches

func (r Request) HeaderMatches(name, value string) bool

type Resource

type Resource struct {
	// Method optionally permits one explicit request method instead of GET/HEAD.
	Method   string
	Body     []byte
	Header   http.Header
	Modified time.Time
	ETag     string
	Status   int
	Redirect string
	Fault    Fault
}

Resource is an atomic response snapshot. Set copies Body and Header. A zero Status serves normal content with HEAD, Range and HTTP validators. Other statuses serve Body verbatim. Redirect uses Status or defaults to 302.

type Server

type Server struct {
	URL string
	// contains filtered or unexported fields
}

Server owns its listener and connections; New registers cleanup with the test. Set/Delete/Requests/Count may run concurrently with requests.

func New

func New(t testing.TB, options Options) *Server

func NewProxy

func NewProxy(t testing.TB, auth Auth, targets ...*Server) *Server

NewProxy starts an HTTP forward proxy with optional proxy authentication. Only the supplied running fixtures are reachable: an absolute URL or CONNECT cannot accidentally turn a fault test into a public-registry fetch. CONNECT can tunnel either scheme; the client still verifies the destination's certificate.

func (*Server) Certificate

func (s *Server) Certificate() *x509.Certificate

func (*Server) Client

func (s *Server) Client() *http.Client

func (*Server) Close

func (s *Server) Close()

func (*Server) Count

func (s *Server) Count(method, path string) int

Count matches the decoded path before redaction; empty method/path match all.

func (*Server) Delete

func (s *Server) Delete(path string)

func (*Server) Requests

func (s *Server) Requests() []Request

Requests returns independent snapshots in arrival order, including denied, missing and subsequently interrupted requests. Counts never reset implicitly.

func (*Server) Set

func (s *Server) Set(path string, resource Resource)

Jump to

Keyboard shortcuts

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