fix: use testify instead of t.Fatal or t.Error in pkg package (part 1)

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
This commit is contained in:
Matthieu MOREL
2024-11-30 14:40:12 +01:00
parent 39d9cd707a
commit 0a71106a68
15 changed files with 103 additions and 207 deletions

View File

@ -18,6 +18,8 @@ import (
"math/rand" "math/rand"
"reflect" "reflect"
"testing" "testing"
"github.com/stretchr/testify/require"
) )
// TestIntervalTreeInsert tests interval tree insertion. // TestIntervalTreeInsert tests interval tree insertion.
@ -53,9 +55,7 @@ func TestIntervalTreeInsert(t *testing.T) {
tr := ivt.(*intervalTree) tr := ivt.(*intervalTree)
visits := tr.visitLevel() visits := tr.visitLevel()
if !reflect.DeepEqual(expected, visits) { require.Truef(t, reflect.DeepEqual(expected, visits), "level order expected %v, got %v", expected, visits)
t.Fatalf("level order expected %v, got %v", expected, visits)
}
} }
// TestIntervalTreeSelfBalanced ensures range tree is self-balanced after inserting ranges to the tree. // TestIntervalTreeSelfBalanced ensures range tree is self-balanced after inserting ranges to the tree.
@ -107,13 +107,9 @@ func TestIntervalTreeSelfBalanced(t *testing.T) {
tr := ivt.(*intervalTree) tr := ivt.(*intervalTree)
visits := tr.visitLevel() visits := tr.visitLevel()
if !reflect.DeepEqual(expected, visits) { require.Truef(t, reflect.DeepEqual(expected, visits), "level order expected %v, got %v", expected, visits)
t.Fatalf("level order expected %v, got %v", expected, visits)
}
if visits[len(visits)-1].depth != 3 { require.Equalf(t, 3, visits[len(visits)-1].depth, "expected self-balanced tree with last level 3, but last level got %d", visits[len(visits)-1].depth)
t.Fatalf("expected self-balanced tree with last level 3, but last level got %d", visits[len(visits)-1].depth)
}
} }
// TestIntervalTreeDelete ensures delete operation maintains red-black tree properties. // TestIntervalTreeDelete ensures delete operation maintains red-black tree properties.
@ -214,15 +210,11 @@ func TestIntervalTreeDelete(t *testing.T) {
{root: NewInt64Interval(953, 954), color: red, left: newInt64EmptyInterval(), right: newInt64EmptyInterval(), depth: 4}, {root: NewInt64Interval(953, 954), color: red, left: newInt64EmptyInterval(), right: newInt64EmptyInterval(), depth: 4},
} }
visitsBeforeDelete := tr.visitLevel() visitsBeforeDelete := tr.visitLevel()
if !reflect.DeepEqual(expectedBeforeDelete, visitsBeforeDelete) { require.Truef(t, reflect.DeepEqual(expectedBeforeDelete, visitsBeforeDelete), "level order after insertion expected %v, got %v", expectedBeforeDelete, visitsBeforeDelete)
t.Fatalf("level order after insertion expected %v, got %v", expectedBeforeDelete, visitsBeforeDelete)
}
// delete the node "514" // delete the node "514"
range514 := NewInt64Interval(514, 515) range514 := NewInt64Interval(514, 515)
if deleted := tr.Delete(NewInt64Interval(514, 515)); !deleted { require.Truef(t, tr.Delete(NewInt64Interval(514, 515)), "range %v not deleted", range514)
t.Fatalf("range %v not deleted", range514)
}
expectedAfterDelete514 := []visitedInterval{ expectedAfterDelete514 := []visitedInterval{
{root: NewInt64Interval(510, 511), color: black, left: NewInt64Interval(82, 83), right: NewInt64Interval(830, 831), depth: 0}, {root: NewInt64Interval(510, 511), color: black, left: NewInt64Interval(82, 83), right: NewInt64Interval(830, 831), depth: 0},
@ -246,15 +238,11 @@ func TestIntervalTreeDelete(t *testing.T) {
{root: NewInt64Interval(953, 954), color: red, left: newInt64EmptyInterval(), right: newInt64EmptyInterval(), depth: 4}, {root: NewInt64Interval(953, 954), color: red, left: newInt64EmptyInterval(), right: newInt64EmptyInterval(), depth: 4},
} }
visitsAfterDelete514 := tr.visitLevel() visitsAfterDelete514 := tr.visitLevel()
if !reflect.DeepEqual(expectedAfterDelete514, visitsAfterDelete514) { require.Truef(t, reflect.DeepEqual(expectedAfterDelete514, visitsAfterDelete514), "level order after deleting '514' expected %v, got %v", expectedAfterDelete514, visitsAfterDelete514)
t.Fatalf("level order after deleting '514' expected %v, got %v", expectedAfterDelete514, visitsAfterDelete514)
}
// delete the node "11" // delete the node "11"
range11 := NewInt64Interval(11, 12) range11 := NewInt64Interval(11, 12)
if deleted := tr.Delete(NewInt64Interval(11, 12)); !deleted { require.Truef(t, tr.Delete(NewInt64Interval(11, 12)), "range %v not deleted", range11)
t.Fatalf("range %v not deleted", range11)
}
expectedAfterDelete11 := []visitedInterval{ expectedAfterDelete11 := []visitedInterval{
{root: NewInt64Interval(510, 511), color: black, left: NewInt64Interval(383, 384), right: NewInt64Interval(830, 831), depth: 0}, {root: NewInt64Interval(510, 511), color: black, left: NewInt64Interval(383, 384), right: NewInt64Interval(830, 831), depth: 0},
@ -277,9 +265,7 @@ func TestIntervalTreeDelete(t *testing.T) {
{root: NewInt64Interval(953, 954), color: red, left: newInt64EmptyInterval(), right: newInt64EmptyInterval(), depth: 4}, {root: NewInt64Interval(953, 954), color: red, left: newInt64EmptyInterval(), right: newInt64EmptyInterval(), depth: 4},
} }
visitsAfterDelete11 := tr.visitLevel() visitsAfterDelete11 := tr.visitLevel()
if !reflect.DeepEqual(expectedAfterDelete11, visitsAfterDelete11) { require.Truef(t, reflect.DeepEqual(expectedAfterDelete11, visitsAfterDelete11), "level order after deleting '11' expected %v, got %v", expectedAfterDelete11, visitsAfterDelete11)
t.Fatalf("level order after deleting '11' expected %v, got %v", expectedAfterDelete11, visitsAfterDelete11)
}
} }
func TestIntervalTreeIntersects(t *testing.T) { func TestIntervalTreeIntersects(t *testing.T) {
@ -323,9 +309,7 @@ func TestIntervalTreeStab(t *testing.T) {
ivt.Insert(NewStringInterval("0", "3"), 0) ivt.Insert(NewStringInterval("0", "3"), 0)
tr := ivt.(*intervalTree) tr := ivt.(*intervalTree)
if tr.root.max.Compare(StringComparable("8")) != 0 { require.Equalf(t, 0, tr.root.max.Compare(StringComparable("8")), "wrong root max got %v, expected 8", tr.root.max)
t.Fatalf("wrong root max got %v, expected 8", tr.root.max)
}
if x := len(ivt.Stab(NewStringPoint("0"))); x != 3 { if x := len(ivt.Stab(NewStringPoint("0"))); x != 3 {
t.Errorf("got %d, expected 3", x) t.Errorf("got %d, expected 3", x)
} }
@ -381,12 +365,8 @@ func TestIntervalTreeRandom(t *testing.T) {
for ab := range ivs { for ab := range ivs {
for xy := range ivs { for xy := range ivs {
v := xy.x + int64(rand.Intn(int(xy.y-xy.x))) v := xy.x + int64(rand.Intn(int(xy.y-xy.x)))
if slen := len(ivt.Stab(NewInt64Point(v))); slen == 0 { require.NotEmptyf(t, ivt.Stab(NewInt64Point(v)), "expected %v stab non-zero for [%+v)", v, xy)
t.Fatalf("expected %v stab non-zero for [%+v)", v, xy) require.Truef(t, ivt.Intersects(NewInt64Point(v)), "did not get %d as expected for [%+v)", v, xy)
}
if !ivt.Intersects(NewInt64Point(v)) {
t.Fatalf("did not get %d as expected for [%+v)", v, xy)
}
} }
if !ivt.Delete(NewInt64Interval(ab.x, ab.y)) { if !ivt.Delete(NewInt64Interval(ab.x, ab.y)) {
t.Errorf("did not delete %v as expected", ab) t.Errorf("did not delete %v as expected", ab)

View File

@ -8,15 +8,16 @@ import (
"hash/crc32" "hash/crc32"
"reflect" "reflect"
"testing" "testing"
"github.com/stretchr/testify/require"
) )
// TestHash32 tests that Hash32 provided by this package can take an initial // TestHash32 tests that Hash32 provided by this package can take an initial
// crc and behaves exactly the same as the standard one in the following calls. // crc and behaves exactly the same as the standard one in the following calls.
func TestHash32(t *testing.T) { func TestHash32(t *testing.T) {
stdhash := crc32.New(crc32.IEEETable) stdhash := crc32.New(crc32.IEEETable)
if _, err := stdhash.Write([]byte("test data")); err != nil { _, err := stdhash.Write([]byte("test data"))
t.Fatalf("unexpected write error: %v", err) require.NoErrorf(t, err, "unexpected write error: %v", err)
}
// create a new hash with stdhash.Sum32() as initial crc // create a new hash with stdhash.Sum32() as initial crc
hash := New(stdhash.Sum32(), crc32.IEEETable) hash := New(stdhash.Sum32(), crc32.IEEETable)
@ -38,12 +39,10 @@ func TestHash32(t *testing.T) {
} }
// write something // write something
if _, err := stdhash.Write([]byte("test data")); err != nil { _, err = stdhash.Write([]byte("test data"))
t.Fatalf("unexpected write error: %v", err) require.NoErrorf(t, err, "unexpected write error: %v", err)
} _, err = hash.Write([]byte("test data"))
if _, err := hash.Write([]byte("test data")); err != nil { require.NoErrorf(t, err, "unexpected write error: %v", err)
t.Fatalf("unexpected write error: %v", err)
}
wsum32 = stdhash.Sum32() wsum32 = stdhash.Sum32()
if g := hash.Sum32(); g != wsum32 { if g := hash.Sum32(); g != wsum32 {
t.Errorf("Sum32 after write = %d, want %d", g, wsum32) t.Errorf("Sum32 after write = %d, want %d", g, wsum32)

View File

@ -29,27 +29,17 @@ import (
func TestExpectFunc(t *testing.T) { func TestExpectFunc(t *testing.T) {
ep, err := NewExpect("echo", "hello world") ep, err := NewExpect("echo", "hello world")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
wstr := "hello world\r\n" wstr := "hello world\r\n"
l, eerr := ep.ExpectFunc(context.Background(), func(a string) bool { return len(a) > 10 }) l, eerr := ep.ExpectFunc(context.Background(), func(a string) bool { return len(a) > 10 })
if eerr != nil { require.NoError(t, eerr)
t.Fatal(eerr) require.Equalf(t, l, wstr, `got "%v", expected "%v"`, l, wstr)
} require.NoError(t, ep.Close())
if l != wstr {
t.Fatalf(`got "%v", expected "%v"`, l, wstr)
}
if cerr := ep.Close(); cerr != nil {
t.Fatal(cerr)
}
} }
func TestExpectFuncTimeout(t *testing.T) { func TestExpectFuncTimeout(t *testing.T) {
ep, err := NewExpect("tail", "-f", "/dev/null") ep, err := NewExpect("tail", "-f", "/dev/null")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
go func() { go func() {
// It's enough to have "talkative" process to stuck in the infinite loop of reading // It's enough to have "talkative" process to stuck in the infinite loop of reading
for { for {
@ -66,21 +56,15 @@ func TestExpectFuncTimeout(t *testing.T) {
require.ErrorIs(t, err, context.DeadlineExceeded) require.ErrorIs(t, err, context.DeadlineExceeded)
if err = ep.Stop(); err != nil { require.NoError(t, ep.Stop())
t.Fatal(err) require.ErrorContains(t, ep.Close(), "unexpected exit code [143]")
}
err = ep.Close()
require.ErrorContains(t, err, "unexpected exit code [143]")
require.Equal(t, 143, ep.exitCode) require.Equal(t, 143, ep.exitCode)
} }
func TestExpectFuncExitFailure(t *testing.T) { func TestExpectFuncExitFailure(t *testing.T) {
// tail -x should not exist and return a non-zero exit code // tail -x should not exist and return a non-zero exit code
ep, err := NewExpect("tail", "-x") ep, err := NewExpect("tail", "-x")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel() defer cancel()
@ -95,9 +79,7 @@ func TestExpectFuncExitFailure(t *testing.T) {
func TestExpectFuncExitFailureStop(t *testing.T) { func TestExpectFuncExitFailureStop(t *testing.T) {
// tail -x should not exist and return a non-zero exit code // tail -x should not exist and return a non-zero exit code
ep, err := NewExpect("tail", "-x") ep, err := NewExpect("tail", "-x")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel() defer cancel()
@ -109,12 +91,8 @@ func TestExpectFuncExitFailureStop(t *testing.T) {
exitCode, err := ep.ExitCode() exitCode, err := ep.ExitCode()
require.Equal(t, 1, exitCode) require.Equal(t, 1, exitCode)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, ep.Stop())
if err = ep.Stop(); err != nil { require.ErrorContains(t, ep.Close(), "unexpected exit code [1]")
t.Fatal(err)
}
err = ep.Close()
require.ErrorContains(t, err, "unexpected exit code [1]")
exitCode, err = ep.ExitCode() exitCode, err = ep.ExitCode()
require.Equal(t, 1, exitCode) require.Equal(t, 1, exitCode)
require.NoError(t, err) require.NoError(t, err)
@ -122,68 +100,41 @@ func TestExpectFuncExitFailureStop(t *testing.T) {
func TestEcho(t *testing.T) { func TestEcho(t *testing.T) {
ep, err := NewExpect("echo", "hello world") ep, err := NewExpect("echo", "hello world")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
ctx := context.Background() ctx := context.Background()
l, eerr := ep.ExpectWithContext(ctx, ExpectedResponse{Value: "world"}) l, eerr := ep.ExpectWithContext(ctx, ExpectedResponse{Value: "world"})
if eerr != nil { require.NoError(t, eerr)
t.Fatal(eerr)
}
wstr := "hello world" wstr := "hello world"
if l[:len(wstr)] != wstr { require.Equalf(t, l[:len(wstr)], wstr, `got "%v", expected "%v"`, l, wstr)
t.Fatalf(`got "%v", expected "%v"`, l, wstr) require.NoError(t, ep.Close())
} _, eerr = ep.ExpectWithContext(ctx, ExpectedResponse{Value: "..."})
if cerr := ep.Close(); cerr != nil { require.Errorf(t, eerr, "expected error on closed expect process")
t.Fatal(cerr)
}
if _, eerr = ep.ExpectWithContext(ctx, ExpectedResponse{Value: "..."}); eerr == nil {
t.Fatalf("expected error on closed expect process")
}
} }
func TestLineCount(t *testing.T) { func TestLineCount(t *testing.T) {
ep, err := NewExpect("printf", "1\n2\n3") ep, err := NewExpect("printf", "1\n2\n3")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
wstr := "3" wstr := "3"
l, eerr := ep.ExpectWithContext(context.Background(), ExpectedResponse{Value: wstr}) l, eerr := ep.ExpectWithContext(context.Background(), ExpectedResponse{Value: wstr})
if eerr != nil { require.NoError(t, eerr)
t.Fatal(eerr) require.Equalf(t, l, wstr, `got "%v", expected "%v"`, l, wstr)
} require.Equalf(t, 3, ep.LineCount(), "got %d, expected 3", ep.LineCount())
if l != wstr { require.NoError(t, ep.Close())
t.Fatalf(`got "%v", expected "%v"`, l, wstr)
}
if ep.LineCount() != 3 {
t.Fatalf("got %d, expected 3", ep.LineCount())
}
if cerr := ep.Close(); cerr != nil {
t.Fatal(cerr)
}
} }
func TestSend(t *testing.T) { func TestSend(t *testing.T) {
ep, err := NewExpect("tr", "a", "b") ep, err := NewExpect("tr", "a", "b")
if err != nil { require.NoError(t, err)
t.Fatal(err) err = ep.Send("a\r")
} require.NoError(t, err)
if err := ep.Send("a\r"); err != nil { _, err = ep.ExpectWithContext(context.Background(), ExpectedResponse{Value: "b"})
t.Fatal(err) require.NoError(t, err)
} require.NoError(t, ep.Stop())
if _, err := ep.ExpectWithContext(context.Background(), ExpectedResponse{Value: "b"}); err != nil {
t.Fatal(err)
}
if err := ep.Stop(); err != nil {
t.Fatal(err)
}
} }
func TestSignal(t *testing.T) { func TestSignal(t *testing.T) {
ep, err := NewExpect("sleep", "100") ep, err := NewExpect("sleep", "100")
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
ep.Signal(os.Interrupt) ep.Signal(os.Interrupt)
donec := make(chan struct{}) donec := make(chan struct{})
go func() { go func() {
@ -267,8 +218,7 @@ func TestResponseMatchRegularExpr(t *testing.T) {
require.Error(t, err) require.Error(t, err)
} }
cerr := ep.Close() require.NoError(t, ep.Close())
require.NoError(t, cerr)
}) })
} }
} }

View File

@ -19,6 +19,7 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/require"
"go.uber.org/zap/zaptest" "go.uber.org/zap/zaptest"
) )
@ -41,9 +42,8 @@ func TestSetFlagsFromEnv(t *testing.T) {
"a": "", "a": "",
"b": "bar", "b": "bar",
} { } {
if got := fs.Lookup(f).Value.String(); got != want { got := fs.Lookup(f).Value.String()
t.Fatalf("flag %q=%q, want %q", f, got, want) require.Equalf(t, want, got, "flag %q=%q, want %q", f, got, want)
}
} }
// now read the env and verify flags were updated as expected // now read the env and verify flags were updated as expected
@ -85,7 +85,5 @@ func TestSetFlagsFromEnvParsingError(t *testing.T) {
break break
} }
} }
if err != nil { require.NoErrorf(t, err, "unexpected error %v", err)
t.Fatalf("unexpected error %v", err)
}
} }

View File

@ -17,6 +17,8 @@ package flags
import ( import (
"reflect" "reflect"
"testing" "testing"
"github.com/stretchr/testify/require"
) )
func TestStringsValue(t *testing.T) { func TestStringsValue(t *testing.T) {
@ -30,8 +32,6 @@ func TestStringsValue(t *testing.T) {
} }
for i := range tests { for i := range tests {
ss := []string(*NewStringsValue(tests[i].s)) ss := []string(*NewStringsValue(tests[i].s))
if !reflect.DeepEqual(tests[i].exp, ss) { require.Truef(t, reflect.DeepEqual(tests[i].exp, ss), "#%d: expected %q, got %q", i, tests[i].exp, ss)
t.Fatalf("#%d: expected %q, got %q", i, tests[i].exp, ss)
}
} }
} }

View File

@ -19,6 +19,7 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestUint32Value(t *testing.T) { func TestUint32Value(t *testing.T) {
@ -101,9 +102,7 @@ func TestUint32FromFlag(t *testing.T) {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
fs := flag.NewFlagSet("etcd", flag.ContinueOnError) fs := flag.NewFlagSet("etcd", flag.ContinueOnError)
fs.Var(NewUint32Value(tc.defaultVal), flagName, "Maximum concurrent streams that each client can open at a time.") fs.Var(NewUint32Value(tc.defaultVal), flagName, "Maximum concurrent streams that each client can open at a time.")
if err := fs.Parse(tc.arguments); err != nil { require.NoError(t, fs.Parse(tc.arguments))
t.Fatalf("Unexpected error: %v\n", err)
}
actualMaxStream := Uint32FromFlag(fs, flagName) actualMaxStream := Uint32FromFlag(fs, flagName)
assert.Equal(t, tc.expectedVal, actualMaxStream) assert.Equal(t, tc.expectedVal, actualMaxStream)
}) })

View File

@ -17,6 +17,8 @@ package flags
import ( import (
"reflect" "reflect"
"testing" "testing"
"github.com/stretchr/testify/require"
) )
func TestNewUniqueStrings(t *testing.T) { func TestNewUniqueStrings(t *testing.T) {
@ -58,11 +60,7 @@ func TestNewUniqueStrings(t *testing.T) {
} }
for i := range tests { for i := range tests {
uv := NewUniqueStringsValue(tests[i].s) uv := NewUniqueStringsValue(tests[i].s)
if !reflect.DeepEqual(tests[i].exp, uv.Values) { require.Truef(t, reflect.DeepEqual(tests[i].exp, uv.Values), "#%d: expected %+v, got %+v", i, tests[i].exp, uv.Values)
t.Fatalf("#%d: expected %+v, got %+v", i, tests[i].exp, uv.Values) require.Equalf(t, uv.String(), tests[i].rs, "#%d: expected %q, got %q", i, tests[i].rs, uv.String())
}
if uv.String() != tests[i].rs {
t.Fatalf("#%d: expected %q, got %q", i, tests[i].rs, uv.String())
}
} }
} }

View File

@ -18,6 +18,8 @@ import (
"net/url" "net/url"
"reflect" "reflect"
"testing" "testing"
"github.com/stretchr/testify/require"
) )
func TestValidateURLsValueBad(t *testing.T) { func TestValidateURLsValueBad(t *testing.T) {
@ -66,8 +68,6 @@ func TestNewURLsValue(t *testing.T) {
} }
for i := range tests { for i := range tests {
uu := []url.URL(*NewURLsValue(tests[i].s)) uu := []url.URL(*NewURLsValue(tests[i].s))
if !reflect.DeepEqual(tests[i].exp, uu) { require.Truef(t, reflect.DeepEqual(tests[i].exp, uu), "#%d: expected %+v, got %+v", i, tests[i].exp, uu)
t.Fatalf("#%d: expected %+v, got %+v", i, tests[i].exp, uu)
}
} }
} }

View File

@ -19,6 +19,7 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestPageWriterRandom(t *testing.T) { func TestPageWriterRandom(t *testing.T) {
@ -36,12 +37,9 @@ func TestPageWriterRandom(t *testing.T) {
} }
n += c n += c
} }
if cw.writeBytes > n { require.LessOrEqualf(t, cw.writeBytes, n, "wrote %d bytes to io.Writer, but only wrote %d bytes", cw.writeBytes, n)
t.Fatalf("wrote %d bytes to io.Writer, but only wrote %d bytes", cw.writeBytes, n) maxPendingBytes := pageBytes + defaultBufferBytes
} require.LessOrEqualf(t, n-cw.writeBytes, maxPendingBytes, "got %d bytes pending, expected less than %d bytes", n-cw.writeBytes, maxPendingBytes)
if maxPendingBytes := pageBytes + defaultBufferBytes; n-cw.writeBytes > maxPendingBytes {
t.Fatalf("got %d bytes pending, expected less than %d bytes", n-cw.writeBytes, maxPendingBytes)
}
t.Logf("total writes: %d", cw.writes) t.Logf("total writes: %d", cw.writes)
t.Logf("total write bytes: %d (of %d)", cw.writeBytes, n) t.Logf("total write bytes: %d (of %d)", cw.writeBytes, n)
} }
@ -61,9 +59,7 @@ func TestPageWriterPartialSlack(t *testing.T) {
if err := w.Flush(); err != nil { if err := w.Flush(); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if cw.writes != 1 { require.Equalf(t, 1, cw.writes, "got %d writes, expected 1", cw.writes)
t.Fatalf("got %d writes, expected 1", cw.writes)
}
// nearly fill buffer // nearly fill buffer
if _, err := w.Write(buf[:1022]); err != nil { if _, err := w.Write(buf[:1022]); err != nil {
t.Fatal(err) t.Fatal(err)
@ -72,16 +68,12 @@ func TestPageWriterPartialSlack(t *testing.T) {
if _, err := w.Write(buf[:8]); err != nil { if _, err := w.Write(buf[:8]); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if cw.writes != 1 { require.Equalf(t, 1, cw.writes, "got %d writes, expected 1", cw.writes)
t.Fatalf("got %d writes, expected 1", cw.writes)
}
// finish writing slack space // finish writing slack space
if _, err := w.Write(buf[:128]); err != nil { if _, err := w.Write(buf[:128]); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if cw.writes != 2 { require.Equalf(t, 2, cw.writes, "got %d writes, expected 2", cw.writes)
t.Fatalf("got %d writes, expected 2", cw.writes)
}
} }
// TestPageWriterOffset tests if page writer correctly repositions when offset is given. // TestPageWriterOffset tests if page writer correctly repositions when offset is given.
@ -97,9 +89,7 @@ func TestPageWriterOffset(t *testing.T) {
if err := w.Flush(); err != nil { if err := w.Flush(); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if w.pageOffset != 64 { require.Equalf(t, 64, w.pageOffset, "w.pageOffset expected 64, got %d", w.pageOffset)
t.Fatalf("w.pageOffset expected 64, got %d", w.pageOffset)
}
w = NewPageWriter(cw, w.pageOffset, pageBytes) w = NewPageWriter(cw, w.pageOffset, pageBytes)
if _, err := w.Write(buf[:64]); err != nil { if _, err := w.Write(buf[:64]); err != nil {
@ -108,9 +98,7 @@ func TestPageWriterOffset(t *testing.T) {
if err := w.Flush(); err != nil { if err := w.Flush(); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if w.pageOffset != 0 { require.Equalf(t, 0, w.pageOffset, "w.pageOffset expected 0, got %d", w.pageOffset)
t.Fatalf("w.pageOffset expected 0, got %d", w.pageOffset)
}
} }
func TestPageWriterPageBytes(t *testing.T) { func TestPageWriterPageBytes(t *testing.T) {
@ -161,9 +149,7 @@ type checkPageWriter struct {
} }
func (cw *checkPageWriter) Write(p []byte) (int, error) { func (cw *checkPageWriter) Write(p []byte) (int, error) {
if len(p)%cw.pageBytes != 0 { require.Equalf(cw.t, 0, len(p)%cw.pageBytes, "got write len(p) = %d, expected len(p) == k*cw.pageBytes", len(p))
cw.t.Fatalf("got write len(p) = %d, expected len(p) == k*cw.pageBytes", len(p))
}
cw.writes++ cw.writes++
cw.writeBytes += len(p) cw.writeBytes += len(p)
return len(p), nil return len(p), nil

View File

@ -16,9 +16,10 @@ package ioutil
import ( import (
"bytes" "bytes"
"errors"
"io" "io"
"testing" "testing"
"github.com/stretchr/testify/require"
) )
type readerNilCloser struct{ io.Reader } type readerNilCloser struct{ io.Reader }
@ -29,19 +30,15 @@ func (rc *readerNilCloser) Close() error { return nil }
func TestExactReadCloserExpectEOF(t *testing.T) { func TestExactReadCloserExpectEOF(t *testing.T) {
buf := bytes.NewBuffer(make([]byte, 10)) buf := bytes.NewBuffer(make([]byte, 10))
rc := NewExactReadCloser(&readerNilCloser{buf}, 1) rc := NewExactReadCloser(&readerNilCloser{buf}, 1)
if _, err := rc.Read(make([]byte, 10)); !errors.Is(err, ErrExpectEOF) { _, err := rc.Read(make([]byte, 10))
t.Fatalf("expected %v, got %v", ErrExpectEOF, err) require.ErrorIsf(t, err, ErrExpectEOF, "expected %v, got %v", ErrExpectEOF, err)
}
} }
// TestExactReadCloserShort expects an eof when reading too little // TestExactReadCloserShort expects an eof when reading too little
func TestExactReadCloserShort(t *testing.T) { func TestExactReadCloserShort(t *testing.T) {
buf := bytes.NewBuffer(make([]byte, 5)) buf := bytes.NewBuffer(make([]byte, 5))
rc := NewExactReadCloser(&readerNilCloser{buf}, 10) rc := NewExactReadCloser(&readerNilCloser{buf}, 10)
if _, err := rc.Read(make([]byte, 10)); err != nil { _, err := rc.Read(make([]byte, 10))
t.Fatalf("Read expected nil err, got %v", err) require.NoErrorf(t, err, "Read expected nil err, got %v", err)
} require.ErrorIs(t, rc.Close(), ErrShortRead)
if err := rc.Close(); !errors.Is(err, ErrShortRead) {
t.Fatalf("Close expected %v, got %v", ErrShortRead, err)
}
} }

View File

@ -20,6 +20,8 @@ import (
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
) )
func TestPercentiles(t *testing.T) { func TestPercentiles(t *testing.T) {
@ -64,9 +66,7 @@ func TestReport(t *testing.T) {
ErrorDist: map[string]int{"oops": 1}, ErrorDist: map[string]int{"oops": 1},
Lats: []float64{1.0, 1.0, 1.0, 1.0, 1.0}, Lats: []float64{1.0, 1.0, 1.0, 1.0, 1.0},
} }
if !reflect.DeepEqual(stats, wStats) { require.Truef(t, reflect.DeepEqual(stats, wStats), "got %+v, want %+v", stats, wStats)
t.Fatalf("got %+v, want %+v", stats, wStats)
}
wstrs := []string{ wstrs := []string{
"Stddev:\t0", "Stddev:\t0",
@ -108,7 +108,5 @@ func TestWeightedReport(t *testing.T) {
ErrorDist: map[string]int{"oops": 1}, ErrorDist: map[string]int{"oops": 1},
Lats: []float64{0.5, 0.5, 0.5, 0.5, 0.5}, Lats: []float64{0.5, 0.5, 0.5, 0.5, 0.5},
} }
if !reflect.DeepEqual(stats, wStats) { require.Truef(t, reflect.DeepEqual(stats, wStats), "got %+v, want %+v", stats, wStats)
t.Fatalf("got %+v, want %+v", stats, wStats)
}
} }

View File

@ -17,6 +17,8 @@ package report
import ( import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
) )
func TestGetTimeseries(t *testing.T) { func TestGetTimeseries(t *testing.T) {
@ -25,20 +27,12 @@ func TestGetTimeseries(t *testing.T) {
sp.Add(now, time.Second) sp.Add(now, time.Second)
sp.Add(now.Add(5*time.Second), time.Second) sp.Add(now.Add(5*time.Second), time.Second)
n := sp.getTimeSeries().Len() n := sp.getTimeSeries().Len()
if n < 3 { require.GreaterOrEqualf(t, n, 3, "expected at 6 points of time series, got %s", sp.getTimeSeries())
t.Fatalf("expected at 6 points of time series, got %s", sp.getTimeSeries())
}
// add a point with duplicate timestamp // add a point with duplicate timestamp
sp.Add(now, 3*time.Second) sp.Add(now, 3*time.Second)
ts := sp.getTimeSeries() ts := sp.getTimeSeries()
if ts[0].MinLatency != time.Second { require.Equalf(t, time.Second, ts[0].MinLatency, "ts[0] min latency expected %v, got %s", time.Second, ts[0].MinLatency)
t.Fatalf("ts[0] min latency expected %v, got %s", time.Second, ts[0].MinLatency) require.Equalf(t, 2*time.Second, ts[0].AvgLatency, "ts[0] average latency expected %v, got %s", 2*time.Second, ts[0].AvgLatency)
} require.Equalf(t, 3*time.Second, ts[0].MaxLatency, "ts[0] max latency expected %v, got %s", 3*time.Second, ts[0].MaxLatency)
if ts[0].AvgLatency != 2*time.Second {
t.Fatalf("ts[0] average latency expected %v, got %s", 2*time.Second, ts[0].AvgLatency)
}
if ts[0].MaxLatency != 3*time.Second {
t.Fatalf("ts[0] max latency expected %v, got %s", 3*time.Second, ts[0].MaxLatency)
}
} }

View File

@ -19,6 +19,7 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/stretchr/testify/require"
"go.uber.org/zap/zaptest" "go.uber.org/zap/zaptest"
) )
@ -34,9 +35,7 @@ func TestFIFOSchedule(t *testing.T) {
fmt.Println("err: ", err) fmt.Println("err: ", err)
} }
}() }()
if next != i { require.Equalf(t, next, i, "job#%d: got %d, want %d", i, next, i)
t.Fatalf("job#%d: got %d, want %d", i, next, i)
}
next = i + 1 next = i + 1
if next%3 == 0 { if next%3 == 0 {
panic("fifo panic") panic("fifo panic")

View File

@ -17,14 +17,14 @@ package stringutil
import ( import (
"sort" "sort"
"testing" "testing"
"github.com/stretchr/testify/require"
) )
func TestUniqueStrings(t *testing.T) { func TestUniqueStrings(t *testing.T) {
ss := UniqueStrings(10, 50) ss := UniqueStrings(10, 50)
sort.Strings(ss) sort.Strings(ss)
for i := 1; i < len(ss); i++ { for i := 1; i < len(ss); i++ {
if ss[i-1] == ss[i] { require.NotEqualf(t, ss[i-1], ss[i], "ss[i-1] %q == ss[i] %q", ss[i-1], ss[i])
t.Fatalf("ss[i-1] %q == ss[i] %q", ss[i-1], ss[i])
}
} }
} }

View File

@ -23,6 +23,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require"
"go.etcd.io/etcd/client/pkg/v3/logutil" "go.etcd.io/etcd/client/pkg/v3/logutil"
) )
@ -215,9 +217,7 @@ func TestLog(t *testing.T) {
tt.trace.lg = lg tt.trace.lg = lg
tt.trace.Log() tt.trace.Log()
data, err := os.ReadFile(logPath) data, err := os.ReadFile(logPath)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
for _, msg := range tt.expectedMsg { for _, msg := range tt.expectedMsg {
if !bytes.Contains(data, []byte(msg)) { if !bytes.Contains(data, []byte(msg)) {
@ -293,9 +293,7 @@ func TestLogIfLong(t *testing.T) {
tt.trace.lg = lg tt.trace.lg = lg
tt.trace.LogIfLong(tt.threshold) tt.trace.LogIfLong(tt.threshold)
data, err := os.ReadFile(logPath) data, err := os.ReadFile(logPath)
if err != nil { require.NoError(t, err)
t.Fatal(err)
}
for _, msg := range tt.expectedMsg { for _, msg := range tt.expectedMsg {
if !bytes.Contains(data, []byte(msg)) { if !bytes.Contains(data, []byte(msg)) {
t.Errorf("Expected to find %v in log", msg) t.Errorf("Expected to find %v in log", msg)