(t *testing.T)
| 1022 | } |
| 1023 | |
| 1024 | func TestAddEndpoint_Concurrency(t *testing.T) { |
| 1025 | s := RunServerOnPort(-1) |
| 1026 | defer s.Shutdown() |
| 1027 | |
| 1028 | nc, err := nats.Connect(s.ClientURL()) |
| 1029 | if err != nil { |
| 1030 | t.Fatalf("Expected to connect to server, got %v", err) |
| 1031 | } |
| 1032 | defer nc.Close() |
| 1033 | |
| 1034 | ctx := context.Background() |
| 1035 | |
| 1036 | handler := func(ctx context.Context, req micro.Request) { |
| 1037 | req.RespondJSON(map[string]any{"hello": "world"}) |
| 1038 | } |
| 1039 | config := micro.Config{ |
| 1040 | Name: "test_service", |
| 1041 | Version: "0.1.0", |
| 1042 | } |
| 1043 | |
| 1044 | srv, err := micro.AddService(nc, config) |
| 1045 | if err != nil { |
| 1046 | t.Fatalf("Unexpected error: %v", err) |
| 1047 | } |
| 1048 | defer srv.Stop() |
| 1049 | |
| 1050 | res := make(chan error, 10) |
| 1051 | wg := sync.WaitGroup{} |
| 1052 | wg.Add(10) |
| 1053 | |
| 1054 | // now add a few endpoints concurrently |
| 1055 | // and make sure they are added successfully |
| 1056 | // and there is no race |
| 1057 | for i := 0; i < 10; i++ { |
| 1058 | go func(i int) { |
| 1059 | wg.Wait() |
| 1060 | res <- srv.AddEndpoint(fmt.Sprintf("test%d", i), micro.ContextHandler(ctx, handler)) |
| 1061 | }(i) |
| 1062 | // after all goroutines are started, release the lock |
| 1063 | } |
| 1064 | wg.Add(-10) |
| 1065 | |
| 1066 | for i := 0; i < 10; i++ { |
| 1067 | select { |
| 1068 | case err := <-res: |
| 1069 | if err != nil { |
| 1070 | t.Fatalf("Unexpected error: %s", err) |
| 1071 | } |
| 1072 | case <-time.After(1 * time.Second): |
| 1073 | t.Fatalf("Timeout waiting for endpoint to be added") |
| 1074 | } |
| 1075 | } |
| 1076 | |
| 1077 | if len(srv.Info().Endpoints) != 10 { |
| 1078 | t.Fatalf("Expected 11 endpoints, got: %d", len(srv.Info().Endpoints)) |
| 1079 | } |
| 1080 | |
| 1081 | } |
nothing calls this directly
no test coverage detected