github.com/akkaraju-satvik/dbmap@v0.0.3-0.20240414054547-f818701a74f0/cmd/create-migration_test.go (about)

     1  package cmd
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	"github.com/akkaraju-satvik/dbmap/config"
     8  )
     9  
    10  func TestCreateMigration(t *testing.T) {
    11  	tests := []struct {
    12  		name        string
    13  		testID      string
    14  		expectedErr bool
    15  		config      config.Config
    16  	}{
    17  		{
    18  			name:        "Create Migration",
    19  			testID:      "create_migration_success",
    20  			expectedErr: false,
    21  			config: config.Config{
    22  				MigrationsDir: "migrations",
    23  				DbURL:         "",
    24  			},
    25  		},
    26  		{
    27  			name:        "Invalid Config with Empty DB URL Value",
    28  			testID:      "invalid_config_empty_db_url",
    29  			expectedErr: true,
    30  			config: config.Config{
    31  				MigrationsDir: "migrations",
    32  				DbURL:         "",
    33  			},
    34  		},
    35  		{
    36  			name:        "Invalid Config with Empty Migrations Directory Value",
    37  			testID:      "invalid_config_empty_migrations_dir",
    38  			expectedErr: true,
    39  			config: config.Config{
    40  				MigrationsDir: "",
    41  				DbURL:         "",
    42  			},
    43  		},
    44  	}
    45  
    46  	for _, tt := range tests {
    47  		t.Run(tt.name, func(t *testing.T) {
    48  			dir, err := os.MkdirTemp("", "test*")
    49  			if err != nil {
    50  				t.Fatalf("Error creating temp dir\n %s", err)
    51  			}
    52  			defer os.RemoveAll(dir)
    53  			if err = os.Chdir(dir); err != nil {
    54  				t.Fatalf("Error changing directory: %s", err)
    55  			}
    56  			pool, resource, port := createResource()
    57  			defer pool.Purge(resource)
    58  			dbUrl := "postgres://postgres:postgres@localhost:" + port + "/postgres?sslmode=disable"
    59  			err = initializeProject("migrations", dbUrl)
    60  			if err != nil {
    61  				t.Fatalf("Error initializing a test project\n %s", err)
    62  			}
    63  			if tt.testID != "invalid_config_empty_db_url" {
    64  				tt.config.DbURL = dbUrl
    65  			}
    66  			err = createMigration(tt.config)
    67  			if err != nil {
    68  				if !tt.expectedErr {
    69  					t.Fatalf("Error creating migration\n %s", err.Error())
    70  				}
    71  			}
    72  		})
    73  	}
    74  }