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 testutil_test
16
17import (
18	"context"
19	"flag"
20	"fmt"
21	"log"
22	"net"
23	"testing"
24
25	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
26	"cloud.google.com/go/spanner/internal/testutil"
27	"github.com/golang/protobuf/proto"
28	"google.golang.org/api/option"
29	instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1"
30	"google.golang.org/grpc"
31)
32
33var instanceClientOpt option.ClientOption
34
35var (
36	mockInstanceAdmin = testutil.NewInMemInstanceAdminServer()
37)
38
39func setupInstanceAdminServer() {
40	flag.Parse()
41
42	serv := grpc.NewServer()
43	instancepb.RegisterInstanceAdminServer(serv, mockInstanceAdmin)
44
45	lis, err := net.Listen("tcp", "localhost:0")
46	if err != nil {
47		log.Fatal(err)
48	}
49	go serv.Serve(lis)
50
51	conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
52	if err != nil {
53		log.Fatal(err)
54	}
55	instanceClientOpt = option.WithGRPCConn(conn)
56}
57
58func TestInstanceAdminGetInstance(t *testing.T) {
59	setupInstanceAdminServer()
60	var expectedResponse = &instancepb.Instance{
61		Name:        "name2-1052831874",
62		Config:      "config-1354792126",
63		DisplayName: "displayName1615086568",
64		NodeCount:   1539922066,
65	}
66
67	mockInstanceAdmin.SetErr(nil)
68	mockInstanceAdmin.SetReqs(nil)
69
70	mockInstanceAdmin.SetResps(append(mockInstanceAdmin.Resps()[:0], expectedResponse))
71
72	var formattedName string = fmt.Sprintf("projects/%s/instances/%s", "[PROJECT]", "[INSTANCE]")
73	var request = &instancepb.GetInstanceRequest{
74		Name: formattedName,
75	}
76
77	c, err := instance.NewInstanceAdminClient(context.Background(), instanceClientOpt)
78	if err != nil {
79		t.Fatal(err)
80	}
81
82	resp, err := c.GetInstance(context.Background(), request)
83
84	if err != nil {
85		t.Fatal(err)
86	}
87
88	if want, got := request, mockInstanceAdmin.Reqs()[0]; !proto.Equal(want, got) {
89		t.Errorf("wrong request %q, want %q", got, want)
90	}
91
92	if want, got := expectedResponse, resp; !proto.Equal(want, got) {
93		t.Errorf("wrong response %q, want %q)", got, want)
94	}
95}
96