github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zdi/lazy_test.go (about)

     1  package zdi_test
     2  
     3  import (
     4  	"github.com/sohaha/zlsgo/ztype"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/sohaha/zlsgo"
     9  	"github.com/sohaha/zlsgo/zdi"
    10  	"github.com/sohaha/zlsgo/ztime"
    11  )
    12  
    13  func TestProvide(t *testing.T) {
    14  	tt := zlsgo.NewTest(t)
    15  	di := zdi.New()
    16  
    17  	val := ztime.Now()
    18  
    19  	di.Provide(func() *testSt {
    20  		tt.Log("init testSt")
    21  		return &testSt{Msg: val, Num: 666}
    22  	})
    23  
    24  	di.Provide(func(ts *testSt) *testSt2 {
    25  		tt.Log("init testSt2")
    26  		return &testSt2{Name: "2->" + ts.Msg}
    27  	})
    28  
    29  	override := di.Provide(func() time.Time {
    30  		tt.Log("init time")
    31  		return time.Now()
    32  	})
    33  	tt.Log(override)
    34  
    35  	// overwrite the previous time.Time, *testSt
    36  	override = di.Provide(func() (time.Time, *testSt) {
    37  		tt.Log("init time2")
    38  		return time.Now(), &testSt{Msg: val, Num: 999}
    39  	})
    40  	tt.Log(override)
    41  
    42  	_, err := di.Invoke(func(t2 *testSt2, t1 *testSt, now time.Time) {
    43  		tt.Log(t2.Name, t1.Num, now)
    44  		tt.Equal(val, t1.Msg)
    45  	})
    46  	tt.NoError(err)
    47  
    48  	di.Provide(func() *ztype.Type {
    49  		tt.Log("test panic")
    50  		panic("panic")
    51  		return nil
    52  	})
    53  
    54  	_, err = di.Invoke(func(typ *ztype.Type) {
    55  		tt.Log(typ)
    56  	})
    57  	tt.EqualTrue(err != nil)
    58  	t.Log(err)
    59  }