github.com/haraldrudell/parl@v0.4.176/on-debug_test.go (about)

     1  /*
     2  © 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  import (
     9  	"io"
    10  	"testing"
    11  
    12  	"github.com/haraldrudell/parl/plog"
    13  	"github.com/haraldrudell/parl/pruntime"
    14  )
    15  
    16  type TestWriter struct {
    17  	counter AtomicCounter
    18  }
    19  
    20  func (w *TestWriter) Write(b []byte) (n int, err error) {
    21  	w.counter.Inc()
    22  	n = len(b)
    23  	return
    24  }
    25  
    26  var _ io.Writer = &TestWriter{}
    27  
    28  func TestDebugThunk(t *testing.T) {
    29  	var expNoDebug = 0
    30  	var expDebug = 1
    31  	var expRegexp = 1
    32  
    33  	var testWriter = TestWriter{}
    34  	var myLogger = plog.NewLog(&testWriter)
    35  
    36  	var realStderrLogger = stderrLogger
    37  	stderrLogger = myLogger
    38  	defer func() { stderrLogger = realStderrLogger }()
    39  
    40  	// Debug false
    41  	testWriter.counter.Set(0)
    42  	OnDebug(func() string { return "" })
    43  	if c := testWriter.counter.Value(); c != uint64(expNoDebug) {
    44  		t.Errorf("debug false testWriter.counter %d exp %d", c, expNoDebug)
    45  	}
    46  
    47  	// Debug true
    48  	SetDebug(true)
    49  	testWriter.counter.Set(0)
    50  	OnDebug(func() string { return "" })
    51  	if c := testWriter.counter.Value(); c != uint64(expDebug) {
    52  		t.Errorf("debug true testWriter.counter %d exp %d", c, expDebug)
    53  	}
    54  	SetDebug(false)
    55  
    56  	// regexp debug
    57  	var funcName = pruntime.NewCodeLocation(0).FuncName
    58  	t.Logf("funcName: %q", funcName)
    59  	SetRegexp(funcName)
    60  	testWriter.counter.Set(0)
    61  	OnDebug(func() string { return "" })
    62  	if c := testWriter.counter.Value(); c != uint64(expRegexp) {
    63  		t.Errorf("regexp testWriter.counter %d exp %d", c, expRegexp)
    64  	}
    65  	SetRegexp("")
    66  }