|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "io" |
| 6 | + "net/http" |
| 7 | + "net/http/httptest" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + "runtime" |
| 11 | + "strings" |
| 12 | + "sync/atomic" |
| 13 | + "testing" |
| 14 | + |
| 15 | + "github.com/stretchr/testify/assert" |
| 16 | + "github.com/stretchr/testify/require" |
| 17 | + "github.com/zalando/go-keyring" |
| 18 | + |
| 19 | + "github.com/jjuanrivvera/alegra-cli/internal/config" |
| 20 | +) |
| 21 | + |
| 22 | +// These tests exercise the failure paths the integration suite never hit: the |
| 23 | +// fake servers previously only returned 200/404, so partial batch failures, |
| 24 | +// API errors mid-operation, and persistence failures were all untested. |
| 25 | + |
| 26 | +// failureTestEnv points the CLI at srv with env-only credentials and an |
| 27 | +// isolated config dir, returning that dir. |
| 28 | +func failureTestEnv(t *testing.T, srv *httptest.Server) string { |
| 29 | + t.Helper() |
| 30 | + dir := t.TempDir() |
| 31 | + t.Setenv(config.EnvBaseURL, srv.URL) |
| 32 | + t.Setenv(config.EnvEmail, "e@x.com") |
| 33 | + t.Setenv(config.EnvToken, "tok") |
| 34 | + t.Setenv(config.EnvProfile, "") |
| 35 | + t.Setenv(config.EnvConfig, filepath.Join(dir, "config.yaml")) |
| 36 | + return dir |
| 37 | +} |
| 38 | + |
| 39 | +func TestImport_PartialFailureFailsLoudly(t *testing.T) { |
| 40 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 41 | + w.Header().Set("Content-Type", "application/json") |
| 42 | + body, _ := io.ReadAll(r.Body) |
| 43 | + var m map[string]any |
| 44 | + _ = json.Unmarshal(body, &m) |
| 45 | + if m["name"] == "Bad" { |
| 46 | + w.WriteHeader(http.StatusBadRequest) |
| 47 | + _, _ = w.Write([]byte(`{"message":"name is invalid","code":400}`)) |
| 48 | + return |
| 49 | + } |
| 50 | + _, _ = w.Write([]byte(`{"id":"9","name":"ok"}`)) |
| 51 | + })) |
| 52 | + t.Cleanup(srv.Close) |
| 53 | + dir := failureTestEnv(t, srv) |
| 54 | + |
| 55 | + csvFile := filepath.Join(dir, "rows.csv") |
| 56 | + require.NoError(t, os.WriteFile(csvFile, []byte("name\nGood\nBad\nAlsoGood\n"), 0o600)) |
| 57 | + |
| 58 | + out, err := runRoot(t, "contacts", "import", "-f", csvFile) |
| 59 | + // A partial import must fail the command (exit code), report which row |
| 60 | + // broke, and still account for the rows that were created. |
| 61 | + require.Error(t, err, "partial failure must not look like success to pipelines") |
| 62 | + assert.Contains(t, err.Error(), "1 row(s) failed") |
| 63 | + assert.Contains(t, out, "[row 2] FAILED") |
| 64 | + assert.Contains(t, out, "Imported 2, failed 1") |
| 65 | +} |
| 66 | + |
| 67 | +func TestEmit_BatchAPIErrorFailsAndKeepsCacheClean(t *testing.T) { |
| 68 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 69 | + w.Header().Set("Content-Type", "application/json") |
| 70 | + if strings.HasSuffix(r.URL.Path, "/invoices/stamp") { |
| 71 | + w.WriteHeader(http.StatusBadRequest) // 4xx: not retried, fails fast |
| 72 | + _, _ = w.Write([]byte(`{"message":"EPR001: certificado vencido"}`)) |
| 73 | + return |
| 74 | + } |
| 75 | + _, _ = w.Write([]byte(`{}`)) |
| 76 | + })) |
| 77 | + t.Cleanup(srv.Close) |
| 78 | + dir := failureTestEnv(t, srv) |
| 79 | + |
| 80 | + out, err := runRoot(t, "invoices", "emit", "7", "--force") |
| 81 | + require.Error(t, err) |
| 82 | + assert.Contains(t, err.Error(), "1 batch(es) failed") |
| 83 | + assert.Contains(t, out, "FAILED") |
| 84 | + |
| 85 | + // A failed batch must never be recorded as emitted. |
| 86 | + data, rerr := os.ReadFile(filepath.Join(dir, "emitted.json")) |
| 87 | + if rerr == nil { |
| 88 | + assert.NotContains(t, string(data), ":7", "failed invoice must not be marked emitted") |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +func TestEmit_CacheSaveFailureStopsEmission(t *testing.T) { |
| 93 | + if runtime.GOOS == "windows" { |
| 94 | + t.Skip("read-only directory permissions are not enforced on Windows") |
| 95 | + } |
| 96 | + var stamps int32 |
| 97 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 98 | + w.Header().Set("Content-Type", "application/json") |
| 99 | + if strings.HasSuffix(r.URL.Path, "/invoices/stamp") { |
| 100 | + atomic.AddInt32(&stamps, 1) |
| 101 | + _, _ = w.Write([]byte(`{"stamped":true}`)) |
| 102 | + return |
| 103 | + } |
| 104 | + _, _ = w.Write([]byte(`{}`)) |
| 105 | + })) |
| 106 | + t.Cleanup(srv.Close) |
| 107 | + dir := failureTestEnv(t, srv) |
| 108 | + |
| 109 | + // Make the config dir unwritable so the post-batch cache save fails. |
| 110 | + require.NoError(t, os.Chmod(dir, 0o500)) |
| 111 | + t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) |
| 112 | + |
| 113 | + // 12 ids → 2 batches. The save failure after batch 1 must stop the run |
| 114 | + // before batch 2 is stamped, and the error must name the affected ids. |
| 115 | + ids := []string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"} |
| 116 | + out, err := runRoot(t, append([]string{"invoices", "emit", "--force"}, ids...)...) |
| 117 | + require.Error(t, err) |
| 118 | + assert.Contains(t, err.Error(), "could not record them in the idempotency cache") |
| 119 | + assert.Contains(t, err.Error(), "1") // affected ids are listed |
| 120 | + assert.Contains(t, out, "stamped") |
| 121 | + assert.Equal(t, int32(1), atomic.LoadInt32(&stamps), "must stop stamping once the guard cannot record progress") |
| 122 | +} |
| 123 | + |
| 124 | +func TestDelete_AbortsWithoutConfirmation(t *testing.T) { |
| 125 | + var deletes int32 |
| 126 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 127 | + w.Header().Set("Content-Type", "application/json") |
| 128 | + if r.Method == http.MethodDelete { |
| 129 | + atomic.AddInt32(&deletes, 1) |
| 130 | + } |
| 131 | + _, _ = w.Write([]byte(`{}`)) |
| 132 | + })) |
| 133 | + t.Cleanup(srv.Close) |
| 134 | + failureTestEnv(t, srv) |
| 135 | + |
| 136 | + // Piped/empty stdin without --yes: the prompt cannot be answered, so the |
| 137 | + // delete must abort — and the DELETE request must never be sent. |
| 138 | + rootCmd.SetIn(strings.NewReader("")) |
| 139 | + t.Cleanup(func() { rootCmd.SetIn(nil) }) |
| 140 | + |
| 141 | + _, err := runRoot(t, "contacts", "delete", "1") |
| 142 | + require.Error(t, err) |
| 143 | + assert.Contains(t, err.Error(), "aborted") |
| 144 | + assert.Zero(t, atomic.LoadInt32(&deletes), "no DELETE may be sent without confirmation") |
| 145 | +} |
| 146 | + |
| 147 | +func TestAuthLogin_NeverPersistsTokenToConfig(t *testing.T) { |
| 148 | + keyring.MockInit() |
| 149 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 150 | + w.Header().Set("Content-Type", "application/json") |
| 151 | + _, _ = w.Write([]byte(`{"name":"Tester","applicationVersion":"colombia"}`)) |
| 152 | + })) |
| 153 | + t.Cleanup(srv.Close) |
| 154 | + dir := failureTestEnv(t, srv) |
| 155 | + t.Setenv(config.EnvToken, "") // force login to use the flag token |
| 156 | + |
| 157 | + const secret = "super-secret-token" |
| 158 | + _, err := runRoot(t, "auth", "login", "--email", "a@x.com", "--token", secret, "--profile", "p1") |
| 159 | + require.NoError(t, err) |
| 160 | + |
| 161 | + // The token belongs in the keyring only; the YAML must never contain it. |
| 162 | + data, rerr := os.ReadFile(filepath.Join(dir, "config.yaml")) |
| 163 | + require.NoError(t, rerr) |
| 164 | + assert.NotContains(t, string(data), secret, "plaintext token leaked into config.yaml") |
| 165 | +} |
0 commit comments