|
Packit |
63bb0d |
package jsondb
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
import (
|
|
Packit |
63bb0d |
"errors"
|
|
Packit |
63bb0d |
"io/ioutil"
|
|
Packit |
63bb0d |
"os"
|
|
Packit |
63bb0d |
"path"
|
|
Packit |
63bb0d |
"testing"
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
"github.com/stretchr/testify/require"
|
|
Packit |
63bb0d |
)
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
func TestWriteFileAtomically(t *testing.T) {
|
|
Packit |
63bb0d |
dir, err := ioutil.TempDir("", "jsondb-test-")
|
|
Packit |
63bb0d |
require.NoError(t, err)
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
defer func() {
|
|
Packit |
63bb0d |
err := os.RemoveAll(dir)
|
|
Packit |
63bb0d |
require.NoError(t, err)
|
|
Packit |
63bb0d |
}()
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
t.Run("success", func(t *testing.T) {
|
|
Packit |
63bb0d |
octopus := []byte("🐙\n")
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
// use an uncommon mode to check it's set correctly
|
|
Packit |
63bb0d |
perm := os.FileMode(0750)
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
err = writeFileAtomically(dir, "octopus", perm, func(f *os.File) error {
|
|
Packit |
63bb0d |
_, err := f.Write(octopus)
|
|
Packit |
63bb0d |
return err
|
|
Packit |
63bb0d |
})
|
|
Packit |
63bb0d |
require.NoError(t, err)
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
// ensure that there are no stray temporary files
|
|
Packit |
63bb0d |
infos, err := ioutil.ReadDir(dir)
|
|
Packit |
63bb0d |
require.NoError(t, err)
|
|
Packit |
63bb0d |
require.Equal(t, 1, len(infos))
|
|
Packit |
63bb0d |
require.Equal(t, "octopus", infos[0].Name())
|
|
Packit |
63bb0d |
require.Equal(t, perm, infos[0].Mode())
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
filename := path.Join(dir, "octopus")
|
|
Packit |
63bb0d |
contents, err := ioutil.ReadFile(filename)
|
|
Packit |
63bb0d |
require.NoError(t, err)
|
|
Packit |
63bb0d |
require.Equal(t, octopus, contents)
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
err = os.Remove(filename)
|
|
Packit |
63bb0d |
require.NoError(t, err)
|
|
Packit |
63bb0d |
})
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
t.Run("error", func(t *testing.T) {
|
|
Packit |
63bb0d |
err = writeFileAtomically(dir, "no-octopus", 0750, func(f *os.File) error {
|
|
Packit |
63bb0d |
return errors.New("something went wrong")
|
|
Packit |
63bb0d |
})
|
|
Packit |
63bb0d |
require.Error(t, err)
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
_, err := os.Stat(path.Join(dir, "no-octopus"))
|
|
Packit |
63bb0d |
require.Error(t, err)
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
// ensure there are no stray temporary files
|
|
Packit |
63bb0d |
infos, err := ioutil.ReadDir(dir)
|
|
Packit |
63bb0d |
require.NoError(t, err)
|
|
Packit |
63bb0d |
require.Equal(t, 0, len(infos))
|
|
Packit |
63bb0d |
})
|
|
Packit |
63bb0d |
}
|