testctx

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2023 License: ISC Imports: 3 Imported by: 3

README

testctx

testctx is a Go package with useful methods for simplifying creating test contexts. The methods ensure a context created within a test is correctly canceled once the test is completed, to avoid leaking any resources created during the test.

Requiring this package

$ go get matheusd.com/testctx@latest

Example usage

package mypkg

import (
    "testing"

    "matheusd.com/testctx"
)

func testFunc(ctx context.Context) {
    <-ctx.Done()
}

func TestMyFunc(t *testing.T) {
    t.Parallel()
    testFunc(testctx.New(t))
    
    // testFunc gets GC'd once the test completes.
}

License

This package is licensed under the copyfree ISC License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(t Cleaner) context.Context

New returns a new context that times out at the default timeout and is canceled once the test is done.

func SetDefaultTimeout

func SetDefaultTimeout(t time.Duration)

SetDefaultTimeout sets the default timeout duration for new contexts at the package level. While this is safe for concurrent access, it is usually an error to use different timeout values for different tests of the same package as it can lead to data races. If a particular test or operation requires a different timeout value, it is better to call WithTimeout and use the returned context explicitly.

func WithBackground added in v0.2.0

func WithBackground(t Cleaner) context.Context

WithBackground returns a new context that uses context.Background() as parent (thus disabling the standard timeout generated by this package).

func WithCancel

func WithCancel(t Cleaner) (context.Context, func())

WithCancel returns a new context with the default timeout value and a cancel function that can be used for early termination.

func WithParent

func WithParent(t Cleaner, parent context.Context) context.Context

WithParent returns a new context with the specified parent that times out at the default timeout value.

func WithTimeout

func WithTimeout(t Cleaner, timeout time.Duration) context.Context

WithTimeout returns a new context that times out at the specified timeout.

Types

type Cleaner

type Cleaner interface {
	Cleanup(func())
}

Cleaner is an interface that is satisfied by both testing.T and testing.B with the needed methods for this package to work.

Jump to

Keyboard shortcuts

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