testcloud

package
v0.0.0-...-49bc348 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 15 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.

README

testcloud

Package testcloud is the shared test fixture for this module. It never talks to a live cloud: every request reaches either an httptest server or a fake http.RoundTripper installed by the test.

Fixture server

cloud := testcloud.New(t)               // server, mux and token-authenticated provider
cloud.Mux.HandleFunc("GET /v2.1/servers/{id}", func(w http.ResponseWriter, r *http.Request) {
	testcloud.JSON(w, 200, `{"server":{"id":"s"}}`)
})
client := cloud.Client("compute", "/v2.1/") // endpoint under the fixture server

New registers t.Cleanup for the server. The provider token is test-token; call cloud.Provider.SetToken to use another one. NewServer starts a stand-alone server with the same idle-connection policy, and AdvertiseNova serves a Nova version document.

HTTP handlers may run off the test goroutine, so they report failures with t.Errorf and then return; they never call t.Fatal.

Fake transports

Use a fake transport when a test must control the response object itself (status, headers, body faults, Response.Request) or must observe requests without a server.

API Behavior
type RoundTripperFunc func(*http.Request) (*http.Response, error) Adapter; RoundTrip returns exactly what the function returns.
func LinkRequest(fn func(*http.Request) (*http.Response, error)) RoundTripperFunc Calls fn; a non-nil response whose Request is nil gets the outgoing request. An existing Request is kept.
func (c *Cloud) SetTransport(rt http.RoundTripper) Sets c.Provider.HTTPClient.Transport. Client endpoints still name the fixture server URL.
func Response(status int, body string, header http.Header) *http.Response Sets only StatusCode, Header (as given, nil stays nil) and a string Body.
func StreamResponse(status int, body io.ReadCloser, header http.Header) *http.Response Same, with a caller-supplied body such as *Body.
func NewRecorder(reply func(*http.Request) (*http.Response, error)) *Recorder Transport that records each request, then answers through LinkRequest(reply). Safe for concurrent use.
func (rec *Recorder) Calls() []Call, Len() int, Reset() Copy of the recorded calls in arrival order; number of calls; discard the calls recorded so far.
type Call struct{ Method, Path, EscapedPath, RawQuery, Body string; Header http.Header } r.Method, r.URL.Path, r.URL.EscapedPath(), r.URL.RawQuery, the full request body ("" for a nil body) and r.Header.Clone().
type Body struct{ Data string; ReadErr, CloseErr error; OnRead, OnClose func() } Scripted response body, see below. Reads() and Closes() count calls.

Body yields Data; the read that exhausts it returns ReadErr (or io.EOF when ReadErr is nil) together with the last bytes, and later reads return 0 and the same error. A truncated body is Data plus io.ErrUnexpectedEOF. OnRead runs once, after the first read has copied its bytes. Close runs OnClose on every call and returns CloseErr.

calls := testcloud.NewRecorder(func(r *http.Request) (*http.Response, error) {
	return testcloud.Response(200, `{"group":{}}`, http.Header{"Content-Type": {"application/json"}}), nil
})
cloud.SetTransport(calls)
// ...
if calls.Len() != 1 || calls.Calls()[0].EscapedPath != "/cinder/v3/project/groups/a%2Fb" {
	t.Fatal(calls.Calls())
}

Worked examples: blockstorage/v3/groups (recorder, response builder and fault body) and network/v2/extensions/vpnaas/services (recorder with a projection onto a local call struct, and LinkRequest with a caller-owned call slice).

Migrating an ad-hoc transport

