profile_list_test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "testing"
  9. )
  10. type profileListOutput struct {
  11. Profiles []string `json:"profiles"`
  12. }
  13. func withProfilesDir(t *testing.T, names ...string) {
  14. t.Helper()
  15. dir := t.TempDir()
  16. for _, n := range names {
  17. body := `{"name":"` + n + `","zones":[]}`
  18. if err := os.WriteFile(filepath.Join(dir, n+".json"), []byte(body), 0644); err != nil {
  19. t.Fatalf("write profile %s: %v", n, err)
  20. }
  21. }
  22. orig := profilesDir
  23. profilesDir = dir
  24. t.Cleanup(func() { profilesDir = orig })
  25. }
  26. func runProfileList(t *testing.T) string {
  27. t.Helper()
  28. var out bytes.Buffer
  29. cmd := NewProfileListCmd()
  30. cmd.SetOut(&out)
  31. cmd.SetErr(&out)
  32. if err := cmd.Execute(); err != nil {
  33. t.Fatalf("list returned error: %v", err)
  34. }
  35. return out.String()
  36. }
  37. // README.md advertises JSON for `list`. The shape must not change with the
  38. // number of profiles on disk.
  39. func TestProfileListEmitsJSONWithProfiles(t *testing.T) {
  40. withJSON(t)
  41. withProfilesDir(t, "desk", "movie")
  42. got := runProfileList(t)
  43. var parsed profileListOutput
  44. if err := json.Unmarshal([]byte(got), &parsed); err != nil {
  45. t.Fatalf("list output is not valid JSON: %v (output %q)", err, got)
  46. }
  47. if len(parsed.Profiles) != 2 {
  48. t.Errorf("profiles = %v, want 2 entries", parsed.Profiles)
  49. }
  50. }
  51. func TestProfileListEmitsJSONWithoutProfiles(t *testing.T) {
  52. withJSON(t)
  53. withProfilesDir(t)
  54. got := runProfileList(t)
  55. var parsed profileListOutput
  56. if err := json.Unmarshal([]byte(got), &parsed); err != nil {
  57. t.Fatalf("list output is not valid JSON: %v (output %q)", err, got)
  58. }
  59. if parsed.Profiles == nil {
  60. t.Error("profiles = null, want an empty array so consumers can iterate unconditionally")
  61. }
  62. }
  63. func TestProfileListUsesTheSharedJSONShape(t *testing.T) {
  64. withJSON(t)
  65. withProfilesDir(t, "desk")
  66. got := runProfileList(t)
  67. if !strings.Contains(got, "\n \"profiles\": [") {
  68. t.Errorf("list output = %q, want the same two-space indent as the other JSON commands", got)
  69. }
  70. }