github.com/supabase/cli@v1.168.1/internal/migration/new/new_test.go (about) 1 package new 2 3 import ( 4 "os" 5 "path/filepath" 6 "testing" 7 8 "github.com/spf13/afero" 9 "github.com/stretchr/testify/assert" 10 "github.com/stretchr/testify/require" 11 "github.com/supabase/cli/internal/utils" 12 ) 13 14 func TestNewCommand(t *testing.T) { 15 t.Run("creates new migration file", func(t *testing.T) { 16 // Setup in-memory fs 17 fsys := afero.NewMemMapFs() 18 // Setup empty stdin 19 stdin, err := fsys.Create("/dev/stdin") 20 require.NoError(t, err) 21 // Run test 22 assert.NoError(t, Run("test_migrate", stdin, fsys)) 23 // Validate output 24 files, err := afero.ReadDir(fsys, utils.MigrationsDir) 25 assert.NoError(t, err) 26 assert.Equal(t, 1, len(files)) 27 assert.Regexp(t, `([0-9]{14})_test_migrate\.sql`, files[0].Name()) 28 }) 29 30 t.Run("streams content from pipe", func(t *testing.T) { 31 // Setup in-memory fs 32 fsys := afero.NewMemMapFs() 33 // Setup stdin 34 r, w, err := os.Pipe() 35 require.NoError(t, err) 36 script := "create table pet;\ndrop table pet;\n" 37 _, err = w.WriteString(script) 38 require.NoError(t, err) 39 require.NoError(t, w.Close()) 40 // Run test 41 assert.NoError(t, Run("test_migrate", r, fsys)) 42 // Validate output 43 files, err := afero.ReadDir(fsys, utils.MigrationsDir) 44 assert.NoError(t, err) 45 assert.Equal(t, 1, len(files)) 46 path := filepath.Join(utils.MigrationsDir, files[0].Name()) 47 contents, err := afero.ReadFile(fsys, path) 48 assert.NoError(t, err) 49 assert.Equal(t, []byte(script), contents) 50 }) 51 52 t.Run("throws error on failure to create directory", func(t *testing.T) { 53 // Setup read-only fs 54 fsys := afero.NewMemMapFs() 55 // Setup empty stdin 56 stdin, err := fsys.Create("/dev/stdin") 57 require.NoError(t, err) 58 // Run test 59 assert.Error(t, Run("test_migrate", stdin, afero.NewReadOnlyFs(fsys))) 60 }) 61 62 t.Run("throws error on closed pipe", func(t *testing.T) { 63 // Setup read-only fs 64 fsys := afero.NewMemMapFs() 65 // Setup empty stdin 66 r, _, err := os.Pipe() 67 require.NoError(t, err) 68 require.NoError(t, r.Close()) 69 // Run test 70 assert.Error(t, Run("test_migrate", r, fsys)) 71 }) 72 }