Convert one package at a time and keep every assertion's meaning. Run go vet and go test -race for the package afterwards.

  1. Adapter type. Delete the local type xTransport func(*http.Request) (*http.Response, error) and its RoundTrip method.
    • A method that sets Request only when the response has none becomes testcloud.LinkRequest(fn).
    • A method that is just return f(r) becomes testcloud.RoundTripperFunc(fn). Do not switch it to LinkRequest: setting Response.Request can change what the code under test observes.
    • A method that always overwrites Request is equivalent to LinkRequest only when the function never returns a response that already names a request (for example one from http.DefaultTransport). Check before converting.
  2. Installation. cloud.Provider.HTTPClient.Transport = x becomes cloud.SetTransport(x).
  3. Response builders. A builder that returns &http.Response{StatusCode: code, Header: h, Body: io.NopCloser(strings.NewReader(body))} becomes testcloud.Response(code, body, h); one with an io.ReadCloser becomes testcloud.StreamResponse. Builders that also set Status, ContentLength, Request, Proto or trailers stay local, or keep the extra assignments after the call.
  4. Call recorders. A closure that reads the request body and appends method, path, escaped path, raw query, body and cloned headers becomes testcloud.NewRecorder(reply). Map fields as method→Method, path→Path, escaped→EscapedPath, query→RawQuery, body→Body, header(s)→Header; len(*calls) becomes calls.Len() and (*calls)[i] becomes calls.Calls()[i].
    • When a test compares whole call slices with reflect.DeepEqual against a local struct, keep that struct and add a projection from rec.Calls() (see pythonVPNServiceCalls). Comparing []testcloud.Call directly would also compare headers and escaped paths.
    • The recorder records before the reply runs and replaces r.Body with a fresh reader over the same bytes. A reply that relied on finding the body already drained, or a recorder that records after the reply, header values instead of a clone, url.Values instead of the raw query, or decoded JSON, stays local or needs a projection.
    • A request body read error is ignored by the recorder, as the existing closures do; a test that asserts on it stays local.
  5. Fault bodies. A body that returns its data and then a read error, counts closes, runs a hook and returns a close error maps to testcloud.Body: text/data→Data, readErr→ReadErr, closeErr→CloseErr, afterRead/onRead→OnRead (once), afterClose/onClose→OnClose (every close), closed/closes→Closes(). Check the exact read sequence first. Differences that only show after the first error (a body that reports its error once and then io.EOF, as the former groupFaultBody did) or between returning the error with the last bytes and on the next read are invisible to io.ReadAll and JSON decoding; convert such a body only when the code under test stops at the first read error. Keep a local body when it wraps a real response body (ReadCloser embedding); when it blocks, waits on a context or channel, or cancels; when it serves at most one buffer of data per read on purpose; or when it implements Seek or other interfaces.
  6. Delays and cancellation. Transports that sleep, wait for r.Context().Done() or release on a channel stay as ordinary functions passed to RoundTripperFunc or LinkRequest; the helper has no scheduling API.
  7. Wrapping transports. Struct types that call base.RoundTrip and then decorate the response stay local; only their installation changes to SetTransport.

Documentation

Overview

Package testcloud provides an isolated HTTP fixture, never a live cloud.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CancelWhenBlocked

func CancelWhenBlocked(t testing.TB, parent context.Context, cause error) context.Context

CancelWhenBlocked returns a child of parent that is cancelled with cause as soon as an SDK progress send under it blocks because nobody receives. It uses progress.NotifyBlocked, so no timing assumption is involved; if no send blocks within ten seconds the test fails and the context is cancelled with a distinct error.

func JSON

func JSON(w http.ResponseWriter, status int, body string)

func NewServer

func NewServer(handler http.Handler) *httptest.Server

NewServer starts an httptest server whose idle connections close without lingering. Each fixture server is short-lived, and the default close leaves a TIME_WAIT socket per connection; across the full suite that exhausts local ephemeral ports. Connections serving a request keep the default close, so a handler that truncates its body still produces a clean EOF, not a reset.

func NovaVersionDocument

func NovaVersionDocument(self, minimum, maximum string) string

NovaVersionDocument is a single CURRENT v2.1 version document.

func Response

func Response(status int, body string, header http.Header) *http.Response

Response builds a fake response with only StatusCode, Header and Body set. The header is used as given; nil leaves Response.Header nil.

func StreamResponse

func StreamResponse(status int, body io.ReadCloser, header http.Header) *http.Response

StreamResponse is Response with a caller-supplied body, such as a *Body.

Types

type Body

type Body struct {
	Data     string
	ReadErr  error
	CloseErr error
	OnRead   func()
	OnClose  func()
	// contains filtered or unexported fields
}

Body is a scripted response body for read, close and truncation faults. Reads yield Data; the read that exhausts Data returns ReadErr (io.EOF when ReadErr is nil) together with the last bytes, and later reads return 0 and the same error. A truncated body is Data plus io.ErrUnexpectedEOF. OnRead runs once, after the first Read has copied its bytes and before it returns. Close runs OnClose on every call and returns CloseErr. Fields must be set before the first Read or Close.

func (*Body) Close

func (b *Body) Close() error

Close implements io.Closer.

func (*Body) Closes

func (b *Body) Closes() int

Closes returns how many times Close was called.

func (*Body) Read

func (b *Body) Read(p []byte) (int, error)

Read implements io.Reader.

func (*Body) Reads

func (b *Body) Reads() int

Reads returns how many times Read was called.

type Call

