I’m having a query about the way to implement interfaces accurately in Go in the case of third-party packages that use chained strategies. I’ve compiled an instance challenge under for you to be able to perceive the issue.
bundle most important
import (
myAPI "github.com/hashicorp/vault/api"
)
var myClient *myAPI.Consumer
kind MyProvider interface {
GetClient() MyAPIClient
}
kind MyAPIClient interface {
// I need to do that however it doesn't work
Logical() MyAPILogical
// This works although
// Logical() *myAPI.Logical
}
kind MyAPILogical interface {
Write(path string, knowledge map[string]interface{}) (*myAPI.Secret, error)
}
kind Supplier struct {}
func PublicFunctionIWantToTest(supplier MyProvider) {
shopper := supplier.GetClient()
// We usually do one thing right here with the 'shopper' variable, however vital
// is that we ahead it afterward
privateFunctionThatIsUsedInTheTest(shopper)
}
func privateFunctionThatIsUsedInTheTest(shopper MyAPIClient) (*myAPI.Secret, error) {
return shopper.Logical().Write(
"/right here/goes/some/path",
map[string]interface{}{
"key": "worth",
},
)
}
func NewProvider() MyProvider {
return Supplier{}
}
func (p Supplier) GetClient() MyAPIClient {
return myClient
}
// Empty operate simply in order that this instance could be constructed
func most important() {}
As you may see, the bundle has a chained methodology Logical().Write()
. Since I need to create exams for PublicFunctionIWantToTest
, I need to move down all of the performance as interface in order that I can use mockery to create mocks for it.
Sadly, I’m hitting a difficulty with my MyAPIClient
and the MyAPILogical
interface. Since I can see within the bundle’s documentation (api bundle – github.com/hashicorp/vault/api – Go Packages) that the Logical()
methodology returns a Logical
occasion, I need to make it in order that interface methodology returns the opposite interface MyAPILogical
(line 15). This doesn’t work although, there may be an error on line 47 within the GetClient()
methodology saying that I might not implement the interface accurately. How may I try this?
can't use myClient (variable of kind *api.Consumer) as MyAPIClient worth in return assertion: *api.Consumer doesn't implement MyAPIClient (flawed kind for methodology Logical)
have Logical() *api.Logical
need Logical()
Thanks kindly
I’m not aware of that bundle and I don’t but see the “massive image” of what you’re attempting to do, however you’re getting that error as a result of, such as you mentioned, (*api.Consumer).Logical
returns *api.Logical
, not MyAPILogical
, and regardless that the interface is applied by *api.Logical
, the MyAPIClient
interface should be matched precisely.
One workaround might be to wrap the *api.Consumer
kind right into a struct and implement your Logical
operate via that:
kind myAPIClient struct{ *myAPI.Consumer }
func (c myAPIClient) Logical() MyAPILogical {
return c.Consumer.Logical()
}
var myClient myAPIClient