Documentation
¶
Overview ¶
Package testutil provides test-only helpers for forcing I/O failures on demand, capturing process output, bootstrapping HTTP handlers, and normalizing time-variant values in assertions.
Helpers ¶
- Deterministic I/O failure mocks: NewErrorReader returns a reader whose ErrorReader.Read always fails; NewErrorCloser returns an io.ReadCloser whose ErrorCloser.Close always fails. These exercise error paths that are otherwise difficult to trigger.
- HTTP test bootstrap: RouterWithHandler builds an http.Handler backed by `julienschmidt/httprouter` with a route pre-registered.
- Output capture for assertions: CaptureOutput redirects stdout, stderr, and the default logger for the duration of a function call and returns captured output as a string.
- Time-variant text normalization: ReplaceDateTime and ReplaceUnixTimestamp replace dynamic timestamp fragments in strings (for example JSON responses).
Usage ¶
reader := testutil.NewErrorReader("read failed")
closer := testutil.NewErrorCloser("close failed")
_ = reader
_ = closer
output := testutil.CaptureOutput(t, func() {
fmt.Println("hello")
})
h := testutil.RouterWithHandler(http.MethodGet, "/health", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
_ = h
normalized := testutil.ReplaceDateTime(responseBody, "<DATETIME>")
normalized = testutil.ReplaceUnixTimestamp(normalized, "<UNIX_TS>")
_ = output
_ = normalized
These functions are intended for use in tests only.
When To Use ¶
- An error branch depends on a failing Read or Close that is hard to trigger otherwise.
- A JSON assertion contains a generated timestamp that must be normalized first.
- A handler needs a real router because it reads path parameters.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CaptureOutput ¶
CaptureOutput captures stdout, stderr, and standard-logger output produced while fn runs, and returns it as a single string.
It temporarily redirects the process-global os.Stdout, os.Stderr, and the standard logger (via log.SetOutput) to an in-memory pipe, runs fn, then restores all three (including the logger's previous output destination) before returning. Restoration and cleanup happen on every exit path, including a panic inside fn.
Because it mutates process-global state, CaptureOutput MUST NOT be used from parallel tests (t.Parallel) or while other goroutines write to stdout, stderr, or the standard logger; concurrent use would capture interleaved or missing output.
func ReplaceDateTime ¶
ReplaceDateTime replaces RFC3339-like datetime substrings in src with repl. It is useful for deterministic assertions on JSON responses with dynamic timestamps.
The match is bounded to the RFC3339 grammar (date, "T", time, optional fractional seconds and timezone offset) and never spans newlines. Space-separated datetimes (for example "2006-01-02 15:04:05") are intentionally not matched.
Example ¶
package main
import (
"fmt"
"github.com/tecnickcom/nurago/pkg/testutil"
)
func main() {
// A JSON response carrying a generated timestamp cannot be compared
// against a fixed golden value until the timestamp is normalized.
body := `{"id":"7","created_at":"2026-09-07T15:04:05.123Z","status":"ok"}`
fmt.Println(testutil.ReplaceDateTime(body, "<TIME>"))
}
Output: {"id":"7","created_at":"<TIME>","status":"ok"}
func ReplaceUnixTimestamp ¶
ReplaceUnixTimestamp replaces standalone 19-digit integers in src with repl. It is useful for deterministic assertions on JSON responses with dynamic Unix-nanosecond timestamps.
This is a heuristic keyed only on digit count: any standalone 19-digit integer is replaced, including unrelated identifiers that happen to be exactly 19 digits long. Numbers with more or fewer than 19 digits are left untouched.
Example ¶
package main
import (
"fmt"
"github.com/tecnickcom/nurago/pkg/testutil"
)
func main() {
body := `{"event":"login","ts":1757254800123456789}`
// Standalone 19-digit integers are treated as Unix-nanosecond
// timestamps. Shorter or longer numbers are left alone.
fmt.Println(testutil.ReplaceUnixTimestamp(body, "<TS>"))
fmt.Println(testutil.ReplaceUnixTimestamp(`{"count":42}`, "<TS>"))
}
Output: {"event":"login","ts":<TS>} {"count":42}
func RouterWithHandler ¶
func RouterWithHandler(method, path string, handlerFunc http.HandlerFunc) http.Handler
RouterWithHandler returns a new httprouter with handlerFunc registered for method and path.
Example ¶
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"github.com/tecnickcom/nurago/pkg/testutil"
)
func main() {
// The handler under test reads an httprouter path parameter, so it
// needs a real router rather than a bare http.HandlerFunc.
handler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(map[string]string{"path": r.URL.Path})
if err != nil {
fmt.Println(err)
}
}
router := testutil.RouterWithHandler(http.MethodGet, "/users/:id", handler)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, httptest.NewRequestWithContext(
context.TODO(), http.MethodGet, "/users/42", nil,
))
fmt.Println(rec.Code)
fmt.Print(rec.Body.String())
}
Output: 200 {"path":"/users/42"}
Types ¶
type ErrorCloser ¶
ErrorCloser is an io.ReadCloser whose Close method always returns an error. Its Read side yields io.EOF immediately (an empty body); only Close fails. The embedded reader is an io.Reader (not a concrete bytes.Reader), so the exported surface is exactly io.ReadCloser.
func NewErrorCloser ¶
func NewErrorCloser(errMsg string) *ErrorCloser
NewErrorCloser creates an ErrorCloser that returns errMsg from Close.
Example ¶
package main
import (
"fmt"
"github.com/tecnickcom/nurago/pkg/testutil"
)
func main() {
// ErrorCloser fails on Close, covering the deferred-close error path
// that is otherwise difficult to trigger.
c := testutil.NewErrorCloser("simulated close failure")
fmt.Println(c.Close())
}
Output: simulated close failure
func (*ErrorCloser) Close ¶
func (e *ErrorCloser) Close() error
Close always returns the configured error.
type ErrorReader ¶
type ErrorReader struct {
// contains filtered or unexported fields
}
ErrorReader is an io.Reader that always returns an error.
func NewErrorReader ¶
func NewErrorReader(msg string) *ErrorReader
NewErrorReader creates an ErrorReader that always returns msg as an error.
Example ¶
package main
import (
"fmt"
"io"
"github.com/tecnickcom/nurago/pkg/testutil"
)
func main() {
// ErrorReader fails on every Read, which exercises the error branch of
// code that consumes an io.Reader.
r := testutil.NewErrorReader("simulated read failure")
_, err := io.ReadAll(r)
fmt.Println(err)
}
Output: simulated read failure
type TestHTTPResponseWriter ¶
type TestHTTPResponseWriter interface {
http.ResponseWriter
}
TestHTTPResponseWriter wraps http.ResponseWriter to simplify mock generation.