From a10a604018d0cb07babfe218d9fb2e00e1c8ae3b Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Sat, 7 May 2022 13:17:18 -0600 Subject: Refactor how data dir is initialized --- srv/src/post/store.go | 11 ++++++----- srv/src/post/store_test.go | 22 +++++++--------------- 2 files changed, 13 insertions(+), 20 deletions(-) (limited to 'srv/src/post') diff --git a/srv/src/post/store.go b/srv/src/post/store.go index 3f044e2..6bdccc2 100644 --- a/srv/src/post/store.go +++ b/srv/src/post/store.go @@ -9,6 +9,7 @@ import ( "time" _ "github.com/mattn/go-sqlite3" // we need dis + "github.com/mediocregopher/blog.mediocregopher.com/srv/cfg" migrate "github.com/rubenv/sql-migrate" ) @@ -99,9 +100,7 @@ var migrations = []*migrate.Migration{ // Params are parameters used to initialize a new Store. All fields are required // unless otherwise noted. type StoreParams struct { - - // Path to the file the database will be stored at. - DBFilePath string + DataDir cfg.DataDir } type store struct { @@ -113,9 +112,11 @@ type store struct { // path. func NewStore(params StoreParams) (Store, error) { - db, err := sql.Open("sqlite3", params.DBFilePath) + path := path.Join(params.DataDir.Path, "post.sqlite3") + + db, err := sql.Open("sqlite3", path) if err != nil { - return nil, fmt.Errorf("opening sqlite file: %w", err) + return nil, fmt.Errorf("opening sqlite file at %q: %w", path, err) } migrations := &migrate.MemoryMigrationSource{Migrations: migrations} diff --git a/srv/src/post/store_test.go b/srv/src/post/store_test.go index 9b0ee45..1b4fb30 100644 --- a/srv/src/post/store_test.go +++ b/srv/src/post/store_test.go @@ -1,13 +1,12 @@ package post import ( - "io/ioutil" - "os" "sort" "strconv" "testing" "time" + "github.com/mediocregopher/blog.mediocregopher.com/srv/cfg" "github.com/stretchr/testify/assert" "github.com/tilinna/clock" ) @@ -29,25 +28,18 @@ type storeTestHarness struct { func newStoreTestHarness(t *testing.T) storeTestHarness { - clock := clock.NewMock(time.Now().UTC().Truncate(1 * time.Hour)) + var dataDir cfg.DataDir - tmpFile, err := ioutil.TempFile(os.TempDir(), "mediocre-blog-post-store-test-") - if err != nil { - t.Fatal("Cannot create temporary file", err) + if err := dataDir.Init(); err != nil { + t.Fatal(err) } - tmpFilePath := tmpFile.Name() - tmpFile.Close() - t.Logf("using temporary sqlite file at %q", tmpFilePath) + t.Cleanup(func() { dataDir.Close() }) - t.Cleanup(func() { - if err := os.Remove(tmpFilePath); err != nil { - panic(err) - } - }) + clock := clock.NewMock(time.Now().UTC().Truncate(1 * time.Hour)) store, err := NewStore(StoreParams{ - DBFilePath: tmpFilePath, + DataDir: dataDir, }) assert.NoError(t, err) -- cgit v1.2.3