...

Source file src/golang.conradwood.net/tests/functionchain/funcchain_test.go

Documentation: golang.conradwood.net/tests/functionchain

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"golang.conradwood.net/go-easyops/errors"
     9  	"golang.conradwood.net/go-easyops/utils/functionchain"
    10  )
    11  
    12  func TestFuncChain(t *testing.T) {
    13  	fc := functionchain.NewFunctionChain()
    14  	xt := &tester{
    15  		t:                t,
    16  		disable_fail_ctr: 5,
    17  	}
    18  	fc.Add(xt)
    19  	xt.enable_fail_max = 5
    20  	testfc(t, xt, true, true)
    21  	testfc(t, xt, false, false)
    22  }
    23  
    24  type tester struct {
    25  	t                 *testing.T
    26  	enable_fail_max   int // how often to fail
    27  	enable_fail_ctr   int // how often actually failed
    28  	enable_requested  int
    29  	enable_failed     int
    30  	disable_fail_max  int // how often to fail
    31  	disable_fail_ctr  int // how often actually failed
    32  	disable_requested int
    33  	disable_failed    int
    34  }
    35  
    36  func (ts *tester) SetTo(ctx context.Context, b bool) error {
    37  	if b {
    38  		ts.enable_requested++
    39  		if ts.enable_fail_ctr < ts.enable_fail_max {
    40  			ts.enable_fail_ctr++
    41  			return errors.Errorf("enable fail")
    42  		}
    43  	} else {
    44  		ts.disable_requested++
    45  		if ts.disable_fail_ctr < ts.disable_fail_max {
    46  			ts.disable_fail_ctr++
    47  			return errors.Errorf("disable fail")
    48  		}
    49  	}
    50  	return nil
    51  }
    52  
    53  func testfc(t *testing.T, xt *tester, enable, enable_result bool) {
    54  	fc := functionchain.NewFunctionChain()
    55  	fc.Add(xt)
    56  	started := time.Now()
    57  	err := fc.SetTo(context.Background(), enable)
    58  	diff := time.Since(started)
    59  
    60  	if enable_result && err != nil {
    61  		// failed
    62  		t.Errorf("Failed enable=%v after %0.1fs", enable, diff.Seconds())
    63  		return
    64  
    65  	}
    66  
    67  	if !enable_result && err == nil {
    68  		// failed
    69  		t.Errorf("Expected to fail enable=%v, but it did not after %0.1fs", enable, diff.Seconds())
    70  		return
    71  
    72  	}
    73  
    74  }
    75  

View as plain text