type Call struct {
	Method      string      // r.Method
	Path        string      // r.URL.Path
	EscapedPath string      // r.URL.EscapedPath()
	RawQuery    string      // r.URL.RawQuery
	Body        string      // the full request body; "" when r.Body is nil
	Header      http.Header // r.Header.Clone()
}

Call is one request seen by a Recorder.

type Cloud

type Cloud struct {
	Server   *httptest.Server
	Mux      *http.ServeMux
	Provider *gophercloud.ProviderClient
}

func New

func New(t *testing.T) *Cloud

func (*Cloud) AdvertiseNova

func (c *Cloud) AdvertiseNova(path, minimum, maximum string) *atomic.Int32

AdvertiseNova serves a Nova v2.1 version document at the discovery path (ending in a slash) with the given advertised bounds. Empty bounds serve a clean 404, as a cloud without version discovery does. It returns a counter of discovery requests.

func (*Cloud) Client

func (c *Cloud) Client(service, path string) *gophercloud.ServiceClient

func (*Cloud) SetTransport

func (c *Cloud) SetTransport(rt http.RoundTripper)

SetTransport replaces the provider's HTTP transport, so requests reach rt instead of the fixture server. Client endpoints still name the server URL.

type Gate

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

Gate holds the Nth request that match accepts until the test has run its action through AwaitThen, then answers it with the request context's error without forwarding it. It forces an interleaving in which the operation has already started its next request when the test acts, for example cancels. Other requests pass through unchanged.

func NewGate

func NewGate(n int32, match func(*http.Request) bool) *Gate

NewGate gates the nth (1-based) request accepted by match.

func (*Gate) AwaitThen

func (g *Gate) AwaitThen(t testing.TB, action func())

AwaitThen waits until the gated request arrives, runs action and releases the request. The ten-second limit only guards against a hang.

func (*Gate) Intercept

func (g *Gate) Intercept(r *http.Request) (handled bool, err error)

Intercept handles r when it is the gated request: it waits for AwaitThen to finish and returns the request context's error with handled true. Requests that are not gated return handled false.

func (*Gate) Seen

func (g *Gate) Seen() int32

Seen reports how many requests match accepted, including the gated one.

func (*Gate) Wrap

func (g *Gate) Wrap(next http.RoundTripper) http.RoundTripper

Wrap forwards every request except the gated one to next.

type Progress

type Progress[T any] struct {
	C chan T
	// contains filtered or unexported fields
}

Progress drains an SDK progress channel on its own goroutine and calls fn for each received value, in order. Pass C to the progress option and call Done after the operation returns, before asserting on what fn recorded. The SDK sends nothing after an operation returns, so Done may close C.

func NewProgress

func NewProgress[T any](t testing.TB, fn func(T)) *Progress[T]

NewProgress starts the receiver. A nil fn only drains. Cleanup calls Done.

func (*Progress[T]) Done

func (p *Progress[T]) Done()

Done closes C and waits until fn has returned for every received value.

type Recorder

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

Recorder is an http.RoundTripper that records every request and answers it with Reply. It is safe for concurrent use.

func NewRecorder

func NewRecorder(reply func(*http.Request) (*http.Response, error)) *Recorder

NewRecorder returns a Recorder that answers through LinkRequest(reply).

func (*Recorder) Calls

func (rec *Recorder) Calls() []Call

Calls returns a copy of the recorded calls in arrival order.

func (*Recorder) Len

func (rec *Recorder) Len() int

Len returns the number of recorded calls.

func (*Recorder) Reset

func (rec *Recorder) Reset()

Reset discards the recorded calls, so later Calls and Len see only the requests that arrive afterwards. The reply function is unchanged.

func (*Recorder) RoundTrip

func (rec *Recorder) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip records r and then calls the reply function. The request body is read to its end before the reply runs; r.Body is then replaced with a fresh reader over the same bytes, so the reply can still inspect it. A request body read error is not reported; Call.Body holds the bytes read before it.

type RoundTripperFunc

type RoundTripperFunc func(*http.Request) (*http.Response, error)

RoundTripperFunc adapts a function to http.RoundTripper. RoundTrip returns exactly what the function returns; use LinkRequest when the fake response should carry its request as a real transport's does.

func LinkRequest

func LinkRequest(fn func(*http.Request) (*http.Response, error)) RoundTripperFunc

LinkRequest wraps fn so that a non-nil response whose Request is nil gets the outgoing request, as net/http.Transport sets Response.Request. A response that already names a request keeps it.

func (RoundTripperFunc) RoundTrip

func (f RoundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip calls f(r).

Jump to

Keyboard shortcuts

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