Skip to content

Commit

Permalink
✅ (pkg/gcs) test for IssueDownloadSignedURL
Browse files Browse the repository at this point in the history
  • Loading branch information
Shion1305 committed May 26, 2024
1 parent cd68a99 commit 3bdc8b6
Showing 1 changed file with 102 additions and 0 deletions.
102 changes: 102 additions & 0 deletions pkg/gcs/object_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package gcs

import (
"cloud.google.com/go/storage"
"context"
"fmt"
"google.golang.org/api/option"
"io"
"net/http"
"net/url"
"testing"
"time"
"ynufes-mypage-backend/pkg/setting"
)

func TestObjectRef_IssueDownloadSignedURL(t *testing.T) {
ctx := context.Background()
conf := setting.Get()
certPath := conf.Infrastructure.Firebase.JsonCredentialFile
c, err := storage.NewClient(ctx, option.WithCredentialsFile(certPath))
if err != nil {
t.Fatal(err)
}
b := c.Bucket("ynufes-mypage-staging-bucket")
ref := NewFolderRef(b, "some-folder")
uploadRef, err := ref.Upload(ctx, "some-file", []byte("some-content"))
if err != nil {
t.Fatal(err)
return
}
issueOpt := IssueLinkOptions{
ExpiresIn: 5 * time.Second,
AuthHeaders: map[string]string{
"user": "shion-test",
},
AuthMetaHeaders: map[string]string{
"user": "shion-meta",
},
AuthQueries: map[string]string{
"user-query": "shion-query",
},
}
targetUrl, err := uploadRef.IssueDownloadSignedURL(issueOpt, true)
if err != nil {
t.Fatal(err)
}
if err := verifySignedURL(targetUrl, issueOpt, true); err != nil {
t.Fatal(err)
}
}

//func uploadTestFile(
// ctx context.Context,
// bucket *storage.BucketHandle,
// fileName string,
// content []byte,
//) (ObjectRef, error) {
// ref := NewFolderRef(bucket, "some-folder")
// return ref.Upload(ctx, fileName, content)
//}

func verifySignedURL(
target SignedObjectLink,
opt IssueLinkOptions,
addQuery bool,
) error {
targetURL, err := url.Parse(string(target))
if err != nil {
return fmt.Errorf("failed to parse signed URL: %w", err)
}
if addQuery {
q := targetURL.Query()
for k, v := range opt.AuthQueries {
q.Set(k, v)
}
targetURL.RawQuery = q.Encode()
}
fmt.Println("targetURL: ", targetURL.String())
req, err := http.NewRequest("GET", targetURL.String(), nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
for k, v := range opt.AuthHeaders {
req.Header.Set(k, v)
}
for k, v := range opt.AuthMetaHeaders {
req.Header.Set("x-goog-meta-"+k, v)
}
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
payload, _ := io.ReadAll(resp.Body)
if string(payload) != "some-content" {
return fmt.Errorf("unexpected payload: %s", string(payload))
}
return nil
}

0 comments on commit 3bdc8b6

Please sign in to comment.