简体   繁体   中英

Unable to create an interface to mock Google Cloud Storage

I'm trying to create an interface to abstract the google cloud storage.

I have the following interfaces:

type Client interface {
    Bucket(name string) *BucketHandle
    Close() error
}

type BucketHandle interface {
    Create(context.Context, string, *storage.BucketAttrs) error
    Delete(context.Context) error
    Attrs(context.Context) (*storage.BucketAttrs, error)
}

And the my code

type Bucket struct {
    handler Client
}

func NewStorage(ctx context.Context, bucketName string) Bucket {
    var bkt Bucket
    client, err := storage.NewClient(ctx)
    if err != nil {
        return Bucket{}
    }

    bkt.handler = client
    return bkt
}

I get the following error: cannot use client (variable of type *storage.Client) as Client value in assignment: wrong type for method Bucket

And goland shows the following

Cannot use 'client' (type *Client) as type Client Type does not implement 'Client' need method: Bucket(name string) *BucketHandle have method: Bucket(name string) *BucketHandle 

I'm lost on why the types aren't the same.

Cannot use 'client' (type *Client) as type Client Type does not implement 'Client' need method: Bucket(name string) *BucketHandle have method: Bucket(name string) *BucketHandle

There is nothing wrong with this error. The reason it seems misleading is because you have created an interface with the exact same name as a concrete struct in the library ie, BucketHandle

Notice closely the difference between the return types in the two functions:

// In your interface, the return type is an interface that you created
Bucket(name string) *BucketHandle

// In the library, the return type is a concrete struct that exists in that lib
Bucket(name string) *BucketHandle

You will need to modify the Client interface to the following and it should work fine.

type Client interface {
    Bucket(name string) *storage.BucketHandle
    Close() error
}

storage.NewClient(ctx) return *storage.Client. whereas you are trying to assign to Client, your Client should implement the methods which storage.Client implements

Client interface should be

type Client interface {
    Close() error
    ServiceAccount(ctx context.Context, projectID string) (string, error)
}

and bucket can be

type Bucket struct {
    handler Client
}

check here https://github.com/googleapis/google-cloud-go/blob/master/storage/storage.go#L101

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM