Documentation
¶
Overview ¶
Package spew implements a deep pretty printer for Go data structures to aid in debugging.
Originally copied from https://github.com/davecgh/go-spew it has been patched to fit go-testdeep needs as the original repository seems to have no activity anymore.
A quick overview of the additional features spew provides over the built-in printing facilities for Go data types are as follows:
- Pointers are dereferenced and followed
- Circular data structures are detected and handled properly
- Custom fmt.Stringer/error interfaces are optionally invoked, including on unexported types
- Custom types which only implement the fmt.Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables
- Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output
spew dumps Go data structures using a style which prints with newlines, customizable indentation, and additional debug information such as types and all pointer addresses used to indirect to the final value.
Quick Start ¶
This section demonstrates how to quickly get started with spew. See the sections below for further details on formatting and configuration options.
To dump a variable with full newlines, indentation, type and pointer information use Sdump:
str := spew.Sdump(myVar1)
Configuration Options ¶
Configuration of spew is handled by fields in the ConfigState type. For convenience, all of the top-level functions use a global state available via the spew.Config global.
It is also possible to create a ConfigState instance that provides methods equivalent to the top-level functions. This allows concurrent configuration options. See the ConfigState documentation for more details.
The following configuration options are available:
Indent String to use for each indentation level for Sdump function. It is a single space by default. A popular alternative is "\t".
MaxDepth Maximum number of levels to descend into nested data structures. There is no limit by default.
DisableMethods Disables invocation of error and fmt.Stringer interface methods. Method invocation is enabled by default.
DisablePointerMethods Disables invocation of error and fmt.Stringer interface methods on types which only accept pointer receivers from non-pointer variables. Pointer method invocation is enabled by default.
DisablePointerAddresses DisablePointerAddresses specifies whether to disable the printing of pointer addresses. This is useful when diffing data structures in tests.
EnableCapacities EnableCapacities specifies whether to enaable the printing of capacities for arrays, slices and channels.
Sdump Usage ¶
Simply call spew.Sdump with a variable you want to dump as a string:
str := spew.Sdump(myVar1)
Sample Sdump Output ¶
(main.Foo) {
unexportedField: (*main.Bar)(0xf84002e210)({
flag: (main.Flag) flagTwo,
data: (uintptr) <nil>
}),
ExportedField: (map[interface {}]interface {}) (len=1) {
(string) (len=3) "one": (bool) true
}
}
Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C command as shown.
([]uint8) (len=32) {
00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
00000020 31 32 |12|
}
Errors ¶
Since it is possible for custom fmt.Stringer/error interfaces to panic, spew detects them and handles them internally by printing the panic information inline with the output. Since spew is intended to provide deep pretty printing capabilities on structures, it intentionally does not return any errors.
Index ¶
Examples ¶
Constants ¶
const UnsafeDisabled = false
UnsafeDisabled is a build-time constant which specifies whether or not access to the unsafe package is available.
Variables ¶
var Config = ConfigState{Indent: " "}
Config is the active configuration of the top-level functions. The configuration can be changed by modifying the contents of spew.Config.
Functions ¶
func Sdump ¶
func Sdump(a any, config ...ConfigState) string
Sdump returns the string representation of a using config[0] if passed.
Example ¶
This example demonstrates how to use Sdump to dump variables to stdout.
/*
* Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package main
import (
"fmt"
"github.com/maxatome/go-testdeep/internal/spew"
)
type Flag int
const (
flagOne Flag = iota
flagTwo
)
var flagStrings = map[Flag]string{
flagOne: "flagOne",
flagTwo: "flagTwo",
}
func (f Flag) String() string {
if s, ok := flagStrings[f]; ok {
return s
}
return fmt.Sprintf("Unknown flag (%d)", int(f))
}
type Bar struct {
data uintptr
}
type Foo struct {
unexportedField Bar
ExportedField map[any]any
}
// This example demonstrates how to use Sdump to dump variables to stdout.
func main() {
// The following package level declarations are assumed for this example:
/*
type Flag int
const (
flagOne Flag = iota
flagTwo
)
var flagStrings = map[Flag]string{
flagOne: "flagOne",
flagTwo: "flagTwo",
}
func (f Flag) String() string {
if s, ok := flagStrings[f]; ok {
return s
}
return fmt.Sprintf("Unknown flag (%d)", int(f))
}
type Bar struct {
data uintptr
}
type Foo struct {
unexportedField Bar
ExportedField map[any]any
}
*/
// Setup some sample data structures for the example.
bar := Bar{uintptr(0x1234)}
s1 := Foo{bar, map[any]any{"one": true}}
f := Flag(5)
b := []byte{
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
0x31, 0x32,
}
// Dump!
fmt.Println(spew.Sdump(s1))
fmt.Println(spew.Sdump(f))
fmt.Println(spew.Sdump(b))
}
Output: (spew_test.Foo) { unexportedField: (spew_test.Bar) { data: (uintptr) 0x1234 }, ExportedField: (map[interface {}]interface {}) (len=1) { (string) (len=3) "one": (bool) true } } (spew_test.Flag) Unknown flag (5) ([]uint8) (len=34) { 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| 00000020 31 32 |12| }
func UnsafeReflectValue ¶
UnsafeReflectValue converts the passed reflect.Value into a one that bypasses the typical safety restrictions preventing access to unaddressable and unexported data. It works by digging the raw pointer to the underlying value out of the protected value and generating a new unprotected (unsafe) reflect.Value to it.
This allows us to check for implementations of the fmt.Stringer and error interfaces to be used for pretty printing ordinarily unaddressable and inaccessible values such as unexported struct fields.
Types ¶
type ConfigState ¶
type ConfigState struct {
// Indent specifies the string to use for each indentation level. The
// global config instance that all top-level functions use set this to a
// single space by default. If you would like more indentation, you might
// set this to a tab with "\t" or perhaps two spaces with " ".
Indent string
// MaxDepth controls the maximum number of levels to descend into nested
// data structures. The default, 0, means there is no limit.
//
// NOTE: Circular data structures are properly detected, so it is not
// necessary to set this value unless you specifically want to limit deeply
// nested data structures.
MaxDepth int
// DisableMethods specifies whether or not error and fmt.Stringer
// interfaces are invoked for types that implement them.
DisableMethods bool
// DisablePointerMethods specifies whether or not to check for and invoke
// error and fmt.Stringer interfaces on types which only accept a pointer
// receiver when the current type is not a pointer.
//
// NOTE: This might be an unsafe action since calling one of these methods
// with a pointer receiver could technically mutate the value, however,
// in practice, types which choose to satisfy an error or fmt.Stringer
// interface with a pointer receiver should not be mutating their state
// inside these interface methods. As a result, this option relies on
// access to the unsafe package, so it will not have any effect when
// running in environments without access to the unsafe package such as
// Google App Engine or with the "safe" build tag specified.
DisablePointerMethods bool
// DisablePointerAddresses specifies whether to disable the printing of
// pointer addresses. This is useful when diffing data structures in tests.
DisablePointerAddresses bool
// EnableCapacities specifies whether to enable the printing of capacities
// for arrays, slices and channels.
EnableCapacities bool
}
ConfigState houses the configuration options used by spew to format and display values. There is a global instance, Config, that is used to control top-level Sdump functionality.
The zero value for ConfigState provides no indentation. You would typically want to set it to a space or a tab.