1/*
2 * Copyright (c) 2013-2016 Dave Collins <dave@davec.name>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17/*
18This test file is part of the spew package rather than than the spew_test
19package because it needs access to internals to properly test certain cases
20which are not possible via the public interface since they should never happen.
21*/
22
23package spew
24
25import (
26	"bytes"
27	"reflect"
28	"testing"
29)
30
31// dummyFmtState implements a fake fmt.State to use for testing invalid
32// reflect.Value handling.  This is necessary because the fmt package catches
33// invalid values before invoking the formatter on them.
34type dummyFmtState struct {
35	bytes.Buffer
36}
37
38func (dfs *dummyFmtState) Flag(f int) bool {
39	return f == int('+')
40}
41
42func (dfs *dummyFmtState) Precision() (int, bool) {
43	return 0, false
44}
45
46func (dfs *dummyFmtState) Width() (int, bool) {
47	return 0, false
48}
49
50// TestInvalidReflectValue ensures the dump and formatter code handles an
51// invalid reflect value properly.  This needs access to internal state since it
52// should never happen in real code and therefore can't be tested via the public
53// API.
54func TestInvalidReflectValue(t *testing.T) {
55	i := 1
56
57	// Dump invalid reflect value.
58	v := new(reflect.Value)
59	buf := new(bytes.Buffer)
60	d := dumpState{w: buf, cs: &Config}
61	d.dump(*v)
62	s := buf.String()
63	want := "<invalid>"
64	if s != want {
65		t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want)
66	}
67	i++
68
69	// Formatter invalid reflect value.
70	buf2 := new(dummyFmtState)
71	f := formatState{value: *v, cs: &Config, fs: buf2}
72	f.format(*v)
73	s = buf2.String()
74	want = "<invalid>"
75	if s != want {
76		t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want)
77	}
78}
79
80// SortValues makes the internal sortValues function available to the test
81// package.
82func SortValues(values []reflect.Value, cs *ConfigState) {
83	sortValues(values, cs)
84}
85