Skip to content

Commit

Permalink
SetAsserter works only outside unit tests, they MUST use pkg asserter
Browse files Browse the repository at this point in the history
  • Loading branch information
lainio committed Sep 8, 2024
1 parent a9dc394 commit 73eb244
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
13 changes: 9 additions & 4 deletions assert/assert.go
Original file line number Diff line number Diff line change
Expand Up @@ -967,8 +967,6 @@ func doNotZero[T Number](val T, a []any) {
//
// NOTE that since our TLS [asserterMap] we still continue to use indexing.
func current() (curAsserter asserter) {
// we need thread local storage, maybe we'll implement that to x.package?
// study `tester` and copy ideas from it.
tlsID := goid()
asserterMap.Rx(func(m map[int]asserter) {
aster, found := m[tlsID]
Expand Down Expand Up @@ -1023,9 +1021,16 @@ func SetDefault(i defInd) (old defInd) {
// to return plain error messages instead of the panic asserts, they can use
// following:
//
// assert.SetAsserter(assert.Plain)
// defer assert.SetAsserter(assert.Plain)()
func SetAsserter(i defInd) func() {
asserterMap.Set(goid(), defAsserter[i])
// get pkg lvl asserter
curAsserter := defAsserter[def]
// .. to check if we are doing unit tests
if !curAsserter.isUnitTesting() {
// .. allow TLS specific asserter. NOTE see current()
curGoRID := goid()
asserterMap.Set(curGoRID, defAsserter[i])
}
return popCurrentAsserter
}

Expand Down
16 changes: 16 additions & 0 deletions assert/assert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,22 @@ func ExampleCLen() {
// Output: sample: assert_test.go:253: ExampleCLen.func1(): assertion failure: length: got '2', want '3'
}

func ExampleThatNot() {
sample := func() (err error) {
defer err2.Handle(&err)

assert.ThatNot(true, "overrides if Plain asserter")
return err
}

// set asserter for this thread/goroutine only, we want plain errors
defer assert.SetAsserter(assert.Plain)()

err := sample()
fmt.Printf("%v", err)
// Output: testing: run example: overrides if Plain asserter
}

func BenchmarkMKeyExists(b *testing.B) {
bs := map[int]int{0: 0, 1: 1}
for n := 0; n < b.N; n++ {
Expand Down

0 comments on commit 73eb244

Please sign in to comment.