github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/service_test.go (about) 1 package service 2 3 import ( 4 "context" 5 "errors" 6 "sync" 7 "testing" 8 9 "github.com/tickoalcantara12/micro/v3/profile" 10 proto "github.com/tickoalcantara12/micro/v3/proto/debug" 11 "github.com/tickoalcantara12/micro/v3/service/client" 12 ) 13 14 func testShutdown(wg *sync.WaitGroup, cancel func()) { 15 // add 1 16 wg.Add(1) 17 // shutdown the service 18 cancel() 19 // wait for stop 20 wg.Wait() 21 } 22 23 func testService(ctx context.Context, wg *sync.WaitGroup, name string) *Service { 24 profile.Test.Setup(nil) 25 26 // add self 27 wg.Add(1) 28 29 // create service 30 return New( 31 Name(name), 32 AfterStart(func() error { 33 wg.Done() 34 return nil 35 }), 36 AfterStop(func() error { 37 wg.Done() 38 return nil 39 }), 40 ) 41 } 42 43 func testRequest(ctx context.Context, c client.Client, name string) error { 44 // test call debug 45 req := c.NewRequest( 46 name, 47 "Debug.Health", 48 new(proto.HealthRequest), 49 ) 50 51 rsp := new(proto.HealthResponse) 52 53 err := c.Call(context.TODO(), req, rsp) 54 if err != nil { 55 return err 56 } 57 58 if rsp.Status != "ok" { 59 return errors.New("service response: " + rsp.Status) 60 } 61 62 return nil 63 } 64 65 func benchmarkService(b *testing.B, n int, name string) { 66 // stop the timer 67 b.StopTimer() 68 69 // waitgroup for server start 70 var wg sync.WaitGroup 71 72 // cancellation context 73 ctx, cancel := context.WithCancel(context.Background()) 74 75 // create test server 76 service := testService(ctx, &wg, name) 77 78 // start the server 79 go func() { 80 if err := service.Run(); err != nil { 81 b.Fatal(err) 82 } 83 }() 84 85 // wait for service to start 86 wg.Wait() 87 88 // make a test call to warm the cache 89 for i := 0; i < 10; i++ { 90 if err := testRequest(ctx, service.Client(), name); err != nil { 91 b.Fatal(err) 92 } 93 } 94 95 // start the timer 96 b.StartTimer() 97 98 // number of iterations 99 for i := 0; i < b.N; i++ { 100 // for concurrency 101 for j := 0; j < n; j++ { 102 wg.Add(1) 103 104 go func() { 105 err := testRequest(ctx, service.Client(), name) 106 wg.Done() 107 if err != nil { 108 b.Fatal(err) 109 } 110 }() 111 } 112 113 // wait for test completion 114 wg.Wait() 115 } 116 117 // stop the timer 118 b.StopTimer() 119 120 // shutdown service 121 testShutdown(&wg, cancel) 122 } 123 124 func BenchmarkService1(b *testing.B) { 125 benchmarkService(b, 1, "test.service.1") 126 } 127 128 func BenchmarkService8(b *testing.B) { 129 benchmarkService(b, 8, "test.service.8") 130 } 131 132 func BenchmarkService16(b *testing.B) { 133 benchmarkService(b, 16, "test.service.16") 134 } 135 136 func BenchmarkService32(b *testing.B) { 137 benchmarkService(b, 32, "test.service.32") 138 } 139 140 func BenchmarkService64(b *testing.B) { 141 benchmarkService(b, 64, "test.service.64") 142 }