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

101 lines
2 KiB
Go
Raw Normal View History

2020-04-04 17:16:36 +00:00
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
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
2020-04-04 17:16:36 +00:00
"gitlab.com/slon/shad-go/distbuild/pkg/artifact"
2020-03-12 22:33:54 +00:00
"gitlab.com/slon/shad-go/distbuild/pkg/build"
)
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 {
2020-03-12 22:33:54 +00:00
tmpDir, err := ioutil.TempDir("", "")
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)
2020-04-04 17:16:36 +00:00
return &testCache{Cache: cache, tmpDir: tmpDir}
}
func TestCache(t *testing.T) {
c := newTestCache(t)
defer c.cleanup()
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)
defer c.cleanup()
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)
defer c.cleanup()
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)
}