Skip to content

Commit

Permalink
test(iam): remove reflect hack (#260)
Browse files Browse the repository at this point in the history
Co-authored-by: Hidetake Iwata <[email protected]>
  • Loading branch information
tpokki and int128 authored Jul 22, 2024
1 parent 3e74dbb commit af9efbf
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 32 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,6 @@ Dockerfile.cross
*.swp
*.swo
*~

# macOS
.DS_Store
36 changes: 4 additions & 32 deletions internal/controller/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,9 @@ import (
"context"
"fmt"
"path/filepath"
"reflect"
"runtime"
"testing"
"time"
"unsafe"

"cloud.google.com/go/iam/apiv1/iampb"
"cloud.google.com/go/pubsub"
Expand Down Expand Up @@ -61,15 +59,6 @@ func TestControllers(t *testing.T) {
RunSpecs(t, "Controller Suite")
}

func TestGetInternalGrpcServer(t *testing.T) {
psServer := pstest.NewServer()
gSrv := getInternalGrpcServer(psServer)
sInfo := gSrv.GetServiceInfo()
if sInfo == nil {
t.Error("failed to get grpc server info")
}
}

var _ = BeforeSuite(func() {
logf.SetLogger(zap.New(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true)))

Expand Down Expand Up @@ -114,16 +103,13 @@ var _ = BeforeSuite(func() {
})
Expect(err).ToNot(HaveOccurred())

psServer = pstest.NewServer(
// create new server with additional IAMPolicyServer fake
psServer = pstest.NewServerWithCallback(
0,
func(s *grpc.Server) { iampb.RegisterIAMPolicyServer(s, pubsubtest.CreateFakeIamPolicyServer()) },
pubsubtest.CreateTopicErrorInjectionReactor(),
)

gsrv := getInternalGrpcServer(psServer)

// trying to register fake iam policy server
// this fails randomly because Registering is not possible after `grsv.Serve()` is called.
iampb.RegisterIAMPolicyServer(gsrv, pubsubtest.CreateFakeIamPolicyServer())

DeferCleanup(func() {
Expect(psServer.Close()).Should(Succeed())
})
Expand Down Expand Up @@ -158,17 +144,3 @@ var _ = BeforeSuite(func() {
Expect(err).ToNot(HaveOccurred(), "failed to run manager")
}()
})

// getInternalGrpcServer uses reflection to receive pointer to the internal grpc.Server located in the psutil.Server.
// This reference can be used to register additional fake servers.
func getInternalGrpcServer(psServer *pstest.Server) *grpc.Server {
// try to get access to `Gsrv` thru `*testutil.Server`, that's on first field of `pstest.Server`
rs := reflect.ValueOf(psServer).Elem()

// *testutil.Server
tsrv := rs.Field(0)
tsrv = reflect.NewAt(tsrv.Type(), unsafe.Pointer(tsrv.UnsafeAddr())).Elem()

// *grpc.Server is found from the exported field `Gsrv`
return reflect.Indirect(tsrv).FieldByName("Gsrv").Interface().(*grpc.Server)
}

0 comments on commit af9efbf

Please sign in to comment.