lab.nexedi.com/kirr/go123@v0.0.0-20240207185015-8299741fa871/internal/xtesting/xtesting.go (about) 1 // Copyright (C) 2018 Nexedi SA and Contributors. 2 // Kirill Smelkov <kirr@nexedi.com> 3 // 4 // This program is free software: you can Use, Study, Modify and Redistribute 5 // it under the terms of the GNU General Public License version 3, or (at your 6 // option) any later version, as published by the Free Software Foundation. 7 // 8 // You can also Link and Combine this program with other software covered by 9 // the terms of any of the Free Software licenses or any of the Open Source 10 // Initiative approved licenses and Convey the resulting work. Corresponding 11 // source of such a combination shall include the source code for all other 12 // software used. 13 // 14 // This program is distributed WITHOUT ANY WARRANTY; without even the implied 15 // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 16 // 17 // See COPYING file for full licensing terms. 18 // See https://www.nexedi.com/licensing for rationale and options. 19 20 // Package xtesting provides addons to std package testing. 21 // 22 // The tools provided are mostly useful when doing tests with exceptions. 23 package xtesting 24 25 import ( 26 "fmt" 27 "reflect" 28 "testing" 29 30 "lab.nexedi.com/kirr/go123/exc" 31 ) 32 33 // Asserter is handy objects to make asserts in tests. 34 // 35 // For example: 36 // 37 // assert := xtesting.Assert(t) 38 // assert.Eq(a, b) 39 // .. 40 // 41 // Contrary to t.Fatal* and e.g. github.com/stretchr/testify/require.Assert it 42 // is safe to use Asserter from non-main goroutine. 43 type Asserter struct { 44 t testing.TB 45 } 46 47 // Assert creates Asserter bound to t for reporting. 48 func Assert(t testing.TB) *Asserter { 49 return &Asserter{t} 50 } 51 52 // Eq asserts that a == b and raises exception if not. 53 func (x *Asserter) Eq(a, b interface{}) { 54 x.t.Helper() 55 if !reflect.DeepEqual(a, b) { 56 fmt.Printf("not equal:\nhave: %v\nwant: %v\n", a, b) 57 x.t.Errorf("not equal:\nhave: %v\nwant: %v", a, b) 58 exc.Raise(0) 59 } 60 }