mardi 27 août 2019

How do I run a unit test for this function that uses the GCS sdk?

I am listing items in my bucket on Google cloud storage. Within the function there is some logic that needs to be tested...trimming directory names and some other things I'd like to make sure that THIS function works. I don't like writing separate functions that are used just for testing. If I were to call the API directly I could easily mock this function with something like httpmock. How do I do it with the sdk?

package gcs

import(
    "cloud.google.com/go/storage"
    "context"
    "google.golang.org/api/iterator"
    "google.golang.org/api/option"
    "strings"
)

// GCS something
type GCS struct{
    client *storage.Client
}

// NewGCSClient something
func NewGCSClient() (*GCS, error){
     c, err := storage.NewClient(context.Background(), option.WithCredentialsFile("..."))
    if err != nil {
        return nil, err
    }

    return &GCS{
        c,
    }, nil
}

// ListItems something
func (g *GCS) ListItems() (entries []string, err error){
    dirPath := "names/"

    q := &storage.Query{
        Prefix: dirPath,
    }

    it := g.client.Bucket("mybucket").Objects(context.Background(), q)
    for {
        attrs, err := it.Next()
        if err == iterator.Done {
            break
        }
        if err != nil {
            return entries, err
        }

        name := strings.TrimPrefix(attrs.Name, dirPath)
        child := strings.SplitAfter(name, "/")[0]
        entries = append(entries, child)
    }

    return entries, err
}

Aucun commentaire:

Enregistrer un commentaire