Using an interface in golang to ridicule third-party libraries

I am trying to create a simple layout for unit testing some code using the VMware vSphere API client - govmomi - m, unable to find a useful model.

A simple use case for the client library would be to obtain installed licenses for the vSphere cluster:

vclient, err := govmomi.NewClient(*vcurl, true) if err != nil { return err } lic, err := vclient.LicenseManager().ListLicenses() 

NewClient() returns a pointer to the client structure, Client.LicenseManager() returns an instance of the LicenseManager structure, and LicenseManager.ListLicenses() returns a fragment of structures containing license information. Based on the Python background, I usually beheaded the ListLicenses() method on the LicenseManger for the layout, but I can't find a comparable template or methodology in Go.

At this point, I tried to create a VCenterClient wrapper VCenterClient with the govmomi Client structure as an anonymous element and the NewVCenter() constructor NewVCenter() to create new instances of the wrapper structure with logic for mocks

 import ( "net/url" "github.com/vmware/govmomi" "github.com/vmware/govmomi/vim25/types" ) type VCenterClient struct { VCenterClientInterface } type VCenterClientInterface interface { LicenseManager() LicenseManager } type LicenseManager interface { ListLicenses() ([]types.LicenseManagerLicenseInfo, error) } type VCenterClientMock struct{} type LicenseManagerMock struct{} func (v *VCenterClientMock) LicenseManager() LicenseManager { return LicenseManagerMock{} } func (l LicenseManagerMock) ListLicenses() ([]types.LicenseManagerLicenseInfo, error) { return make([]types.LicenseManagerLicenseInfo, 0), nil } func NewVCenterClient(uri string, mock bool) *VCenterClient { if mock { return &VCenterClient{&VCenterClientMock{}} } vcurl, _ := url.Parse(uri) vclient, _ := govmomi.NewClient(*vcurl, true) return &VCenterClient{vclient} } 

... but I am having problems using interfaces to properly abstract the nested structures in the govmomi library. I know that the above will not work, since govmomi.LicenseManager() returns a structure of type govmomi.LicenseManager , and the VCenterClientInterface.LicenseManager() method returns an interface of type LicenseManager . However, I am struggling to find an alternative.

Any help on a better design pattern or proper use of interfaces in this case would be greatly appreciated.

+5
source share
1 answer

This library is a SOAP client ( http://godoc.org/github.com/vmware/govmomi/vim25/soap#Client ). Annotation at the HTTP level with net / http / httptest ( http://golang.org/pkg/net/http/httptest/ ) or using your own HTTPRoundtripper to mock the answer.

+2
source

Source: https://habr.com/ru/post/1212994/


All Articles