Home > OS >  Testing around GRPC stream Send function in Go
Testing around GRPC stream Send function in Go

Time:10-24

I have a Go GRPC server-side streaming function:

func (server *Server) GetClients(req *iam.GetClientsRequest, client iam.IAM_GetClientsServer) error {
    ctx := client.(interface{ Context() context.Context }).Context()

    userID, err := getUserIDStream(client)
    if err != nil {
        return err
    }

    clients, err := server.db.QueryByUserID(ctx, userID)
    if err != nil {
        return grpc.Errorf(codes.Internal, apiutils.ServerError)
    }

    for _, value := range clients {
        converted, err := server.fromInternalClient(value)
        if err != nil {
            return err
        }

        if err := client.Send(converted); err != nil {
            return err
        }
    }

    return nil
}

and I'm testing it like this:

It("GetClients - Send fails - Error", func() {

    handler := createHandler(db)
    lis := bufconn.Listen(bufSize)
    server := grpc.NewServer()

    iam.RegisterIAMServer(server, NewServer(handler))
    go func() {
        if err := server.Serve(lis); err != nil {
            log.Fatalf("Server exited with error: %v", err)
        }
    }()

    defer lis.Close()
    defer server.GracefulStop()

    conn, err := grpc.DialContext(context.Background(), "bufnet",
        grpc.WithContextDialer(createBufDialier(lis)), grpc.WithInsecure())
    Expect(err).ShouldNot(HaveOccurred())
    defer conn.Close()
    client := iam.NewIAMClient(conn)

    cclient, _ := client.GetClients(addAccessToken(context.Background()), new(iam.GetClientsRequest))
    resp, err := cclient.Recv()

    Expect(resp).Should(BeNil())
    Expect(err).Should(HaveOccurred())
    Expect(err.Error()).Should(Equal(message))
})

My issue is that I'm not sure how to induce a failure on Send so I can test the response. Since I'm using an actual test server and client, I can't just mock out the object and I'd prefer not to go that route anyway. Is there a way I can do this?

CodePudding user response:

Originally, I was trying to force Send to fail by setting bufSize to an artificially low value. However, this wasn't producing an error so I decided to try modifying the maxSendMessageSize on the server:

opts := []grpc.ServerOption{}
if sendFails {
    opts = append(opts, grpc.MaxSendMsgSize(10))
}

lis := bufconn.Listen(bufSize)
server := grpc.NewServer(opts...)

And this worked in producing the error.

  • Related