MCPcopy
hub / github.com/nats-io/nats.go / TestContextHandler

Function TestContextHandler

micro/test/service_test.go:967–1022  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

965}
966
967func TestContextHandler(t *testing.T) {
968 s := RunServerOnPort(-1)
969 defer s.Shutdown()
970
971 nc, err := nats.Connect(s.ClientURL())
972 if err != nil {
973 t.Fatalf("Expected to connect to server, got %v", err)
974 }
975 defer nc.Close()
976
977 ctx, cancel := context.WithCancel(context.Background())
978 defer cancel()
979
980 type key string
981 ctx = context.WithValue(ctx, key("key"), []byte("val"))
982
983 handler := func(ctx context.Context, req micro.Request) {
984 select {
985 case <-ctx.Done():
986 req.Error("400", "context canceled", nil)
987 default:
988 v := ctx.Value(key("key"))
989 req.Respond(v.([]byte))
990 }
991 }
992 config := micro.Config{
993 Name: "test_service",
994 Version: "0.1.0",
995 Endpoint: &micro.EndpointConfig{
996 Subject: "test.func",
997 Handler: micro.ContextHandler(ctx, handler),
998 },
999 }
1000
1001 srv, err := micro.AddService(nc, config)
1002 if err != nil {
1003 t.Fatalf("Unexpected error: %v", err)
1004 }
1005 defer srv.Stop()
1006
1007 resp, err := nc.Request("test.func", nil, 1*time.Second)
1008 if err != nil {
1009 t.Fatalf("Unexpected error: %s", err)
1010 }
1011 if string(resp.Data) != "val" {
1012 t.Fatalf("Invalid response; want: %q; got: %q", "val", string(resp.Data))
1013 }
1014 cancel()
1015 resp, err = nc.Request("test.func", nil, 1*time.Second)
1016 if err != nil {
1017 t.Fatalf("Unexpected error: %s", err)
1018 }
1019 if resp.Header.Get(micro.ErrorCodeHeader) != "400" {
1020 t.Fatalf("Expected error response after canceling context; got: %q", string(resp.Data))
1021 }
1022}
1023
1024func TestAddEndpoint_Concurrency(t *testing.T) {

Callers

nothing calls this directly

Calls 14

ContextHandlerFunction · 0.92
AddServiceFunction · 0.92
keyTypeAlias · 0.85
ConnectMethod · 0.80
FatalfMethod · 0.80
RunServerOnPortFunction · 0.70
DoneMethod · 0.65
ErrorMethod · 0.65
ValueMethod · 0.65
RespondMethod · 0.65
StopMethod · 0.65
GetMethod · 0.65

Tested by

no test coverage detected