1// Copyright 2020 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package fake
16
17import (
18	"context"
19	"net"
20	"testing"
21
22	translate "cloud.google.com/go/translate/apiv3"
23	"google.golang.org/api/option"
24	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
25	"google.golang.org/grpc"
26)
27
28// fakeTranslationServer respresents a fake gRPC server where all of the methods
29// are unimplemented except TranslateText which is explicitly overridden.
30type fakeTranslationServer struct {
31	translatepb.UnimplementedTranslationServiceServer
32}
33
34func (f *fakeTranslationServer) TranslateText(ctx context.Context, req *translatepb.TranslateTextRequest) (*translatepb.TranslateTextResponse, error) {
35	resp := &translatepb.TranslateTextResponse{
36		Translations: []*translatepb.Translation{
37			{TranslatedText: "Hello World"},
38		},
39	}
40	return resp, nil
41}
42
43func TestTranslateTextWithConcreteClient(t *testing.T) {
44	ctx := context.Background()
45
46	// Setup the fake server.
47	fakeTranslationServer := &fakeTranslationServer{}
48	l, err := net.Listen("tcp", "localhost:0")
49	if err != nil {
50		t.Fatal(err)
51	}
52	gsrv := grpc.NewServer()
53	translatepb.RegisterTranslationServiceServer(gsrv, fakeTranslationServer)
54	fakeServerAddr := l.Addr().String()
55	go func() {
56		if err := gsrv.Serve(l); err != nil {
57			panic(err)
58		}
59	}()
60
61	// Create a client.
62	client, err := translate.NewTranslationClient(ctx,
63		option.WithEndpoint(fakeServerAddr),
64		option.WithoutAuthentication(),
65		option.WithGRPCDialOption(grpc.WithInsecure()),
66	)
67	if err != nil {
68		t.Fatal(err)
69	}
70
71	// Run the test.
72	text, err := TranslateTextWithConcreteClient(client, "Hola Mundo", "en-US")
73	if err != nil {
74		t.Fatal(err)
75	}
76	if text != "Hello World" {
77		t.Fatalf("got %q, want Hello World", text)
78	}
79}
80