Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

2.2 KB
Raw Blame
// Package fakes3 provides an in-process S3-compatible service for tests.
package fakes3

import (
	"bytes"
	"io"
	"net/http/httptest"
	"testing"

	"github.com/johannesboyne/gofakes3"
	"github.com/johannesboyne/gofakes3/backend/s3mem"

	storepb "github.com/usememos/memos/proto/gen/store"
)

// Server is an in-memory S3-compatible HTTP service.
type Server struct {
	URL string

	memory *s3mem.Backend
}

// New starts an in-process S3 service with the requested buckets.
func New(t testing.TB, buckets ...string) *Server {
	t.Helper()

	memory := s3mem.New()
	for _, bucket := range buckets {
		if err := memory.CreateBucket(bucket); err != nil {
			t.Fatalf("failed to create fake S3 bucket %q: %v", bucket, err)
		}
	}

	httpServer := httptest.NewServer(gofakes3.New(memory).Server())
	t.Cleanup(httpServer.Close)
	return &Server{
		URL:    httpServer.URL,
		memory: memory,
	}
}

// Config returns a storage configuration that connects to the fake service.
func (s *Server) Config(bucket string) *storepb.StorageS3Config {
	return &storepb.StorageS3Config{
		AccessKeyId:     "test-access-key",
		AccessKeySecret: "test-secret-key",
		Endpoint:        s.URL,
		Region:          "us-east-1",
		Bucket:          bucket,
		UsePathStyle:    true,
	}
}

// PutObject writes an object directly into the in-memory store, bypassing
// the HTTP API, for arranging state that predates the code under test.
func (s *Server) PutObject(bucket, key, contentType string, content []byte) error {
	_, err := s.memory.PutObject(bucket, key, map[string]string{"Content-Type": contentType}, bytes.NewReader(content), int64(len(content)), nil)
	return err
}

// GetObject reads an object directly from the in-memory store.
func (s *Server) GetObject(bucket, key string) ([]byte, error) {
	object, err := s.memory.GetObject(bucket, key, nil)
	if err != nil {
		return nil, err
	}
	defer object.Contents.Close()
	return io.ReadAll(object.Contents)
}

// DeleteObject removes an object directly from the in-memory store, bypassing
// the HTTP API, for arranging state where the backend no longer holds an
// attachment's bytes.
func (s *Server) DeleteObject(bucket, key string) error {
	_, err := s.memory.DeleteObject(bucket, key)
	return err
}