shad-go/distbuild/pkg/artifact/cache_test.go

99 lines
1.9 KiB
Go
Raw Normal View History

package artifact_test
2020-03-12 22:33:54 +00:00
import (
2020-04-04 17:16:36 +00:00
"errors"
2020-03-12 22:33:54 +00:00
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"gitlab.com/slon/shad-go/distbuild/pkg/artifact"
"gitlab.com/slon/shad-go/distbuild/pkg/build"
2020-03-12 22:33:54 +00:00
)
2020-04-04 17:16:36 +00:00
type testCache struct {
*artifact.Cache
tmpDir string
}
2020-04-04 21:55:07 +00:00
func (c *testCache) cleanup() {
_ = os.RemoveAll(c.tmpDir)
2020-04-04 17:16:36 +00:00
}
func newTestCache(t *testing.T) *testCache {
tmpDir, err := os.MkdirTemp("", "")
2020-03-12 22:33:54 +00:00
require.NoError(t, err)
2020-04-04 17:16:36 +00:00
cache, err := artifact.NewCache(tmpDir)
if err != nil {
_ = os.RemoveAll(tmpDir)
}
2020-03-12 22:33:54 +00:00
require.NoError(t, err)
c := &testCache{Cache: cache, tmpDir: tmpDir}
t.Cleanup(c.cleanup)
return c
2020-04-04 17:16:36 +00:00
}
func TestCache(t *testing.T) {
c := newTestCache(t)
2020-03-12 22:33:54 +00:00
idA := build.ID{'a'}
path, commit, _, err := c.Create(idA)
require.NoError(t, err)
_, _, _, err = c.Create(idA)
2020-04-04 17:16:36 +00:00
require.Truef(t, errors.Is(err, artifact.ErrWriteLocked), "%v", err)
2020-03-12 22:33:54 +00:00
_, err = os.Create(filepath.Join(path, "a.txt"))
require.NoError(t, err)
require.NoError(t, commit())
path, unlock, err := c.Get(idA)
require.NoError(t, err)
defer unlock()
_, err = os.Stat(filepath.Join(path, "a.txt"))
require.NoError(t, err)
2020-04-04 17:16:36 +00:00
require.Truef(t, errors.Is(c.Remove(idA), artifact.ErrReadLocked), "%v", err)
2020-03-12 22:33:54 +00:00
idB := build.ID{'b'}
_, _, err = c.Get(idB)
2020-04-04 17:16:36 +00:00
require.Truef(t, errors.Is(err, artifact.ErrNotFound), "%v", err)
2020-03-12 22:33:54 +00:00
require.NoError(t, c.Range(func(artifact build.ID) error {
require.Equal(t, idA, artifact)
return nil
}))
}
func TestAbortWrite(t *testing.T) {
2020-04-04 17:16:36 +00:00
c := newTestCache(t)
2020-03-12 22:33:54 +00:00
idA := build.ID{'a'}
_, _, abort, err := c.Create(idA)
require.NoError(t, err)
require.NoError(t, abort())
_, _, err = c.Get(idA)
2020-04-04 17:16:36 +00:00
require.Truef(t, errors.Is(err, artifact.ErrNotFound), "%v", err)
2020-03-12 22:33:54 +00:00
}
2020-04-04 18:45:29 +00:00
func TestArtifactExists(t *testing.T) {
c := newTestCache(t)
idA := build.ID{'a'}
_, commit, _, err := c.Create(idA)
require.NoError(t, err)
require.NoError(t, commit())
_, _, _, err = c.Create(idA)
require.Truef(t, errors.Is(err, artifact.ErrExists), "%v", err)
}