package cli import ( "bytes" "crypto/rand" "log" "os" "path" "strings" "testing" "postern/internal/db" "postern/internal/persistence" "github.com/spf13/cobra" ) // executeCommand helps invoke a cobra command with specific arguments and captures its stdout/stderr. func executeCommand(cmd *cobra.Command, args ...string) (string, error) { buf := new(bytes.Buffer) cmd.SetOut(buf) cmd.SetErr(buf) cmd.SetArgs(args) err := cmd.Execute() return buf.String(), err } // TestAddUserCommand checks the loop of creating a new user, finding it in the db and checking that the password works. func TestAddRemoveUserCommand(t *testing.T) { f := t.TempDir() // create temporary masterkey mkeyPath := path.Join(f, "masterkey") secretKey := make([]byte, 32) _, _ = rand.Read(secretKey) err := os.WriteFile(mkeyPath, secretKey, 0666) if err != nil { t.Fatal(err) } p, err := persistence.New(persistence.Config{ BlobRoot: path.Join(f, "blobs"), MasterkeyFile: mkeyPath, }) if err != nil { log.Fatal(err) } posternDB, err := db.OpenDB(&db.Config{ DBPath: path.Join(f, "meta.db"), }) if err != nil { log.Fatal(err) } c, err := New(&Config{ DB: posternDB, Persistence: p, }) if err != nil { t.Fatal(err) } output, err := executeCommand(c.rootCmd(), "user", "add", "user1") if err != nil { t.Fatalf("expected no error, got: %v", err) } _, after, found := strings.Cut(output, "Password: ") password := strings.TrimSpace(after) if !found { t.Fatal("expected to find a password in output. Found none") } u, err := c.db.GetUser(t.Context(), "user1") if err != nil { t.Fatalf("expected no error, got: %v", err) } err = u.VerifyPassword([]byte(password)) if err != nil { t.Fatalf("password mismatch, got: %v", err) } // Try removing user output, err = executeCommand(c.rootCmd(), "user", "remove", "user1") if err != nil { t.Fatalf("expected no error, got: %v", err) } if !strings.Contains(output, "removed") { t.Fatal("expected to find 'removed' in output. Found none") } // Try removing user again (failure) output, err = executeCommand(c.rootCmd(), "user", "remove", "user1") if err == nil { t.Errorf("expected error when deleting non-existing user, got none") } }