leaktest

package module
Version: v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2018 License: BSD-3-Clause Imports: 7 Imported by: 6

README

Leaktest Build Status codecov Sourcegraph Documentation

Refactored, tested variant of the goroutine leak detector found in both net/http tests and the cockroachdb source tree.

Takes a snapshot of running goroutines at the start of a test, and at the end - compares the two and voila. Ignores runtime/sys goroutines. Doesn't play nice with t.Parallel() right now, but there are plans to do so.

Installation

Go 1.7+

go get -u github.com/fortytw2/leaktest

Go 1.5/1.6 need to use the tag v1.0.0, as newer versions depend on context.Context.

Example

These tests fail, because they leak a goroutine

// Default "Check" will poll for 5 seconds to check that all
// goroutines are cleaned up
func TestPool(t *testing.T) {
    defer leaktest.Check(t)()

    go func() {
        for {
            time.Sleep(time.Second)
        }
    }()
}

// Helper function to timeout after X duration
func TestPoolTimeout(t *testing.T) {
    defer leaktest.CheckTimeout(t, time.Second)()

    go func() {
        for {
            time.Sleep(time.Second)
        }
    }()
}

// Use Go 1.7+ context.Context for cancellation
func TestPoolContext(t *testing.T) {
    ctx, _ := context.WithTimeout(context.Background(), time.Second)
    defer leaktest.CheckContext(ctx, t)()

    go func() {
        for {
            time.Sleep(time.Second)
        }
    }()
}

LICENSE

Same BSD-style as Go, see LICENSE

Documentation

Overview

Package leaktest provides tools to detect leaked goroutines in tests. To use it, call "defer leaktest.Check(t)()" at the beginning of each test that may use goroutines. copied out of the cockroachdb source tree with slight modifications to be more re-useable

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Check

func Check(t ErrorReporter) func()

Check snapshots the currently-running goroutines and returns a function to be run at the end of tests to see whether any goroutines leaked, waiting up to 5 seconds in error conditions

func CheckContext added in v1.1.0

func CheckContext(ctx context.Context, t ErrorReporter) func()

CheckContext is the same as Check, but uses a context.Context for cancellation and timeout control

func CheckTimeout added in v1.1.0

func CheckTimeout(t ErrorReporter, dur time.Duration) func()

CheckTimeout is the same as Check, but with a configurable timeout

Types

type ErrorReporter

type ErrorReporter interface {
	Errorf(format string, args ...interface{})
}

ErrorReporter is a tiny subset of a testing.TB to make testing not such a massive pain

Source Files

Jump to

Keyboard shortcuts

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