package console_test import ( "bytes" "context" "errors" "os" "path/filepath" "strings" "testing" "git.golem15.com/golem15/summercms/modules/bonfire" "git.golem15.com/jakub/sm-bm-plugin/console" "gorm.io/gorm" ) func TestSeedCommandShape(t *testing.T) { cmd := console.SeedCommand(nil) if cmd.Name != "bm:seed" || cmd.Description == "" { t.Errorf("command = %q %q", cmd.Name, cmd.Description) } if len(cmd.Args) != 1 || cmd.Args[0].Name != "file" || !cmd.Args[0].Required { t.Errorf("Args = %+v, want one required file argument", cmd.Args) } } func TestSeedCommandChecksTheFileBeforeTheDatabase(t *testing.T) { called := false withDB := func(ctx context.Context, fn func(*gorm.DB) error) error { called = true return errors.New("no database in this test") } cmds := []bonfire.Command{console.SeedCommand(withDB)} dir := t.TempDir() invalid := filepath.Join(dir, "invalid.json") if err := os.WriteFile(invalid, []byte(`{"readings": [{"course": "ghost", "title": "X"}]}`), 0o644); err != nil { t.Fatal(err) } broken := filepath.Join(dir, "broken.json") if err := os.WriteFile(broken, []byte(`{"courses": [`), 0o644); err != nil { t.Fatal(err) } var out bytes.Buffer for _, args := range [][]string{nil, {filepath.Join(dir, "missing.json")}, {broken}, {invalid}} { if err := bonfire.Call(context.Background(), cmds, "bm:seed", args, &out); err == nil { t.Errorf("bm:seed %v succeeded", args) } } err := bonfire.Call(context.Background(), cmds, "bm:seed", []string{invalid}, &out) if err == nil || !strings.Contains(err.Error(), "nothing was written") || !strings.Contains(err.Error(), "ghost") { t.Errorf("invalid file error = %v", err) } if called { t.Error("bm:seed reached the database with an invalid file") } out.Reset() err = bonfire.Call(context.Background(), cmds, "bm:seed", []string{"../testdata/seed.example.json", "--dry-run", "--prune"}, &out) if !called || err == nil || !strings.Contains(out.String(), "3 courses") { t.Errorf("dry run called=%v err=%v output %q, want the validation line and the withDB error", called, err, out.String()) } called = false err = bonfire.Call(context.Background(), cmds, "bm:seed", []string{"../testdata/seed.example.json"}, &out) if !called || err == nil { t.Errorf("valid file: called=%v err=%v, want the withDB error", called, err) } }