Skip to content

Add unit tests for init command #303

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"fmt"

"github.com/spf13/afero"
"github.com/spf13/cobra"
_init "github.com/supabase/cli/internal/init"
"github.com/supabase/cli/internal/utils"
Expand All @@ -12,7 +13,8 @@ var initCmd = &cobra.Command{
Use: "init",
Short: "Initialize a project to use Supabase CLI.",
RunE: func(cmd *cobra.Command, args []string) error {
if err := _init.Run(); err != nil {
fsys := afero.NewOsFs()
if err := _init.Run(fsys); err != nil {
return err
}

Expand Down
9 changes: 8 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ require (
github.com/withfig/autocomplete-tools/packages/cobra v1.1.3
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

require (
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
github.com/Microsoft/go-winio v0.5.2 // indirect
Expand Down Expand Up @@ -60,10 +66,11 @@ require (
github.com/pkg/errors v0.9.1 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/afero v1.8.2
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/testify v1.8.0
github.com/subosito/gotenv v1.2.0 // indirect
github.com/yuin/goldmark v1.4.11 // indirect
github.com/yuin/goldmark-emoji v1.0.1 // indirect
Expand Down
8 changes: 6 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -348,12 +348,15 @@ github.com/spf13/viper v1.10.1/go.mod h1:IGlFPqhNAPKRxohIzWpI5QEy4kuI7tcl5WvR+8q
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/withfig/autocomplete-tools/packages/cobra v1.1.3 h1:toi+jQYY7SG/DRYZxP2U2VkFeCY+6FYLXEr8QR8VXzY=
Expand Down Expand Up @@ -730,7 +733,8 @@ gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk=
gotest.tools/v3 v3.0.3 h1:4AuOwCGf4lLR9u3YOe2awrHygurzhO/HeQ6laiA6Sx0=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
21 changes: 11 additions & 10 deletions internal/init/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"os"

"github.com/spf13/afero"
"github.com/supabase/cli/internal/utils"
)

Expand All @@ -21,33 +22,33 @@ var (
errAlreadyInitialized = errors.New("Project already initialized. Remove " + utils.Bold("supabase") + " to reinitialize.")
)

func Run() error {
if err := run(); errors.Is(err, errAlreadyInitialized) {
func Run(fsys afero.Fs) error {
if err := run(fsys); errors.Is(err, errAlreadyInitialized) {
return err
} else if err != nil {
_ = os.RemoveAll("supabase")
_ = fsys.RemoveAll("supabase")
return err
}

return nil
}

func run() error {
func run(fsys afero.Fs) error {
// Sanity checks.
{
if _, err := os.ReadFile("supabase/config.toml"); err == nil {
if _, err := afero.ReadFile(fsys, "supabase/config.toml"); err == nil {
return errAlreadyInitialized
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
}

if err := utils.MkdirIfNotExist("supabase"); err != nil {
if err := fsys.Mkdir("supabase", 0755); err != nil && !errors.Is(err, os.ErrExist) {
return err
}

// 1. Write `config.toml`.
if err := utils.WriteConfig(false); err != nil {
if err := utils.WriteConfig(fsys, false); err != nil {
return err
}

Expand All @@ -60,17 +61,17 @@ func run() error {
// skip
} else {
gitignorePath := *gitRoot + "/.gitignore"
gitignore, err := os.ReadFile(gitignorePath)
gitignore, err := afero.ReadFile(fsys, gitignorePath)
if errors.Is(err, os.ErrNotExist) {
if err := os.WriteFile(gitignorePath, initGitignore, 0644); err != nil {
if err := afero.WriteFile(fsys, gitignorePath, initGitignore, 0644); err != nil {
return err
}
} else if err != nil {
return err
} else if bytes.Contains(gitignore, initGitignore) {
// skip
} else {
f, err := os.OpenFile(gitignorePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
f, err := fsys.OpenFile(gitignorePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
Expand Down
29 changes: 29 additions & 0 deletions internal/init/init_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package init

import (
"testing"

"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestInitCommand(t *testing.T) {
t.Run("creates config file", func(t *testing.T) {
fsys := &afero.MemMapFs{}
assert.NoError(t, Run(fsys))
// TODO: verify .gitignore
exists, err := afero.Exists(fsys, "supabase/config.toml")
assert.NoError(t, err)
assert.True(t, exists)
})

t.Run("errors when config file exists", func(t *testing.T) {
// Test setup
fsys := &afero.MemMapFs{}
_, err := fsys.Create("supabase/config.toml")
require.NoError(t, err)
// Actual test
assert.Error(t, Run(fsys))
})
}
13 changes: 10 additions & 3 deletions internal/utils/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"text/template"

"github.com/BurntSushi/toml"
"github.com/spf13/afero"
"github.com/spf13/viper"
)

Expand Down Expand Up @@ -125,7 +126,12 @@ type (
)

func LoadConfig() error {
if _, err := toml.DecodeFile("supabase/config.toml", &Config); err == nil {
return loadConfig(afero.NewOsFs())
}

func loadConfig(fsys afero.Fs) error {
// TODO: remove this helper once all sub commands pass in fsys
if _, err := toml.DecodeFS(afero.NewIOFS(fsys), "supabase/config.toml", &Config); err == nil {
// skip
} else if errors.Is(err, os.ErrNotExist) {
_, _err := os.Stat("supabase/config.json")
Expand Down Expand Up @@ -388,7 +394,8 @@ secret = ""
return nil
}

func WriteConfig(test bool) error {
func WriteConfig(fsys afero.Fs, test bool) error {
// Using current directory name as project id
cwd, err := os.Getwd()
if err != nil {
return err
Expand All @@ -410,7 +417,7 @@ func WriteConfig(test bool) error {
return err
}

if err := os.WriteFile("supabase/config.toml", initConfigBuf.Bytes(), 0644); err != nil {
if err := afero.WriteFile(fsys, "supabase/config.toml", initConfigBuf.Bytes(), 0644); err != nil {
return err
}

Expand Down
79 changes: 16 additions & 63 deletions internal/utils/config_test.go
Original file line number Diff line number Diff line change
@@ -1,83 +1,36 @@
package utils

import (
"os"
"testing"

"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
)

func TestConfigParsing(t *testing.T) {
t.Cleanup(func() {
if err := os.Remove("supabase/config.toml"); err != nil {
if !os.IsNotExist(err) {
t.Error(err)
}
}
if err := os.Remove("supabase"); err != nil {
if !os.IsNotExist(err) {
t.Error(err)
}
}
})

if err := os.Mkdir("supabase", 0755); err != nil {
t.Error(err)
t.FailNow()
}

t.Run("classic config file", func(t *testing.T) {
if err := WriteConfig(false); err != nil {
t.Error(err)
t.FailNow()
}
if err := LoadConfig(); err != nil {
t.Error(err)
t.FailNow()
}
fsys := afero.NewMemMapFs()
assert.NoError(t, WriteConfig(fsys, false))
assert.NoError(t, loadConfig(fsys))
})

t.Run("config file with environment variables", func(t *testing.T) {
if err := WriteConfig(true); err != nil {
t.Error(err)
t.FailNow()
}
fsys := afero.NewMemMapFs()
assert.NoError(t, WriteConfig(fsys, true))

t.Setenv("AZURE_CLIENT_ID", "hello")
t.Setenv("AZURE_SECRET", "this is cool")
if err := LoadConfig(); err != nil {
t.Error(err)
t.FailNow()
}
if err := InterpolateEnvInConfig(); err != nil {
t.Error(err)
t.FailNow()
}
t.Setenv("AZURE_CLIENT_ID", "hello")
t.Setenv("AZURE_SECRET", "this is cool")
assert.NoError(t, loadConfig(fsys))
assert.NoError(t, InterpolateEnvInConfig())

if Config.Auth.External["azure"].ClientId != "hello" {
t.Errorf("unexpected value for key [ClientId]: %+v", Config.Auth.External["azure"])
t.FailNow()
}

if Config.Auth.External["azure"].Secret != "this is cool" {
t.Errorf("unexpected value for key [Secret]: %+v", Config.Auth.External["azure"])
t.FailNow()
}
assert.Equal(t, "hello", Config.Auth.External["azure"].ClientId)
assert.Equal(t, "this is cool", Config.Auth.External["azure"].Secret)
})

t.Run("config file with environment variables fails when unset", func(t *testing.T) {
if err := WriteConfig(true); err != nil {
t.Error(err)
t.FailNow()
}

if err := LoadConfig(); err != nil {
t.Error(err)
t.FailNow()
}
if err := InterpolateEnvInConfig(); err == nil {
t.Error("expected to fail")
t.FailNow()
}
fsys := afero.NewMemMapFs()
assert.NoError(t, WriteConfig(fsys, true))
assert.NoError(t, loadConfig(fsys))
assert.Error(t, InterpolateEnvInConfig())
})
}