github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/must/must_test.go (about)

     1  // Copyright 2019 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache 2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package must_test
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"runtime"
    11  	"testing"
    12  
    13  	"github.com/Schaudge/grailbase/must"
    14  )
    15  
    16  // TestDepth verifies that the depth passed to Func correctly locates the
    17  // caller of the must function.
    18  func TestDepth(t *testing.T) {
    19  	_, thisFile, _, ok := runtime.Caller(0)
    20  	if !ok {
    21  		t.Fatal("could not determine current file")
    22  	}
    23  	must.Func = func(depth int, v ...interface{}) {
    24  		_, file, _, ok := runtime.Caller(depth)
    25  		if !ok {
    26  			t.Fatal("could not determine caller of Func")
    27  		}
    28  		if file != thisFile {
    29  			t.Errorf("caller at depth %d is '%s'; should be '%s'", depth, file, thisFile)
    30  		}
    31  	}
    32  	must.True(false)
    33  	must.Truef(false, "")
    34  	must.Nil(struct{}{})
    35  	must.Nilf(struct{}{}, "")
    36  	must.Never()
    37  	must.Neverf("")
    38  }
    39  
    40  func Example() {
    41  	must.Func = func(depth int, v ...interface{}) {
    42  		fmt.Print(v...)
    43  		fmt.Print("\n")
    44  	}
    45  
    46  	must.Nil(errors.New("unexpected condition"))
    47  	must.Nil(nil)
    48  	must.Nil(errors.New("some error"))
    49  	must.Nil(errors.New("i/o error"), "reading file")
    50  
    51  	must.True(false)
    52  	must.True(true, "something happened")
    53  	must.True(false, "a condition failed")
    54  
    55  	// Output:
    56  	// unexpected condition
    57  	// some error
    58  	// reading file: i/o error
    59  	// must: assertion failed
    60  	// a condition failed
    61  }