Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: addressed tech doc review changes

=80023af1ec8c
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.md
index 1bc0cddd50..eba91fac6b 100644
--- a/tests/CLAUDE.md
+++ b/tests/CLAUDE.md
@@ -64,7 +64,8 @@ stale one is adopted and your change does not take effect.
suites/ product behaviour: does Infisical do the right thing
harnesstest/ harness behaviour: does our tooling do the right thing
harness/ Stack, Profile, Tenant, Principal
-fixture/ resource builders shared by more than one suite
+fixture/ platform resources: projects, app connections (one package, a file each)
+fixture/<product>/ one package per product: secretmanager, pki, pam (a file per resource)
fakes/ one package per faked third party
provider/ what creating an app connection needs, per service
internal/ wait, mail, id, apierr, spec
@@ -82,9 +83,16 @@ Within `suites/`, group by product boundary, not URL version:
and v2; `secrets` owns v4 and the v3 deprecations. That is what makes the grouping
survive a version bump.
-**Helpers start local and move on the second caller.** An unexported function at the
-bottom of the test file is the right home until a second package needs it; then it
-becomes a `fixture/`. Do not create a package for one caller.
+**Fixtures are one package, split by file; products get their own package.**
+Platform resources live in `fixture` (`fixture.NewProject`, `fixture.NewAppConnection`).
+A product's resources live in `fixture/<product>` (`secretmanager.CreateSecret`). Add a
+file to the right package rather than a new package per resource. Since many resources
+share one package, names carry the resource: `NewProject`, `WithProjectType`,
+`AppConnectionOption`.
+
+**Helpers start local and move on the second caller.** An unexported function in the
+test package is the right home until a second package needs it; then it moves into the
+matching fixture package.
**Import direction is one-way.** `fixture/*` may import `harness`; `harness` must never
import a fixture. `fakes/*` import neither.
@@ -103,24 +111,55 @@ func TestSecret_Create(t *testing.T) {
t.Parallel()
h := harness.From(t)
- t.Run("ok/a created secret reads back with its value", func(t *testing.T) {
+ t.Run("should read back a created secret with its value", func(t *testing.T) {
t.Parallel()
- tn := h.NewTenant(t)
- proj := project.New(t, tn, project.WithType("secret-manager"))
+ // Setup
+ proj := fixture.NewProject(t, h.NewTenant(t), fixture.WithProjectType("secret-manager"))
- secret.Create(t, proj, "dev", "DB_URL", "postgres://localhost/app")
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "DB_URL", "postgres://localhost/app")
- if got := secret.Get(t, proj, "dev", "DB_URL"); got.Value != "postgres://localhost/app" {
- t.Errorf("secret read back as %q, want postgres://localhost/app", got.Value)
- }
+ // Assert
+ got := secretmanager.GetSecret(t, proj, "dev", "DB_URL")
+ require.Equal(t, "postgres://localhost/app", got.Value)
})
}
```
-> Arrange in under about eight lines. Act in one call. Assert one to three claims.
+### Setup, Action, Assert
+
+Every test body is three blocks marked with exactly these comments:
+
+```go
+// Setup
+// Action
+// Assert
+```
+
+Setup in under about eight lines, the Action as one call, Assert one to three claims.
+If Setup is longer, the missing helper belongs beside the test or in a fixture. Where
+the action and the assertion are one call (`ExpectEvent`), write `// Action + Assert`.
+
+These are the one place section-marker comments are allowed. The repository rule
+against them applies to production code; in tests they are the convention.
+
+### Assertions use `require`
+
+All assertions go through `github.com/stretchr/testify/require`, never `t.Error`,
+`t.Fatal` or hand-written comparisons. `require` stops the test at the first failure,
+which is what you want when later lines depend on earlier ones, and it prints both
+values without a format string.
-If arrange is longer, the missing helper belongs beside the test or in a fixture.
+Add a message only when the values alone don't explain the failure:
+
+```go
+require.Equal(t, "first", got.Value, "the refused create still changed the value")
+```
+
+Never call `require` from a goroutine other than the test's own: it calls
+`t.FailNow`, which only works on the test goroutine. Collect results on a channel and
+assert after.
### Profiles
@@ -153,30 +192,29 @@ Choosing the org as the boundary is what makes `t.Parallel()` the default.
Test function: `Test<Resource>_<Behaviour>`.
-Subtest: `<outcome>/<what happened, in words>`. The prefix is not decoration; it is what
-makes a run readable and what a lint can check.
-
-| prefix | meaning |
-|---|---|
-| `ok/` | the happy path |
-| `invalid/` | the request was malformed or referenced something that does not exist |
-| `unauth/` | no credential, or an auth mode the route does not accept |
-| `forbidden/` | authenticated but not allowed |
-| `cross-tenant/` | another tenant's data was not reachable |
-| `notfound/` | the target does not exist |
-| `conflict/` | the request collided with existing state |
-| `unlicensed/` | the plan does not include the feature |
-| `idempotent/` | doing it twice is the same as doing it once |
+Subtest: `should <outcome> [when <condition>]`, lowercase prose, no prefix.
+
+```go
+t.Run("should prune the destination when a synced secret is deleted", ...)
+t.Run("should refuse a write when the project belongs to another tenant", ...)
+t.Run("should read back a created secret with its value", ...)
+```
+
+The outcome comes first so a failure list reads as the broken claims. Add `when` only
+when there is a condition; the default case needs none.
**A subtest name is a claim, not a label.**
```
-ok/the same key in a different environment is a different secret yes
-ok/create secret in prod env no
-conflict/the same key twice at the same path yes
-conflict/duplicate no
+should hold a separate value per environment when one name is created in two yes
+should create secret in prod env no
+should refuse and keep the original when the same name is created twice yes
+should handle duplicates no
```
+Cover the failure outcomes, not only the happy path: refused, forbidden, another
+tenant's resource, not found, conflicting, unlicensed, repeated.
+
**The subject is the operation whose behaviour is being claimed.** Operations used to
set up or observe are not subjects, so "the same key in two environments" is a subtest
of `TestSecret_Create` even though a read is how you see it. Something earns its own
@@ -242,22 +280,22 @@ h.InstanceAdmin(t) // super admin; refused outside Isolated
Fixtures take the resource they belong to:
```go
-proj := project.New(t, tn, project.WithType("secret-manager"))
-proj.NewUser(t, project.Name("bob"), project.Role("admin"))
+proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+proj.NewUser(t, fixture.WithPrincipalName("bob"), fixture.WithRoles("admin"))
proj.Grant(t, principal, "developer")
-secret.Create(t, proj, "dev", "DB_URL", "value", secret.Path("/svc"), secret.As(member))
-secret.Get(t, proj, "dev", "DB_URL")
-secret.Delete(t, proj, "dev", "DB_URL")
+secretmanager.CreateSecret(t, proj, "dev", "DB_URL", "value",
+ secretmanager.WithPath("/svc"), secretmanager.As(member))
+secretmanager.GetSecret(t, proj, "dev", "DB_URL")
+secretmanager.DeleteSecret(t, proj, "dev", "DB_URL")
-conn := appconnection.New(t, tn, provider.GitHub)
+conn := fixture.NewAppConnection(t, tn, provider.GitHub)
```
**Fixtures take required arguments positionally and everything else as options.** What
-the API refuses without is positional; what the schema marks optional is an `Option`.
+the API refuses without is positional; what the schema marks optional is an option.
That is what lets someone add metadata or a different actor without touching every call
-site. Do not add an option nothing uses yet: `staticcheck` will tell you, and adding one
-later is a single line.
+site. Do not add an option nothing uses yet; adding one later is a single line.
**Never build your own API client.** Use `tn.Admin.API`, a principal's `.API`, or
`tn.Client(t, token)`. A hand-built client loses the tenant's `X-Forwarded-For` address
@@ -265,7 +303,7 @@ and starts drawing down a rate-limit bucket shared with every other test, so the
is a 429 in an unrelated package.
Organization roles and project roles are separate types on purpose:
-`harness.OrgRole("admin")` and `project.Role("viewer")`. Passing one where the other
+`harness.OrgRole("admin")` and `fixture.WithRoles("viewer")`. Passing one where the other
belongs does not compile.
## 8. Third parties are faked, not stubbed
@@ -277,7 +315,7 @@ A fake is a working implementation holding real state, so you assert on what the
destination ended up holding rather than on which requests were sent:
```go
-conn := appconnection.New(t, tn, provider.GitHub)
+conn := fixture.NewAppConnection(t, tn, provider.GitHub)
gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())
gh.Seed(t, github.RepoSecret("acme/app", "UNMANAGED", "keep"))
@@ -302,7 +340,7 @@ than polling state:
```go
mark := gh.Mark(t)
-secret.Delete(t, proj, "dev", "DROP")
+secretmanager.DeleteSecret(t, proj, "dev", "DROP")
s.trigger(t)
gh.ExpectEvent[github.SecretDeleted](t, func(e github.SecretDeleted) bool {
@@ -332,7 +370,7 @@ func (SecretDeleted) EventName() string { return "github.secret-deleted" }
Publish it from the fake with `a.events.Publish(...)` wherever state changes. Whatever
mints a credential calls `fakenet.Track` before handing it to Infisical, which
-`appconnection` already does.
+`fixture.NewAppConnection` already does.
### Adding a fake
@@ -377,7 +415,7 @@ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.RBAC)
tn.SetPlan(t, license.Enterprise()) // also verifies it took effect
```
-Use `unlicensed/` subtests to pin downgrade behaviour. `CODE_QUALITY.md` requires that a
+Write `should ... when the plan does not include it` subtests to pin downgrade behaviour. `CODE_QUALITY.md` requires that a
license check never changes a read path, and flipping entitlements is the only way to
test that.
diff --git a/tests/fakes/github/fake_test.go b/tests/fakes/github/fake_test.go
index 74529bf7e0..9561c99d6d 100644
--- a/tests/fakes/github/fake_test.go
+++ b/tests/fakes/github/fake_test.go
@@ -13,220 +13,186 @@ import (
"github.com/Infisical/infisical/tests/fakes/github"
"github.com/Infisical/infisical/tests/infra/fakenet"
+ "github.com/stretchr/testify/require"
"golang.org/x/crypto/nacl/box"
)
-// A fake is a plain http.Handler, so it is provable without Docker. That is the
-// intended development loop: write the fake here, then let the suite consume it
-// through the container.
-func newServer(t *testing.T) (*httptest.Server, *fakenet.Server) {
+const repo = "/repos/acme/app/actions/secrets"
+
+// A fake is a plain http.Handler, so it is provable without Docker.
+func newServer(t *testing.T) *httptest.Server {
t.Helper()
- srv := fakenet.New(github.Service)
- ts := httptest.NewServer(srv)
+ ts := httptest.NewServer(fakenet.New(github.Service))
t.Cleanup(ts.Close)
- return ts, srv
+ return ts
}
-func do(t *testing.T, ts *httptest.Server, method, token, path string, body any) (int, []byte) {
+func send(t *testing.T, ts *httptest.Server, method, host, token, path string, body any) *http.Response {
t.Helper()
var r io.Reader
if body != nil {
raw, err := json.Marshal(body)
- if err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, err)
r = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(t.Context(), method, ts.URL+path, r)
- if err != nil {
- t.Fatal(err)
- }
- req.Host = "api.github.com"
+ require.NoError(t, err)
+ req.Host = host
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
res, err := ts.Client().Do(req)
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = res.Body.Close() }()
- out, _ := io.ReadAll(res.Body)
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = res.Body.Close() })
+ return res
+}
+
+func do(t *testing.T, ts *httptest.Server, method, token, path string, body any) (int, []byte) {
+ t.Helper()
+ res := send(t, ts, method, "api.github.com", token, path, body)
+ out, err := io.ReadAll(res.Body)
+ require.NoError(t, err)
return res.StatusCode, out
}
-// seal encrypts the way the product does, so the test drives the fake through the
-// same wire format GitHub requires.
-func seal(t *testing.T, ts *httptest.Server, token, scope, value string) (string, string) {
+// seal encrypts the way the product does.
+func seal(t *testing.T, ts *httptest.Server, token, scope, value string) (encrypted, keyID string) {
t.Helper()
code, body := do(t, ts, http.MethodGet, token, scope+"/public-key", nil)
- if code != http.StatusOK {
- t.Fatalf("public-key returned %d: %s", code, body)
- }
+ require.Equalf(t, http.StatusOK, code, "public-key: %s", body)
+
var pk struct {
KeyID string `json:"key_id"`
Key string `json:"key"`
}
- if err := json.Unmarshal(body, &pk); err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, json.Unmarshal(body, &pk))
raw, err := base64.StdEncoding.DecodeString(pk.Key)
- if err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, err)
+
var pub [32]byte
copy(pub[:], raw)
sealed, err := box.SealAnonymous(nil, []byte(value), &pub, rand.Reader)
- if err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, err)
return base64.StdEncoding.EncodeToString(sealed), pk.KeyID
}
-func TestGitHubFake_Secrets(t *testing.T) {
- const repo = "/repos/acme/app/actions/secrets"
+func put(t *testing.T, ts *httptest.Server, token, name, encrypted, keyID string) (int, []byte) {
+ t.Helper()
+ return do(t, ts, http.MethodPut, token, repo+"/"+name,
+ map[string]string{"encrypted_value": encrypted, "key_id": keyID})
+}
- t.Run("ok/a sealed value is stored as plaintext the test can read", func(t *testing.T) {
- ts, _ := newServer(t)
+func TestGitHubFake_Secrets(t *testing.T) {
+ t.Run("should list a secret when a sealed value is stored", func(t *testing.T) {
+ // Setup
+ ts := newServer(t)
enc, keyID := seal(t, ts, "ghp_a", repo, "postgres://db/app")
- code, body := do(t, ts, http.MethodPut, "ghp_a", repo+"/DB_URL",
- map[string]string{"encrypted_value": enc, "key_id": keyID})
- if code != http.StatusCreated {
- t.Fatalf("PUT returned %d: %s", code, body)
- }
+ // Action
+ code, body := put(t, ts, "ghp_a", "DB_URL", enc, keyID)
- code, body = do(t, ts, http.MethodGet, "ghp_a", repo, nil)
- if code != http.StatusOK {
- t.Fatalf("list returned %d: %s", code, body)
- }
- if !bytes.Contains(body, []byte("DB_URL")) {
- t.Errorf("list does not mention the secret: %s", body)
- }
+ // Assert
+ require.Equalf(t, http.StatusCreated, code, "PUT: %s", body)
+ _, list := do(t, ts, http.MethodGet, "ghp_a", repo, nil)
+ require.Contains(t, string(list), "DB_URL")
})
- t.Run("invalid/a value that is not a sealed box is refused", func(t *testing.T) {
- ts, _ := newServer(t)
+ t.Run("should refuse a value when it is not a sealed box", func(t *testing.T) {
+ // Setup
+ ts := newServer(t)
_, keyID := seal(t, ts, "ghp_a", repo, "ignored")
+ plaintext := base64.StdEncoding.EncodeToString([]byte("postgres://db/app"))
- // Plaintext, base64'd, which is what a sync that forgot to encrypt would send.
- code, body := do(t, ts, http.MethodPut, "ghp_a", repo+"/DB_URL", map[string]string{
- "encrypted_value": base64.StdEncoding.EncodeToString([]byte("postgres://db/app")),
- "key_id": keyID,
- })
- if code != http.StatusUnprocessableEntity {
- t.Fatalf("PUT of plaintext returned %d, want 422: %s", code, body)
- }
+ // Action
+ code, body := put(t, ts, "ghp_a", "DB_URL", plaintext, keyID)
+
+ // Assert
+ require.Equalf(t, http.StatusUnprocessableEntity, code, "PUT of plaintext: %s", body)
})
- t.Run("ok/a deleted secret stops being listed", func(t *testing.T) {
- ts, _ := newServer(t)
+ t.Run("should stop listing a secret when it is deleted", func(t *testing.T) {
+ // Setup
+ ts := newServer(t)
enc, keyID := seal(t, ts, "ghp_a", repo, "v")
- do(t, ts, http.MethodPut, "ghp_a", repo+"/GONE", map[string]string{"encrypted_value": enc, "key_id": keyID})
+ put(t, ts, "ghp_a", "GONE", enc, keyID)
- if code, body := do(t, ts, http.MethodDelete, "ghp_a", repo+"/GONE", nil); code != http.StatusNoContent {
- t.Fatalf("DELETE returned %d: %s", code, body)
- }
- if _, body := do(t, ts, http.MethodGet, "ghp_a", repo, nil); bytes.Contains(body, []byte("GONE")) {
- t.Errorf("a deleted secret is still listed: %s", body)
- }
+ // Action
+ code, body := do(t, ts, http.MethodDelete, "ghp_a", repo+"/GONE", nil)
+
+ // Assert
+ require.Equalf(t, http.StatusNoContent, code, "DELETE: %s", body)
+ _, list := do(t, ts, http.MethodGet, "ghp_a", repo, nil)
+ require.NotContains(t, string(list), "GONE")
})
- t.Run("cross-tenant/two credentials hold separate accounts", func(t *testing.T) {
- ts, _ := newServer(t)
- encA, keyA := seal(t, ts, "ghp_a", repo, "a-value")
- do(t, ts, http.MethodPut, "ghp_a", repo+"/SHARED", map[string]string{"encrypted_value": encA, "key_id": keyA})
+ t.Run("should keep accounts apart when two credentials use one repository", func(t *testing.T) {
+ // Setup
+ ts := newServer(t)
+ enc, keyID := seal(t, ts, "ghp_a", repo, "a-value")
- // Same repository path, different credential. This is the whole isolation
- // story: one fakenet serves every parallel tenant.
- if _, body := do(t, ts, http.MethodGet, "ghp_b", repo, nil); bytes.Contains(body, []byte("SHARED")) {
- t.Errorf("credential b can see credential a's secret: %s", body)
- }
+ // Action
+ put(t, ts, "ghp_a", "SHARED", enc, keyID)
+
+ // Assert
+ _, list := do(t, ts, http.MethodGet, "ghp_b", repo, nil)
+ require.NotContains(t, string(list), "SHARED", "credential b can see credential a's secret")
})
- t.Run("ok/listing paginates and advertises the last page", func(t *testing.T) {
- ts, _ := newServer(t)
+ t.Run("should reach every secret when the listing spans pages", func(t *testing.T) {
+ // Setup
+ ts := newServer(t)
enc, keyID := seal(t, ts, "ghp_a", repo, "v")
for i := range 150 {
- do(t, ts, http.MethodPut, "ghp_a", fmt.Sprintf("%s/S%03d", repo, i),
- map[string]string{"encrypted_value": enc, "key_id": keyID})
- }
-
- req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+repo+"?per_page=100", nil)
- if err != nil {
- t.Fatal(err)
- }
- req.Host = "api.github.com"
- req.Header.Set("Authorization", "Bearer ghp_a")
- res, err := ts.Client().Do(req)
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = res.Body.Close() }()
-
- link := res.Header.Get("Link")
- if link == "" {
- t.Fatal("no Link header on a result that spans pages, so the client would never fetch page 2")
- }
- if !bytes.Contains([]byte(link), []byte(`rel="last"`)) {
- t.Fatalf("Link header carries no rel=last, which is what the client parses for a page count: %s", link)
+ put(t, ts, "ghp_a", fmt.Sprintf("S%03d", i), enc, keyID)
}
- // Walk the pages the way makePaginatedGitHubRequest does, and check every
- // secret is reachable. A fake that answered page 1 forever would pass a
- // header check and fail this.
+ // Action: walk the pages the way makePaginatedGitHubRequest does.
+ first := send(t, ts, http.MethodGet, "api.github.com", "ghp_a", repo+"?per_page=100", nil)
seen := map[string]bool{}
for page := 1; page <= 2; page++ {
- _, body := do(t, ts, http.MethodGet, "ghp_a",
- fmt.Sprintf("%s?per_page=100&page=%d", repo, page), nil)
+ _, body := do(t, ts, http.MethodGet, "ghp_a", fmt.Sprintf("%s?per_page=100&page=%d", repo, page), nil)
var out struct {
TotalCount int `json:"total_count"`
Secrets []struct {
Name string `json:"name"`
} `json:"secrets"`
}
- if err := json.Unmarshal(body, &out); err != nil {
- t.Fatal(err)
- }
- if out.TotalCount != 150 {
- t.Errorf("page %d reports total_count %d, want 150", page, out.TotalCount)
- }
+ require.NoError(t, json.Unmarshal(body, &out))
+ require.Equal(t, 150, out.TotalCount)
for _, s := range out.Secrets {
seen[s.Name] = true
}
}
- if len(seen) != 150 {
- t.Errorf("walking two pages found %d secrets, want 150", len(seen))
- }
+
+ // Assert
+ require.Contains(t, first.Header.Get("Link"), `rel="last"`, "the client parses rel=last for a page count")
+ require.Len(t, seen, 150)
})
}
func TestFakenet_Dispatch(t *testing.T) {
- t.Run("invalid/an unfaked host is refused by name", func(t *testing.T) {
- ts, _ := newServer(t)
- req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+"/v1/accounts", nil)
- if err != nil {
- t.Fatal(err)
- }
- req.Host = "api.checklyhq.com"
- res, err := ts.Client().Do(req)
- if err != nil {
- t.Fatal(err)
- }
- defer func() { _ = res.Body.Close() }()
-
- if res.StatusCode != http.StatusNotImplemented {
- t.Fatalf("an unfaked host returned %d, want 501", res.StatusCode)
- }
- body, _ := io.ReadAll(res.Body)
- if !bytes.Contains(body, []byte("api.checklyhq.com")) {
- t.Errorf("the refusal does not name the host, so a forgotten fake is hard to place: %s", body)
- }
+ t.Run("should refuse by name when the host has no fake", func(t *testing.T) {
+ // Setup
+ ts := newServer(t)
+
+ // Action
+ res := send(t, ts, http.MethodGet, "api.checklyhq.com", "", "/v1/accounts", nil)
+
+ // Assert
+ require.Equal(t, http.StatusNotImplemented, res.StatusCode)
+ body, err := io.ReadAll(res.Body)
+ require.NoError(t, err)
+ require.Contains(t, string(body), "api.checklyhq.com", "a refusal must name the host")
})
- t.Run("invalid/a request with no credential is refused", func(t *testing.T) {
- ts, _ := newServer(t)
- if code, body := do(t, ts, http.MethodGet, "", "/user", nil); code != http.StatusNotImplemented {
- t.Fatalf("returned %d, want 501: %s", code, body)
- }
+ t.Run("should refuse when the request carries no credential", func(t *testing.T) {
+ // Setup
+ ts := newServer(t)
+
+ // Action
+ code, body := do(t, ts, http.MethodGet, "", "/user", nil)
+
+ // Assert
+ require.Equalf(t, http.StatusNotImplemented, code, "%s", body)
})
}
diff --git a/tests/fakes/license/license_test.go b/tests/fakes/license/license_test.go
index 9c7fb69676..580bea6c65 100644
--- a/tests/fakes/license/license_test.go
+++ b/tests/fakes/license/license_test.go
@@ -1,83 +1,89 @@
package license
import (
- "strings"
"testing"
+
+ "github.com/stretchr/testify/require"
)
func TestPlan_Payload(t *testing.T) {
t.Parallel()
- t.Run("ok/enterprise turns on every feature the list knows", func(t *testing.T) {
+ t.Run("should turn on every known feature when the plan is enterprise", func(t *testing.T) {
t.Parallel()
+
+ // Action
p := Enterprise()
+
+ // Assert: projectV2ToFeatureSet layers over the OSS defaults, so an omitted
+ // feature stays off.
for _, f := range All {
- if _, ok := p.Features[f.V2]; !ok {
- t.Fatalf("enterprise omits %s; projectV2ToFeatureSet layers over the OSS "+
- "defaults, so anything omitted stays off", f.V2)
- }
+ require.Containsf(t, p.Features, f.V2, "enterprise omits %s", f.V2)
}
})
- t.Run("ok/free omits every feature rather than disabling them", func(t *testing.T) {
+ t.Run("should carry no features when the plan is free", func(t *testing.T) {
t.Parallel()
- if len(Free.Features) != 0 {
- t.Fatalf("free carries %d features; a downgraded customer gets the OSS "+
- "defaults, not an explicit set of falses", len(Free.Features))
- }
+ require.Empty(t, Free.Features, "a downgraded customer gets the OSS defaults, not explicit falses")
})
- t.Run("ok/a cap is a number, not a boolean", func(t *testing.T) {
+ t.Run("should entitle a cap as a number", func(t *testing.T) {
t.Parallel()
+
+ // Action
p := Enterprise()
+
+ // Assert
for _, f := range []Feature{MaxInternalCAs, AuditRetentionDays} {
- if _, isBool := p.Features[f.V2].(bool); isBool {
- t.Errorf("%s is entitled as a boolean; it projects onto a numeric "+
- "TFeatureSet field", f.V2)
- }
+ require.IsTypef(t, 0, p.Features[f.V2], "%s projects onto a numeric field", f.V2)
}
})
- t.Run("ok/the entitled rate limits are raised, not merely enabled", func(t *testing.T) {
+ t.Run("should raise the plan rate limits rather than merely enable them", func(t *testing.T) {
t.Parallel()
+
+ // Action
p := Enterprise()
+
+ // Assert
for _, f := range []Feature{ReadRateLimit, WriteRateLimit, SecretsRateLimit} {
got, ok := p.Features[f.V2].(int)
- if !ok || got < 100_000 {
- t.Errorf("%s entitled as %v; the limiter registers whenever the license "+
- "stub is on, so a default-height limit would throttle the suite",
- f.V2, p.Features[f.V2])
- }
+ require.Truef(t, ok, "%s is not a number", f.V2)
+ require.GreaterOrEqualf(t, got, 100_000, "%s would throttle the suite", f.V2)
}
})
- t.Run("ok/Without leaves the original untouched", func(t *testing.T) {
+ t.Run("should leave the original untouched when Without is called", func(t *testing.T) {
t.Parallel()
+
+ // Setup
base := Enterprise()
+
+ // Action
_ = base.Without(RBAC)
- if base.Features[RBAC.V2] != true {
- t.Fatal("Without mutated the plan it was called on, so one test would " +
- "change another's entitlements")
- }
+
+ // Assert
+ require.Equal(t, true, base.Features[RBAC.V2], "Without mutated the plan it was called on")
})
- t.Run("ok/Expect covers only features with somewhere to check them", func(t *testing.T) {
+ t.Run("should only expect features that have a plan field", func(t *testing.T) {
t.Parallel()
+
+ // Action
expect := Enterprise().Expect()
- if _, ok := expect[""]; ok {
- t.Fatal("Expect includes a feature with no TFeatureSet field")
- }
- if _, ok := expect[RBAC.V1]; !ok {
- t.Fatalf("Expect omits %s, which does map to a plan field", RBAC.V1)
- }
+
+ // Assert
+ require.NotContains(t, expect, "")
+ require.Contains(t, expect, RBAC.V1)
})
}
func TestServiceKey_IsParseablePEM(t *testing.T) {
t.Parallel()
+
+ // Action
key := serviceKey()
- if !strings.HasPrefix(key, "-----BEGIN PRIVATE KEY-----") {
- t.Fatalf("service key is not PKCS#8 PEM; the license client parses it before "+
- "signing and fails before sending anything.\ngot: %.40s", key)
- }
+
+ // Assert: the license client parses it before sending anything.
+ require.Regexp(t, `^-----BEGIN PRIVATE KEY-----`, key)
}
diff --git a/tests/fixture/appconnection.go b/tests/fixture/appconnection.go
new file mode 100644
index 0000000000..560c02a36e
--- /dev/null
+++ b/tests/fixture/appconnection.go
@@ -0,0 +1,101 @@
+package fixture
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+ "github.com/Infisical/infisical/tests/internal/id"
+ "github.com/Infisical/infisical/tests/provider"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/require"
+)
+
+// AppConnection is one connection and the credential its fake state is keyed on.
+type AppConnection struct {
+ ID uuid.UUID
+ Name string
+ Provider provider.Provider
+
+ nonce string
+ tn *harness.Tenant
+}
+
+type AppConnectionOption func(*appConnectionConfig)
+
+type appConnectionConfig struct {
+ rejectWith int
+}
+
+// RejectCredentials makes the provider refuse the credential check, so the create
+// fails. Proves the check is load bearing rather than merely made.
+func RejectCredentials(status int) AppConnectionOption {
+ return func(c *appConnectionConfig) { c.rejectWith = status }
+}
+
+func NewAppConnection(tt *testing.T, tn *harness.Tenant, p provider.Provider, opts ...AppConnectionOption) *AppConnection {
+ tt.Helper()
+ conn, err := TryAppConnection(tt, tn, p, opts...)
+ require.NoErrorf(tt, err, "creating a %s connection\n%s", p.App, deniedHint(tt, tn))
+ return conn
+}
+
+// TryAppConnection is NewAppConnection without failing, for an expected refusal.
+func TryAppConnection(tt *testing.T, tn *harness.Tenant, p provider.Provider, opts ...AppConnectionOption) (*AppConnection, error) {
+ tt.Helper()
+
+ var cfg appConnectionConfig
+ for _, o := range opts {
+ o(&cfg)
+ }
+
+ conn := &AppConnection{
+ Name: p.App + "-" + id.Short(),
+ Provider: p,
+ nonce: id.Nonce(),
+ tn: tn,
+ }
+
+ // Before the credential reaches Infisical, so nothing published under it can
+ // arrive before its buffer exists.
+ fakenet.Track(tt, conn.FakenetAdmin(tt), p.Host, conn.nonce)
+
+ if cfg.rejectWith != 0 {
+ fakenet.Open[any](tt, conn.FakenetAdmin(tt), p.Host, conn.nonce).
+ Fail(tt, "", "*", cfg.rejectWith)
+ }
+
+ connID, err := p.Create(tt.Context(), tn.Admin.API, conn.Name, conn.nonce)
+ if err != nil {
+ return nil, err
+ }
+ conn.ID = connID
+ return conn, nil
+}
+
+// deniedHint names the outbound calls that reached no fake, which the application's
+// own error rarely does.
+func deniedHint(tt *testing.T, tn *harness.Tenant) string {
+ h, ok := tn.Module(tt, fakenet.Key, "harness.Shared").(*fakenet.Handle)
+ if !ok {
+ return ""
+ }
+ denied, err := h.Denied(context.WithoutCancel(tt.Context()))
+ if err != nil || len(denied) == 0 {
+ return ""
+ }
+ out := "Outbound calls that reached no fake:\n"
+ for _, d := range denied {
+ out += " " + d.Method + " " + d.URL + ": " + d.Reason + "\n"
+ }
+ return out
+}
+
+func (c *AppConnection) Nonce() string { return c.nonce }
+
+// FakenetAdmin is a URL rather than a handle so fake packages never import fixtures.
+func (c *AppConnection) FakenetAdmin(tt *testing.T) string {
+ tt.Helper()
+ return c.tn.Module(tt, fakenet.Key, "harness.Shared").(*fakenet.Handle).AdminURL()
+}
diff --git a/tests/fixture/appconnection/appconnection.go b/tests/fixture/appconnection/appconnection.go
deleted file mode 100644
index 0e4945dd03..0000000000
--- a/tests/fixture/appconnection/appconnection.go
+++ /dev/null
@@ -1,128 +0,0 @@
-// Package appconnection creates app connections against faked providers.
-//
-// Creating one calls the third party to check the credentials. The fake answers by
-// existing, so nothing has to be registered first; what the fixture carries is the
-// credential, which is the key that connection's fake state is held under.
-package appconnection
-
-import (
- "context"
- "testing"
-
- "github.com/Infisical/infisical/tests/harness"
- "github.com/Infisical/infisical/tests/infra/fakenet"
- "github.com/Infisical/infisical/tests/internal/id"
- "github.com/Infisical/infisical/tests/provider"
- "github.com/google/uuid"
-)
-
-// Connection is one app connection and the credential that addresses its fake.
-type Connection struct {
- ID uuid.UUID
- Name string
- Provider provider.Provider
-
- // nonce is the credential this connection authenticates with, and therefore
- // what tells its outbound calls apart from every other tenant's.
- nonce string
-
- tn *harness.Tenant
-}
-
-// Option adjusts a new connection.
-type Option func(*config)
-
-type config struct {
- rejectWith int
-}
-
-// RejectCredentials makes the provider answer the credential check with an error
-// status, so the connection cannot be created.
-//
-// For asserting that the check is load bearing. Without a test like that, an
-// interception test proves only that a request was made, not that its answer
-// mattered.
-func RejectCredentials(status int) Option {
- return func(c *config) { c.rejectWith = status }
-}
-
-// New creates a connection, failing the test if the provider refuses it.
-func New(tt *testing.T, tn *harness.Tenant, p provider.Provider, opts ...Option) *Connection {
- tt.Helper()
- conn, err := Try(tt, tn, p, opts...)
- if err != nil {
- tt.Fatalf("appconnection: %v\n%s", err, unstubbedHint(tt, tn))
- }
- return conn
-}
-
-// Try is New without failing the test, for the cases where the create is expected
-// to be refused.
-func Try(tt *testing.T, tn *harness.Tenant, p provider.Provider, opts ...Option) (*Connection, error) {
- tt.Helper()
-
- var cfg config
- for _, o := range opts {
- o(&cfg)
- }
-
- conn := &Connection{
- Name: p.App + "-" + id.Short(),
- Provider: p,
- nonce: id.Nonce(),
- tn: tn,
- }
-
- // Before the credential reaches Infisical, so no event published under it can
- // arrive before its buffer exists.
- fakenet.Track(tt, conn.FakenetAdmin(tt), p.Host, conn.nonce)
-
- // The fake answers the credential check by existing, so nothing has to be
- // registered for a connection to be created. Refusing one is the exception, and
- // it goes in before the create: the scope is the credential, which the fixture
- // already knows, so the rule is in place before the first call carries it.
- if cfg.rejectWith != 0 {
- fakenet.Open[any](tt, conn.FakenetAdmin(tt), p.Host, conn.nonce).
- Fail(tt, "", "*", cfg.rejectWith)
- }
-
- connID, err := p.Create(tt.Context(), tn.Admin.API, conn.Name, conn.nonce)
- if err != nil {
- return nil, err
- }
- conn.ID = connID
- return conn, nil
-}
-
-// unstubbedHint turns "the provider call failed" into the URL nobody stubbed.
-//
-// The application reports a validation failure or a 501 and rarely names the URL,
-// so without this the test author is left guessing which call they missed.
-func unstubbedHint(tt *testing.T, tn *harness.Tenant) string {
- h, ok := tn.Module(tt, fakenet.Key, "harness.Shared").(*fakenet.Handle)
- if !ok {
- return ""
- }
- denied, err := h.Denied(context.WithoutCancel(tt.Context()))
- if err != nil || len(denied) == 0 {
- return ""
- }
- out := "Outbound calls that reached no fake:\n"
- for _, d := range denied {
- out += " " + d.Method + " " + d.URL + ": " + d.Reason + "\n"
- }
- return out + "Add a Service to fakenet.New in cmd/fakenet, or a route to the fake that owns that host.\n"
-}
-
-// Nonce is the credential this connection authenticates with, and therefore the key
-// its fake state is held under inside fakenet.
-func (c *Connection) Nonce() string { return c.nonce }
-
-// FakenetAdmin is where this connection's fake can be read and driven.
-//
-// Returned as a URL rather than a typed handle so that a fake package never has to
-// import this one: fixtures may depend on the harness, and fakes depend on neither.
-func (c *Connection) FakenetAdmin(tt *testing.T) string {
- tt.Helper()
- return c.tn.Module(tt, fakenet.Key, "harness.Shared").(*fakenet.Handle).AdminURL()
-}
diff --git a/tests/fixture/project.go b/tests/fixture/project.go
new file mode 100644
index 0000000000..c66339b1f7
--- /dev/null
+++ b/tests/fixture/project.go
@@ -0,0 +1,176 @@
+// Package fixture builds platform resources a test needs: projects and app
+// connections. Product resources live in a package per product under fixture/.
+//
+// Required arguments are positional; everything optional is an option.
+package fixture
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/Infisical/infisical/tests/internal/id"
+ openapi_types "github.com/oapi-codegen/runtime/types"
+ "github.com/stretchr/testify/require"
+)
+
+type Project struct {
+ ID string
+ Name string
+ Slug string
+ Type string
+ Environments []string
+
+ tn *harness.Tenant
+}
+
+type ProjectOption func(*projectConfig)
+
+type projectConfig struct {
+ name string
+ kind string
+}
+
+func WithProjectName(name string) ProjectOption {
+ return func(c *projectConfig) { c.name = name }
+}
+
+// WithProjectType picks the product: secret-manager, cert-manager, kms, ssh.
+func WithProjectType(kind string) ProjectOption {
+ return func(c *projectConfig) { c.kind = kind }
+}
+
+func NewProject(tt *testing.T, tn *harness.Tenant, opts ...ProjectOption) *Project {
+ tt.Helper()
+
+ cfg := projectConfig{name: "p-" + id.Short()}
+ for _, o := range opts {
+ o(&cfg)
+ }
+
+ req := api.CreateProjectJSONRequestBody{ProjectName: cfg.name}
+ if cfg.kind != "" {
+ kind := api.CreateProjectJSONBodyType(cfg.kind)
+ req.Type = &kind
+ }
+
+ res, err := tn.Admin.API.CreateProjectWithResponse(tt.Context(), req)
+ require.NoError(tt, err, "creating a project")
+ require.NotNilf(tt, res.JSON200, "creating a project returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+
+ p := res.JSON200.Project
+ proj := &Project{ID: p.Id, Name: p.Name, Slug: p.Slug, Type: p.Type, tn: tn}
+ for _, env := range p.Environments {
+ proj.Environments = append(proj.Environments, env.Slug)
+ }
+ return proj
+}
+
+func (p *Project) Tenant() *harness.Tenant { return p.tn }
+
+type PrincipalOption func(*principalConfig)
+
+type principalConfig struct {
+ name string
+ roles []string
+}
+
+// WithPrincipalName also picks a user's mailbox: alice means alice@<orgslug>.test.
+func WithPrincipalName(n string) PrincipalOption {
+ return func(c *principalConfig) { c.name = n }
+}
+
+// WithRoles sets project roles. Without it a principal gets member.
+func WithRoles(slugs ...string) PrincipalOption {
+ return func(c *principalConfig) { c.roles = slugs }
+}
+
+func newPrincipalConfig(opts []PrincipalOption) principalConfig {
+ var cfg principalConfig
+ for _, o := range opts {
+ o(&cfg)
+ }
+ return cfg
+}
+
+func (p *Project) NewIdentity(tt *testing.T, opts ...PrincipalOption) *harness.Principal {
+ tt.Helper()
+
+ cfg := newPrincipalConfig(opts)
+ if cfg.name == "" {
+ cfg.name = "i-" + id.Short()
+ }
+
+ req := api.CreateProjectMachineIdentityJSONRequestBody{Name: cfg.name}
+ if len(cfg.roles) > 0 {
+ roles := make([]api.CreateProjectMachineIdentityJSONBody_Roles_Item, 0, len(cfg.roles))
+ for _, slug := range cfg.roles {
+ var item api.CreateProjectMachineIdentityJSONBody_Roles_Item
+ require.NoError(tt, item.FromCreateProjectMachineIdentityJSONBodyRoles0(
+ api.CreateProjectMachineIdentityJSONBodyRoles0{Role: slug}))
+ roles = append(roles, item)
+ }
+ req.Roles = &roles
+ }
+
+ res, err := p.tn.Admin.API.CreateProjectMachineIdentityWithResponse(tt.Context(), p.ID, req)
+ require.NoErrorf(tt, err, "creating identity %s in %s", cfg.name, p.Slug)
+ require.NotNilf(tt, res.JSON200, "creating identity %s in %s returned %d: %s",
+ cfg.name, p.Slug, res.StatusCode(), apierr.Body(res.Body))
+ return p.tn.LoginIdentity(tt, res.JSON200.Identity.Id, cfg.name)
+}
+
+func (p *Project) NewUser(tt *testing.T, opts ...PrincipalOption) *harness.Principal {
+ tt.Helper()
+
+ cfg := newPrincipalConfig(opts)
+ var userOpts []harness.PrincipalOption
+ if cfg.name != "" {
+ userOpts = append(userOpts, harness.WithName(cfg.name))
+ }
+
+ pr := p.tn.NewUser(tt, userOpts...)
+ p.Grant(tt, pr, cfg.roles...)
+ return pr
+}
+
+// Grant gives an existing principal access to this project. Users and identities go
+// through different routes, which is why Principal carries its Kind.
+func (p *Project) Grant(tt *testing.T, pr *harness.Principal, roles ...string) {
+ tt.Helper()
+ ctx := tt.Context()
+
+ // Defaulted here because inviteProjectMembers falls back to member on its own and
+ // createProjectIdentityMembership does not.
+ if len(roles) == 0 {
+ roles = []string{"member"}
+ }
+
+ switch pr.Kind {
+ case harness.User:
+ res, err := p.tn.Admin.API.InviteProjectMembersWithResponse(ctx, p.ID,
+ api.InviteProjectMembersJSONRequestBody{
+ Emails: &[]openapi_types.Email{openapi_types.Email(pr.Email)},
+ RoleSlugs: &roles,
+ })
+ require.NoErrorf(tt, err, "adding %s to %s", pr.Email, p.Slug)
+ require.Equalf(tt, http.StatusOK, res.StatusCode(), "adding %s to %s: %s",
+ pr.Email, p.Slug, apierr.Body(res.Body))
+
+ case harness.Identity:
+ items := make([]api.CreateProjectIdentityMembershipJSONBody_Roles_Item, 0, len(roles))
+ for _, slug := range roles {
+ var item api.CreateProjectIdentityMembershipJSONBody_Roles_Item
+ require.NoError(tt, item.FromCreateProjectIdentityMembershipJSONBodyRoles0(
+ api.CreateProjectIdentityMembershipJSONBodyRoles0{Role: slug}))
+ items = append(items, item)
+ }
+ res, err := p.tn.Admin.API.CreateProjectIdentityMembershipWithResponse(ctx, p.ID, pr.ID.String(),
+ api.CreateProjectIdentityMembershipJSONRequestBody{Roles: &items})
+ require.NoErrorf(tt, err, "adding identity %s to %s", pr.Name, p.Slug)
+ require.Equalf(tt, http.StatusOK, res.StatusCode(), "adding identity %s to %s: %s",
+ pr.Name, p.Slug, apierr.Body(res.Body))
+ }
+}
diff --git a/tests/fixture/project/project.go b/tests/fixture/project/project.go
deleted file mode 100644
index 373dedeaf7..0000000000
--- a/tests/fixture/project/project.go
+++ /dev/null
@@ -1,210 +0,0 @@
-// Package project creates projects and the principals that live inside them.
-//
-// Split from harness because organization membership is not project membership:
-// the roles, the routes and the options differ, and keeping them in separate
-// packages means a project role cannot be passed where only an organization role
-// makes sense. That used to be a runtime check.
-package project
-
-import (
- "net/http"
- "testing"
-
- "github.com/Infisical/infisical/tests/clients/api"
- "github.com/Infisical/infisical/tests/harness"
- "github.com/Infisical/infisical/tests/internal/apierr"
- "github.com/Infisical/infisical/tests/internal/id"
- openapi_types "github.com/oapi-codegen/runtime/types"
-)
-
-// Project is one project inside a tenant.
-type Project struct {
- ID string
- Name string
- Slug string
- Type string
-
- // Environments are the slugs the project was created with: dev, staging, prod
- // unless the type or template says otherwise.
- Environments []string
-
- tn *harness.Tenant
-}
-
-// Option adjusts a new project.
-type Option func(*config)
-
-type config struct {
- name string
- kind string
-}
-
-// WithName names the project. Rarely needed; the slug carries a nanoid.
-func WithName(name string) Option { return func(c *config) { c.name = name } }
-
-// WithType picks the product: secret-manager, cert-manager, kms, ssh.
-func WithType(kind string) Option { return func(c *config) { c.kind = kind } }
-
-// New creates a project owned by the tenant's administrator.
-func New(tt *testing.T, tn *harness.Tenant, opts ...Option) *Project {
- tt.Helper()
-
- cfg := config{name: "p-" + id.Short()}
- for _, o := range opts {
- o(&cfg)
- }
-
- req := api.CreateProjectJSONRequestBody{ProjectName: cfg.name}
- if cfg.kind != "" {
- kind := api.CreateProjectJSONBodyType(cfg.kind)
- req.Type = &kind
- }
-
- res, err := tn.Admin.API.CreateProjectWithResponse(tt.Context(), req)
- if err != nil {
- tt.Fatalf("project: creating: %v", err)
- }
- if res.JSON200 == nil {
- tt.Fatalf("project: creating returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
- }
-
- p := res.JSON200.Project
- proj := &Project{ID: p.Id, Name: p.Name, Slug: p.Slug, Type: p.Type, tn: tn}
- for _, env := range p.Environments {
- proj.Environments = append(proj.Environments, env.Slug)
- }
- return proj
-}
-
-// Tenant is the organization this project belongs to.
-func (p *Project) Tenant() *harness.Tenant { return p.tn }
-
-// PrincipalOption adjusts a principal created inside a project.
-type PrincipalOption func(*principalConfig)
-
-type principalConfig struct {
- name string
- roles []string
-}
-
-// Name names the principal. For a user it also picks the mailbox, so Name("alice")
-// means alice@<orgslug>.test.
-func Name(n string) PrincipalOption { return func(c *principalConfig) { c.name = n } }
-
-// Role sets the project roles the principal gets.
-func Role(slugs ...string) PrincipalOption {
- return func(c *principalConfig) { c.roles = slugs }
-}
-
-func newPrincipalConfig(opts []PrincipalOption) principalConfig {
- var cfg principalConfig
- for _, o := range opts {
- o(&cfg)
- }
- return cfg
-}
-
-// NewIdentity creates a machine identity directly inside this project.
-//
-// One call rather than two: createProjectMachineIdentity takes the project roles
-// and makes the organization identity and the project membership together.
-func (p *Project) NewIdentity(tt *testing.T, opts ...PrincipalOption) *harness.Principal {
- tt.Helper()
-
- cfg := newPrincipalConfig(opts)
- if cfg.name == "" {
- cfg.name = "i-" + id.Short()
- }
-
- req := api.CreateProjectMachineIdentityJSONRequestBody{Name: cfg.name}
- if len(cfg.roles) > 0 {
- roles := make([]api.CreateProjectMachineIdentityJSONBody_Roles_Item, 0, len(cfg.roles))
- for _, slug := range cfg.roles {
- var item api.CreateProjectMachineIdentityJSONBody_Roles_Item
- if err := item.FromCreateProjectMachineIdentityJSONBodyRoles0(
- api.CreateProjectMachineIdentityJSONBodyRoles0{Role: slug}); err != nil {
- tt.Fatalf("project: %v", err)
- }
- roles = append(roles, item)
- }
- req.Roles = &roles
- }
-
- res, err := p.tn.Admin.API.CreateProjectMachineIdentityWithResponse(tt.Context(), p.ID, req)
- if err != nil {
- tt.Fatalf("project: creating identity %s in %s: %v", cfg.name, p.Slug, err)
- }
- if res.JSON200 == nil {
- tt.Fatalf("project: creating identity %s in %s returned %d: %s",
- cfg.name, p.Slug, res.StatusCode(), apierr.Body(res.Body))
- }
- return p.tn.LoginIdentity(tt, res.JSON200.Identity.Id, cfg.name)
-}
-
-// NewUser creates a user and grants it access to this project.
-func (p *Project) NewUser(tt *testing.T, opts ...PrincipalOption) *harness.Principal {
- tt.Helper()
-
- cfg := newPrincipalConfig(opts)
- var userOpts []harness.PrincipalOption
- if cfg.name != "" {
- userOpts = append(userOpts, harness.WithName(cfg.name))
- }
-
- pr := p.tn.NewUser(tt, userOpts...)
- p.Grant(tt, pr, cfg.roles...)
- return pr
-}
-
-// Grant gives an existing principal access to this project.
-//
-// Users and identities take different routes -- inviteProjectMembers against the
-// project's membership collection, createProjectIdentityMembership against the
-// identity -- which is why Principal carries its Kind.
-func (p *Project) Grant(tt *testing.T, pr *harness.Principal, roles ...string) {
- tt.Helper()
- ctx := tt.Context()
-
- // Defaulted here rather than left to the server: inviteProjectMembers falls back
- // to member on its own, createProjectIdentityMembership does not, and a fixture
- // that behaves differently for a user and an identity is a trap.
- if len(roles) == 0 {
- roles = []string{"member"}
- }
-
- switch pr.Kind {
- case harness.User:
- res, err := p.tn.Admin.API.InviteProjectMembersWithResponse(ctx, p.ID,
- api.InviteProjectMembersJSONRequestBody{
- Emails: &[]openapi_types.Email{openapi_types.Email(pr.Email)},
- RoleSlugs: &roles,
- })
- if err != nil {
- tt.Fatalf("project: adding %s to %s: %v", pr.Email, p.Slug, err)
- }
- if res.StatusCode() != http.StatusOK {
- tt.Fatalf("project: adding %s to %s returned %d: %s",
- pr.Email, p.Slug, res.StatusCode(), apierr.Body(res.Body))
- }
-
- case harness.Identity:
- items := make([]api.CreateProjectIdentityMembershipJSONBody_Roles_Item, 0, len(roles))
- for _, slug := range roles {
- var item api.CreateProjectIdentityMembershipJSONBody_Roles_Item
- if err := item.FromCreateProjectIdentityMembershipJSONBodyRoles0(
- api.CreateProjectIdentityMembershipJSONBodyRoles0{Role: slug}); err != nil {
- tt.Fatalf("project: %v", err)
- }
- items = append(items, item)
- }
- res, err := p.tn.Admin.API.CreateProjectIdentityMembershipWithResponse(ctx, p.ID, pr.ID.String(),
- api.CreateProjectIdentityMembershipJSONRequestBody{Roles: &items})
- if err != nil {
- tt.Fatalf("project: adding identity %s to %s: %v", pr.Name, p.Slug, err)
- }
- if res.StatusCode() != http.StatusOK {
- tt.Fatalf("project: adding identity %s to %s returned %d: %s",
- pr.Name, p.Slug, res.StatusCode(), apierr.Body(res.Body))
- }
- }
-}
diff --git a/tests/fixture/secret/secret.go b/tests/fixture/secret/secret.go
deleted file mode 100644
index 295a2f2414..0000000000
--- a/tests/fixture/secret/secret.go
+++ /dev/null
@@ -1,146 +0,0 @@
-// Package secret creates and reads secrets in a project.
-//
-// Environment, name and value are positional because the API refuses a request
-// without them. Everything the schema marks optional is an option, so a test that
-// needs metadata, a different path or a different actor adds one rather than
-// changing every call site.
-package secret
-
-import (
- "fmt"
- "testing"
-
- "github.com/Infisical/infisical/tests/clients/api"
- "github.com/Infisical/infisical/tests/fixture/project"
- "github.com/Infisical/infisical/tests/harness"
- "github.com/Infisical/infisical/tests/internal/apierr"
-)
-
-// Value is what a read returns.
-//
-// A narrowed view rather than the generated struct, because the response is a union
-// and the fields worth asserting on are few. SecretValueHidden is one of them: a
-// value that came back hidden is useless to anything downstream, and reads as empty
-// rather than as an error.
-type Value struct {
- Value string
- ValueHidden bool
- Path string
- Version float32
-}
-
-// Option adjusts a secret operation.
-type Option func(*config)
-
-type config struct {
- path string
- as *harness.Principal
-}
-
-// Path places the secret somewhere other than the project root.
-func Path(p string) Option { return func(c *config) { c.path = p } }
-
-// As performs the operation as a principal other than the tenant administrator.
-//
-// Required for any test about what a member may do. Reaching for tn.Admin because it
-// is to hand makes the claim vacuous, which is why this exists before anything needs
-// it.
-func As(p *harness.Principal) Option { return func(c *config) { c.as = p } }
-
-func resolve(p *project.Project, opts []Option) (config, *api.ClientWithResponses) {
- cfg := config{path: "/"}
- for _, o := range opts {
- o(&cfg)
- }
- client := p.Tenant().Admin.API
- if cfg.as != nil {
- client = cfg.as.API
- }
- return cfg, client
-}
-
-// Create adds a secret and returns what the API reported.
-func Create(tt *testing.T, p *project.Project, env, name, value string, opts ...Option) Value {
- tt.Helper()
- cfg, client := resolve(p, opts)
-
- body := api.CreateSecretV4JSONRequestBody{
- ProjectId: p.ID,
- Environment: env,
- SecretPath: &cfg.path,
- SecretValue: value,
- }
- res, err := client.CreateSecretV4WithResponse(tt.Context(), name, body)
- if err != nil {
- tt.Fatalf("secret: creating %s: %v", name, err)
- }
- if res.JSON200 == nil {
- tt.Fatalf("secret: creating %s returned %d: %s", name, res.StatusCode(), apierr.Body(res.Body))
- }
-
- // The response is a union: a secret, or an approval request when a change policy
- // applies. A tenant has no policy unless a test adds one, so anything else means
- // the request took a path the test did not intend.
- created, err := res.JSON200.AsCreateSecretV4200JSONResponseBody0()
- if err != nil {
- tt.Fatalf("secret: creating %s returned an approval request, not a secret: %s", name, res.Body)
- }
- return Value{
- Value: created.Secret.SecretValue,
- Path: cfg.path,
- Version: created.Secret.Version,
- }
-}
-
-// Get reads a secret back, failing the test if it is not there.
-func Get(tt *testing.T, p *project.Project, env, name string, opts ...Option) Value {
- tt.Helper()
- v, err := TryGet(tt, p, env, name, opts...)
- if err != nil {
- tt.Fatalf("secret: %v", err)
- }
- return v
-}
-
-// TryGet is Get without failing, for asserting that a secret is absent.
-func TryGet(tt *testing.T, p *project.Project, env, name string, opts ...Option) (Value, error) {
- tt.Helper()
- cfg, client := resolve(p, opts)
-
- res, err := client.GetSecretByNameV4WithResponse(tt.Context(), name, &api.GetSecretByNameV4Params{
- ProjectId: p.ID,
- Environment: &env,
- SecretPath: &cfg.path,
- ViewSecretValue: new(api.GetSecretByNameV4ParamsViewSecretValue("true")),
- })
- if err != nil {
- return Value{}, err
- }
- if res.JSON200 == nil {
- return Value{}, fmt.Errorf("reading secret %s returned %d: %s", name, res.StatusCode(), apierr.Body(res.Body))
- }
- return Value{
- Value: res.JSON200.Secret.SecretValue,
- ValueHidden: res.JSON200.Secret.SecretValueHidden,
- Path: res.JSON200.Secret.SecretPath,
- Version: res.JSON200.Secret.Version,
- }, nil
-}
-
-// Delete removes a secret.
-func Delete(tt *testing.T, p *project.Project, env, name string, opts ...Option) {
- tt.Helper()
- cfg, client := resolve(p, opts)
-
- res, err := client.DeleteSecretV4WithResponse(tt.Context(), name, api.DeleteSecretV4JSONRequestBody{
- ProjectId: p.ID,
- Environment: env,
- SecretPath: &cfg.path,
- })
- if err != nil {
- tt.Fatalf("secret: deleting %s: %v", name, err)
- }
- if res.JSON200 == nil {
- tt.Fatalf("secret: deleting %s returned %d: %s", name, res.StatusCode(), apierr.Body(res.Body))
- }
-}
diff --git a/tests/fixture/secretmanager/secret.go b/tests/fixture/secretmanager/secret.go
new file mode 100644
index 0000000000..83f024ff3f
--- /dev/null
+++ b/tests/fixture/secretmanager/secret.go
@@ -0,0 +1,114 @@
+// Package secretmanager builds Secret Manager resources.
+package secretmanager
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/stretchr/testify/require"
+)
+
+// Secret is a narrowed read, since the generated response is a union. ValueHidden
+// matters: a hidden value reads as empty rather than as an error.
+type Secret struct {
+ Value string
+ ValueHidden bool
+ Path string
+ Version float32
+}
+
+type SecretOption func(*secretConfig)
+
+type secretConfig struct {
+ path string
+ as *harness.Principal
+}
+
+// WithPath places the secret somewhere other than the project root.
+func WithPath(p string) SecretOption { return func(c *secretConfig) { c.path = p } }
+
+// As acts as a principal other than the tenant administrator, which any test about
+// what a member may do needs.
+func As(p *harness.Principal) SecretOption { return func(c *secretConfig) { c.as = p } }
+
+func resolve(p *fixture.Project, opts []SecretOption) (secretConfig, *api.ClientWithResponses) {
+ cfg := secretConfig{path: "/"}
+ for _, o := range opts {
+ o(&cfg)
+ }
+ client := p.Tenant().Admin.API
+ if cfg.as != nil {
+ client = cfg.as.API
+ }
+ return cfg, client
+}
+
+func CreateSecret(tt *testing.T, p *fixture.Project, env, name, value string, opts ...SecretOption) Secret {
+ tt.Helper()
+ cfg, client := resolve(p, opts)
+
+ res, err := client.CreateSecretV4WithResponse(tt.Context(), name, api.CreateSecretV4JSONRequestBody{
+ ProjectId: p.ID,
+ Environment: env,
+ SecretPath: &cfg.path,
+ SecretValue: value,
+ })
+ require.NoErrorf(tt, err, "creating secret %s", name)
+ require.NotNilf(tt, res.JSON200, "creating secret %s returned %d: %s", name, res.StatusCode(), apierr.Body(res.Body))
+
+ // A union with an approval request; a tenant has no change policy unless a test
+ // adds one, so that branch means an unintended path.
+ created, err := res.JSON200.AsCreateSecretV4200JSONResponseBody0()
+ require.NoErrorf(tt, err, "creating secret %s returned an approval request: %s", name, res.Body)
+
+ return Secret{Value: created.Secret.SecretValue, Path: cfg.path, Version: created.Secret.Version}
+}
+
+func GetSecret(tt *testing.T, p *fixture.Project, env, name string, opts ...SecretOption) Secret {
+ tt.Helper()
+ s, err := TryGetSecret(tt, p, env, name, opts...)
+ require.NoError(tt, err)
+ return s
+}
+
+// TryGetSecret is GetSecret without failing, for asserting a secret is absent.
+func TryGetSecret(tt *testing.T, p *fixture.Project, env, name string, opts ...SecretOption) (Secret, error) {
+ tt.Helper()
+ cfg, client := resolve(p, opts)
+
+ res, err := client.GetSecretByNameV4WithResponse(tt.Context(), name, &api.GetSecretByNameV4Params{
+ ProjectId: p.ID,
+ Environment: &env,
+ SecretPath: &cfg.path,
+ ViewSecretValue: new(api.GetSecretByNameV4ParamsViewSecretValue("true")),
+ })
+ if err != nil {
+ return Secret{}, err
+ }
+ if res.JSON200 == nil {
+ return Secret{}, fmt.Errorf("reading secret %s returned %d: %s", name, res.StatusCode(), apierr.Body(res.Body))
+ }
+ return Secret{
+ Value: res.JSON200.Secret.SecretValue,
+ ValueHidden: res.JSON200.Secret.SecretValueHidden,
+ Path: res.JSON200.Secret.SecretPath,
+ Version: res.JSON200.Secret.Version,
+ }, nil
+}
+
+func DeleteSecret(tt *testing.T, p *fixture.Project, env, name string, opts ...SecretOption) {
+ tt.Helper()
+ cfg, client := resolve(p, opts)
+
+ res, err := client.DeleteSecretV4WithResponse(tt.Context(), name, api.DeleteSecretV4JSONRequestBody{
+ ProjectId: p.ID,
+ Environment: env,
+ SecretPath: &cfg.path,
+ })
+ require.NoErrorf(tt, err, "deleting secret %s", name)
+ require.NotNilf(tt, res.JSON200, "deleting secret %s returned %d: %s", name, res.StatusCode(), apierr.Body(res.Body))
+}
diff --git a/tests/go.mod b/tests/go.mod
index 5d89ab2a96..4c84cc2146 100644
--- a/tests/go.mod
+++ b/tests/go.mod
@@ -6,6 +6,7 @@ require (
github.com/google/uuid v1.6.0
github.com/moby/moby/api v1.55.0
github.com/oapi-codegen/runtime v1.7.0
+ github.com/stretchr/testify v1.11.1
github.com/testcontainers/testcontainers-go v0.44.0
golang.org/x/crypto v0.54.0
)
@@ -59,7 +60,6 @@ require (
github.com/sirupsen/logrus v1.9.4 // indirect
github.com/speakeasy-api/jsonpath v0.6.3 // indirect
github.com/speakeasy-api/openapi v1.24.0 // indirect
- github.com/stretchr/testify v1.11.1 // indirect
github.com/tklauser/go-sysconf v0.4.0 // indirect
github.com/tklauser/numcpus v0.12.0 // indirect
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
diff --git a/tests/harness/infisical/bootstrap_test.go b/tests/harness/infisical/bootstrap_test.go
index 3d91842438..34ade81688 100644
--- a/tests/harness/infisical/bootstrap_test.go
+++ b/tests/harness/infisical/bootstrap_test.go
@@ -7,63 +7,52 @@ import (
"github.com/Infisical/infisical/tests/infra"
"github.com/Infisical/infisical/tests/internal/spec"
"github.com/google/uuid"
+ "github.com/stretchr/testify/require"
)
func TestBootstrap(t *testing.T) {
requireDocker(t)
- spec.Why(t, `Bootstrap is the root of every principal the suite has. If it is wrong,
- nothing downstream can authenticate, and the failure surfaces as an unexplained 401
- in whichever test happens to run first.`)
+ spec.Why(t, `Bootstrap is the root of every principal. If it is wrong, the failure is
+ an unexplained 401 in whichever test runs first.`)
app := bootStack(t)
root, err := infisical.Bootstrap(t.Context(), app.BaseURL(infra.External))
- if err != nil {
- t.Fatalf("bootstrap: %v", err)
- }
+ require.NoError(t, err)
- t.Run("ok/yields an instance admin identity token", func(t *testing.T) {
- if root.IdentityToken == "" {
- t.Fatal("no identity token; instance-level suites have no principal")
- }
- if root.IdentityID == uuid.Nil {
- t.Error("identity has no id")
- }
+ t.Run("should yield an instance admin identity token", func(t *testing.T) {
+ require.NotEmpty(t, root.IdentityToken, "instance-level suites have no principal")
+ require.NotEqual(t, uuid.Nil, root.IdentityID)
})
- t.Run("ok/keeps the root user credentials", func(t *testing.T) {
- spec.Why(t, `POST /api/v2/organizations refuses any actor that is not a USER, so the
- identity token cannot mint tenants and the password is the only thing that can.`)
+ t.Run("should keep the root user credentials", func(t *testing.T) {
+ spec.Why(t, `Creating an organization refuses any actor that is not a user, so the
+ password is the only thing that can mint tenants.`)
- if root.Email == "" || root.Password == "" {
- t.Fatal("no root user credentials; NewTenant cannot create an organization")
- }
+ require.NotEmpty(t, root.Email)
+ require.NotEmpty(t, root.Password)
})
- t.Run("ok/signup is re-enabled", func(t *testing.T) {
- spec.Why(t, `bootstrapInstance sets allowSignUp:false on any non-cloud instance.
- Left off, there is no path to a second real user, which is the only way to get a
- non-administrator principal.`)
+ t.Run("should re-enable signup", func(t *testing.T) {
+ spec.Why(t, `Bootstrap disables signup on non-cloud instances, which would leave no
+ path to a non-administrator user.`)
+ // Action
st, err := app.Status(t.Context())
- if err != nil {
- t.Fatalf("status: %v", err)
- }
- if !st.SignupAllowed {
- t.Error("allowSignUp is still false")
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.True(t, st.SignupAllowed)
})
- t.Run("idempotent/bootstrapping an adopted instance logs in instead of failing", func(t *testing.T) {
- spec.Why(t, `admin/bootstrap is one shot per database, but a container is adopted by
- name, so the second test binary to arrive finds an instance already bootstrapped.
- That has to be recoverable or only the first binary in a run can work.`)
+ t.Run("should log in instead of failing when the instance is already bootstrapped", func(t *testing.T) {
+ spec.Why(t, `Bootstrap is one shot per database, but containers are adopted, so the
+ second binary in a run finds an instance already bootstrapped.`)
+ // Action
again, err := infisical.Bootstrap(t.Context(), app.BaseURL(infra.External))
- if err != nil {
- t.Fatalf("second bootstrap: %v", err)
- }
- if again.Email != root.Email {
- t.Errorf("adopted a different root: %q then %q", root.Email, again.Email)
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, root.Email, again.Email)
})
}
diff --git a/tests/harness/infisical/infisical_test.go b/tests/harness/infisical/infisical_test.go
index e19baa60bc..628d3216b8 100644
--- a/tests/harness/infisical/infisical_test.go
+++ b/tests/harness/infisical/infisical_test.go
@@ -12,6 +12,7 @@ import (
"github.com/Infisical/infisical/tests/infra/postgres"
"github.com/Infisical/infisical/tests/infra/redis"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
func requireDocker(t *testing.T) {
@@ -28,13 +29,9 @@ func bootStack(t *testing.T, opts ...infisical.Option) *infisical.Handle {
log := infra.NewLogger()
root, err := infra.RepoRoot()
- if err != nil {
- t.Fatalf("repo root: %v", err)
- }
+ require.NoError(t, err)
img, err := infisical.ResolveImage(ctx, root, log)
- if err != nil {
- t.Fatalf("image: %v", err)
- }
+ require.NoError(t, err)
mods := []infra.Module{postgres.Module(), redis.Module(), mailpit.Module(),
infisical.Module(append([]infisical.Option{infisical.WithImage(img)}, opts...)...)}
@@ -43,14 +40,10 @@ func bootStack(t *testing.T, opts ...infisical.Option) *infisical.Handle {
scopes[m.Key()] = infra.Shared
}
plan, err := infra.Resolve(mods, scopes)
- if err != nil {
- t.Fatalf("resolve: %v", err)
- }
+ require.NoError(t, err)
runner := infra.NewRunner(infra.Workspace(), log)
- if err := runner.Network(ctx, infra.NetworkName); err != nil {
- t.Fatalf("network: %v", err)
- }
+ require.NoError(t, runner.Network(ctx, infra.NetworkName))
handles := map[infra.Key]infra.Handle{}
for _, m := range plan.Modules() {
@@ -60,9 +53,7 @@ func bootStack(t *testing.T, opts ...infisical.Option) *infisical.Handle {
began := time.Now()
h, err := m.Start(ctx, infra.NewDeps(handles, infra.NetworkName, infra.Workspace(), name, runner, log))
- if err != nil {
- t.Fatalf("start %s: %v", m.Key(), err)
- }
+ require.NoErrorf(t, err, "starting %s", m.Key())
handles[m.Key()] = h
t.Cleanup(func() { _ = h.Stop(context.WithoutCancel(ctx)) })
log.Decision("ready", infra.ContainerName(name), h.Endpoint(infra.External), time.Since(began), "")
@@ -78,15 +69,11 @@ func TestInfisical_Boot(t *testing.T) {
app := bootStack(t)
- t.Run("ok/serves the API once Start returns", func(t *testing.T) {
- if app.BaseURL(infra.External) == "" {
- t.Fatal("no base URL")
- }
+ t.Run("should serve the API once Start returns", func(t *testing.T) {
+ require.NotEmpty(t, app.BaseURL(infra.External))
})
- t.Run("ok/the container name carries the image id", func(t *testing.T) {
- if app.Image().ShortID() == "" {
- t.Fatal("image has no id, so a code change would adopt a stale container")
- }
+ t.Run("should carry the image id so a code change cannot adopt a stale container", func(t *testing.T) {
+ require.NotEmpty(t, app.Image().ShortID())
})
}
diff --git a/tests/harnesstest/isolated/principals_test.go b/tests/harnesstest/isolated/principals_test.go
index ad62815097..f82fd96efb 100644
--- a/tests/harnesstest/isolated/principals_test.go
+++ b/tests/harnesstest/isolated/principals_test.go
@@ -7,43 +7,40 @@ import (
"github.com/Infisical/infisical/tests/clients/api"
"github.com/Infisical/infisical/tests/harness"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
func TestAdminPrincipals_AreSeparate(t *testing.T) {
- spec.Why(t, `The harness hands out two administrators and the whole Shared profile
- rests on them being different things. If a tenant administrator could write
- instance configuration, one test could disable signup or rotate the root key
- under every other package in the run, and the damage would surface somewhere
- else entirely.
-
- This has been wrong once: while the tenant administrator was the bootstrap root
- wearing an organization claim, the second case below failed.
-
- Isolated because the first case really does write instance configuration.`)
+ spec.Why(t, `If a tenant administrator could write instance configuration, one test
+ could disable signup under every other package. This was wrong once, when the
+ tenant admin was the bootstrap root. Isolated because the first case writes
+ instance configuration.`)
h := harness.From(t)
- t.Run("ok/the instance admin can write instance configuration", func(t *testing.T) {
- res, err := h.InstanceAdmin(t).API.UpdateAdminConfigWithResponse(t.Context(),
+ t.Run("should let the instance admin write instance configuration", func(t *testing.T) {
+ // Setup
+ admin := h.InstanceAdmin(t)
+
+ // Action
+ res, err := admin.API.UpdateAdminConfigWithResponse(t.Context(),
api.UpdateAdminConfigJSONRequestBody{AllowSignUp: new(true)})
- if err != nil {
- t.Fatalf("writing instance config: %v", err)
- }
- if res.StatusCode() != http.StatusOK {
- t.Fatalf("the instance admin was refused instance config: %d: %s", res.StatusCode(), res.Body)
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "refused: %s", res.Body)
})
- t.Run("forbidden/a tenant admin cannot", func(t *testing.T) {
+ t.Run("should refuse instance configuration when the caller is a tenant admin", func(t *testing.T) {
+ // Setup
tn := h.NewTenant(t)
+ // Action
res, err := tn.Admin.API.UpdateAdminConfigWithResponse(t.Context(),
api.UpdateAdminConfigJSONRequestBody{AllowSignUp: new(true)})
- if err != nil {
- t.Fatalf("writing instance config as a tenant admin: %v", err)
- }
- if res.StatusCode() == http.StatusOK {
- t.Fatal("a tenant administrator wrote instance configuration")
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.NotEqual(t, http.StatusOK, res.StatusCode(), "a tenant administrator wrote instance configuration")
})
}
diff --git a/tests/harnesstest/isolated/profile_test.go b/tests/harnesstest/isolated/profile_test.go
index 64bf62d6de..8f805dcdc9 100644
--- a/tests/harnesstest/isolated/profile_test.go
+++ b/tests/harnesstest/isolated/profile_test.go
@@ -4,17 +4,24 @@ import (
"testing"
"github.com/Infisical/infisical/tests/fakes/github"
- "github.com/Infisical/infisical/tests/fixture/appconnection"
+ "github.com/Infisical/infisical/tests/fixture"
"github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/spec"
"github.com/Infisical/infisical/tests/provider"
+ "github.com/stretchr/testify/require"
)
func TestIsolated_ReachesTheSharedFakenet(t *testing.T) {
+ spec.Why(t, `An Isolated package owns its Infisical but shares fakenet, which it must
+ still reach through the shared resolver address.`)
- conn := appconnection.New(t, harness.From(t).NewTenant(t), provider.GitHub)
- gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())
+ // Setup
+ tn := harness.From(t).NewTenant(t)
+
+ // Action
+ conn := fixture.NewAppConnection(t, tn, provider.GitHub)
- if n := gh.Received(t, "GET", "/user"); n != 1 {
- t.Fatalf("the credential check reached fakenet %d times, want 1", n)
- }
+ // Assert
+ gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())
+ require.Equal(t, 1, gh.Received(t, "GET", "/user"))
}
diff --git a/tests/harnesstest/shared/licensing_test.go b/tests/harnesstest/shared/licensing_test.go
index 8f945ec784..f00aadb4b9 100644
--- a/tests/harnesstest/shared/licensing_test.go
+++ b/tests/harnesstest/shared/licensing_test.go
@@ -10,28 +10,32 @@ import (
func TestLicense_PlanOptionReachesTheInstance(t *testing.T) {
t.Parallel()
- spec.Why(t, `Whether WithPlan registers a stub the application actually resolves.
- Verify reads the plan back with refreshCache=true, so a stub that was never
- reached, or was keyed on the wrong feature name, fails here rather than later as
- an unexplained 403 in a test about something else.`)
+ spec.Why(t, `Verify reads the plan back with refreshCache=true, so a plan keyed on
+ the wrong feature name fails here instead of as an unexplained 403 elsewhere.`)
- tn := harness.From(t).NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.RBAC)))
- tn.Verify(t, license.Enterprise().Without(license.RBAC))
+ // Setup
+ plan := license.Enterprise().Without(license.RBAC)
+
+ // Action
+ tn := harness.From(t).NewTenant(t, harness.WithPlan(plan))
+
+ // Assert
+ tn.Verify(t, plan)
}
func TestLicense_ResolvesPerTenant(t *testing.T) {
t.Parallel()
- spec.Why(t, `This one is a product behaviour the harness depends on rather than
- something the harness owns: getPlan resolves per organization only in Cloud
- instance type, and every other type short-circuits to one instance-wide feature
- set. It lives here because if it ever changes, per-tenant licensing stops being
- possible and the design has to change with it -- which is a harness problem, not
- a failing product test.`)
+ spec.Why(t, `getPlan resolves per organization only in Cloud mode. If that changes,
+ per-tenant licensing stops being possible, which is a harness problem.`)
+ // Setup
h := harness.From(t)
+
+ // Action
narrowed := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.RBAC)))
untouched := h.NewTenant(t)
+ // Assert
untouched.Verify(t, license.Enterprise())
narrowed.Verify(t, license.Enterprise().Without(license.RBAC))
}
diff --git a/tests/harnesstest/shared/principal_test.go b/tests/harnesstest/shared/principal_test.go
index eaaac7365c..8e692f47e0 100644
--- a/tests/harnesstest/shared/principal_test.go
+++ b/tests/harnesstest/shared/principal_test.go
@@ -7,72 +7,64 @@ import (
"github.com/Infisical/infisical/tests/clients/api"
"github.com/Infisical/infisical/tests/harness"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
func TestIdentity_HonoursItsOrgRole(t *testing.T) {
t.Parallel()
- spec.Why(t, `Not a claim about Infisical's RBAC, which has its own tests: this is
- whether the fixture's option is applied at all. An ignored OrgRole would make
- every identity an admin, and every authorization test written on top of one would
- pass without meaning anything. That has happened once already, with ProjectRole.
-
- Project creation rather than a read, because reading the plan only proves
- membership and no-access still has that.`)
+ spec.Why(t, `Whether the option is applied at all: an ignored OrgRole would make every
+ identity an admin and every authorization test vacuous. Project creation rather
+ than a read, because no-access still has membership.`)
+ // Setup
tn := harness.From(t).NewTenant(t)
- id := tn.NewIdentity(t, harness.OrgRole("no-access"))
+ identity := tn.NewIdentity(t, harness.OrgRole("no-access"))
- res, err := id.API.CreateProjectWithResponse(t.Context(), api.CreateProjectJSONRequestBody{
+ // Action
+ res, err := identity.API.CreateProjectWithResponse(t.Context(), api.CreateProjectJSONRequestBody{
ProjectName: "should-not-exist",
})
- if err != nil {
- t.Fatalf("creating a project as a no-access identity: %v", err)
- }
- if res.StatusCode() == http.StatusOK {
- t.Fatal("an identity created with OrgRole(no-access) could create a project")
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.NotEqual(t, http.StatusOK, res.StatusCode(), "a no-access identity created a project")
}
func TestUser_IsInvitedThroughMail(t *testing.T) {
t.Parallel()
h := harness.From(t)
- t.Run("ok/an invited user becomes a member", func(t *testing.T) {
+ t.Run("should make an invited user a member of the organization", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `Also the only proof that the harness can read a mailbox at all. The
- invite link comes back in the response only when SMTP is unconfigured, and the
- harness configures it on purpose, so the link has to be pulled out of Mailpit.
- Every email-driven flow rests on this working.`)
+ spec.Why(t, `The invite link only comes back in the response when SMTP is
+ unconfigured, so this also proves the harness can read a mailbox.`)
+ // Setup
tn := h.NewTenant(t)
+
+ // Action
alice := tn.NewUser(t, harness.WithName("alice"))
- if alice.Email != tn.Address("alice") {
- t.Errorf("user got mailbox %q, want %q", alice.Email, tn.Address("alice"))
- }
+ // Assert
+ require.Equal(t, tn.Address("alice"), alice.Email)
res, err := alice.API.GetOrganizationPlanWithResponse(t.Context(), tn.OrgID.String(), nil)
- if err != nil {
- t.Fatalf("reading the plan as the invited user: %v", err)
- }
- if res.StatusCode() != http.StatusOK {
- t.Fatalf("an invited user cannot reach the organization they joined: %d", res.StatusCode())
- }
+ require.NoError(t, err)
+ require.Equal(t, http.StatusOK, res.StatusCode(), "an invited user cannot reach the organization")
})
- t.Run("cross-tenant/two tenants can invite the same local part", func(t *testing.T) {
+ t.Run("should keep users apart when two tenants invite the same local part", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `Mail isolation is by address, not by server: one Mailpit serves the
- whole run. If the domains did not differ, two parallel tests inviting "alice"
- would read each other's invitation and both would pass or fail at random.`)
+ spec.Why(t, `One Mailpit serves the run, so mail isolation is by address. Equal
+ domains would let parallel tests read each other's invitations.`)
+ // Setup
a, b := h.NewTenant(t), h.NewTenant(t)
+
+ // Action
ua, ub := a.NewUser(t, harness.WithName("alice")), b.NewUser(t, harness.WithName("alice"))
- if ua.Email == ub.Email {
- t.Fatalf("both tenants issued %s", ua.Email)
- }
- if ua.Token == ub.Token {
- t.Fatal("two separately invited users share a session token")
- }
+ // Assert
+ require.NotEqual(t, ua.Email, ub.Email)
+ require.NotEqual(t, ua.Token, ub.Token, "two separately invited users share a session")
})
}
diff --git a/tests/harnesstest/shared/stubbing_test.go b/tests/harnesstest/shared/stubbing_test.go
index 9c09d7d78a..a8996d0333 100644
--- a/tests/harnesstest/shared/stubbing_test.go
+++ b/tests/harnesstest/shared/stubbing_test.go
@@ -5,63 +5,64 @@ import (
"testing"
"github.com/Infisical/infisical/tests/fakes/github"
- "github.com/Infisical/infisical/tests/fixture/appconnection"
+ "github.com/Infisical/infisical/tests/fixture"
"github.com/Infisical/infisical/tests/harness"
"github.com/Infisical/infisical/tests/internal/spec"
"github.com/Infisical/infisical/tests/provider"
+ "github.com/stretchr/testify/require"
)
func TestOutbound_IsIntercepted(t *testing.T) {
t.Parallel()
h := harness.From(t)
- t.Run("ok/an outbound call reaches the fake", func(t *testing.T) {
+ t.Run("should reach the fake when the product calls a hardcoded host", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `The one test the whole design rests on. The connection is created with
- no host, so GitHub's client resolves api.github.com, and the only way that
- request can arrive here is fakenet answering DNS and presenting a certificate
- the instance was told to trust. If it stops passing, no integration test
- anywhere is testing anything real.`)
+ spec.Why(t, `The design rests on this: with no host configured, the only way the
+ call arrives is fakenet answering DNS with a certificate the instance trusts.`)
- conn := appconnection.New(t, h.NewTenant(t), provider.GitHub)
- gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())
+ // Setup
+ tn := h.NewTenant(t)
- if n := gh.Received(t, "GET", "/user"); n != 1 {
- t.Fatalf("the credential check reached the fake %d times, want 1", n)
- }
+ // Action
+ conn := fixture.NewAppConnection(t, tn, provider.GitHub)
+
+ // Assert
+ gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())
+ require.Equal(t, 1, gh.Received(t, "GET", "/user"))
})
- t.Run("cross-tenant/two connections to one service stay separate", func(t *testing.T) {
+ t.Run("should keep connections apart when two use the same service", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `One fakenet serves every tenant, so isolation is by credential rather
- than by server. Each connection authenticates with its own, and state is held
- under it, which is why no org id has to be threaded anywhere.`)
+ spec.Why(t, `One fakenet serves every tenant, so isolation is by credential.`)
+
+ // Setup
+ tenantA, tenantB := h.NewTenant(t), h.NewTenant(t)
- a := appconnection.New(t, h.NewTenant(t), provider.GitHub)
- b := appconnection.New(t, h.NewTenant(t), provider.GitHub)
+ // Action
+ a := fixture.NewAppConnection(t, tenantA, provider.GitHub)
+ b := fixture.NewAppConnection(t, tenantB, provider.GitHub)
- // Both created a connection, so both made the same call to the same path.
- for name, conn := range map[string]*appconnection.Connection{"a": a, "b": b} {
+ // Assert
+ for _, conn := range []*fixture.AppConnection{a, b} {
gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())
- if n := gh.Received(t, "GET", "/user"); n != 1 {
- t.Errorf("connection %s counted %d requests, want only its own 1", name, n)
- }
+ require.Equal(t, 1, gh.Received(t, "GET", "/user"), "a connection counted another's requests")
}
})
- t.Run("invalid/what the fake answers is load bearing", func(t *testing.T) {
+ t.Run("should refuse the connection when the fake rejects the credential", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `The interception test above proves a request arrived. On its own that
- is not enough: if the application ignored the response, every value a test
- asserts on would be decoration. Changing the answer has to change the outcome.
- The refusal is a fakenet rule registered against the credential before the
- connection exists, which doubles as the failure-injection path.`)
+ spec.Why(t, `Proves the answer matters, not just that a request arrived. Also the
+ failure-injection path: a rule registered before the connection exists.`)
- _, err := appconnection.Try(t, h.NewTenant(t), provider.GitHub,
- appconnection.RejectCredentials(http.StatusUnauthorized))
- if err == nil {
- t.Fatal("the connection was created even though the credential check was refused")
- }
- })
+ // Setup
+ tn := h.NewTenant(t)
+ // Action
+ _, err := fixture.TryAppConnection(t, tn, provider.GitHub,
+ fixture.RejectCredentials(http.StatusUnauthorized))
+
+ // Assert
+ require.Error(t, err, "the connection was created despite a refused credential check")
+ })
}
diff --git a/tests/harnesstest/shared/tenancy_test.go b/tests/harnesstest/shared/tenancy_test.go
index 0f80dcc1b2..49c3c986b2 100644
--- a/tests/harnesstest/shared/tenancy_test.go
+++ b/tests/harnesstest/shared/tenancy_test.go
@@ -5,21 +5,21 @@ import (
"github.com/Infisical/infisical/tests/harness"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
func TestTenant_IsIsolated(t *testing.T) {
t.Parallel()
- spec.Why(t, `Slugs matter as much as ids here. A tenant's mail domain is derived from
- its slug, so two tenants sharing one would read each other's invitations, and the
- address-based isolation every email flow relies on would silently stop working.`)
+ spec.Why(t, `A tenant's mail domain derives from its slug, so a shared slug would
+ break address-based mail isolation silently.`)
+ // Setup
h := harness.From(t)
+
+ // Action
a, b := h.NewTenant(t), h.NewTenant(t)
- if a.OrgID == b.OrgID {
- t.Fatal("two tenants share an organization, so nothing is isolated")
- }
- if a.OrgSlug == b.OrgSlug {
- t.Errorf("two tenants share a slug (%s), so their mail domains collide", a.OrgSlug)
- }
+ // Assert
+ require.NotEqual(t, a.OrgID, b.OrgID)
+ require.NotEqual(t, a.OrgSlug, b.OrgSlug)
}
diff --git a/tests/infra/fakenet/events_test.go b/tests/infra/fakenet/events_test.go
index 082136a1d6..3da6bf19e3 100644
--- a/tests/infra/fakenet/events_test.go
+++ b/tests/infra/fakenet/events_test.go
@@ -9,6 +9,8 @@ import (
"strings"
"testing"
"time"
+
+ "github.com/stretchr/testify/require"
)
const testHost = "items.test"
@@ -57,9 +59,7 @@ func newRig(t *testing.T, prefix string) *rig {
t.Helper()
srv := New(itemService{})
ca, err := LoadOrCreateCA(filepath.Join(t.TempDir(), "ca.pem"))
- if err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, err)
fakes := httptest.NewServer(srv)
admin := httptest.NewServer(srv.Admin(ca))
t.Cleanup(fakes.Close)
@@ -67,24 +67,18 @@ func newRig(t *testing.T, prefix string) *rig {
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
- if err := Listen(ctx, admin.URL, prefix); err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, Listen(ctx, admin.URL, prefix))
return &rig{fakes: fakes, admin: admin.URL}
}
func (r *rig) call(t *testing.T, method, key, name string) {
t.Helper()
req, err := http.NewRequestWithContext(t.Context(), method, r.fakes.URL+"/items/"+name, nil)
- if err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, err)
req.Host = testHost
req.Header.Set("Authorization", "Bearer "+key)
res, err := http.DefaultClient.Do(req)
- if err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, err)
_ = res.Body.Close()
}
@@ -114,18 +108,21 @@ func expectErr[E Event](t *testing.T, sc *Scope[struct{}], match func(E) bool, o
}
func TestEvents_Expect(t *testing.T) {
- t.Run("ok/an event that already happened is found", func(t *testing.T) {
+ t.Run("should find an event that already happened", func(t *testing.T) {
+ // Setup
r := newRig(t, "p1")
sc := r.scope(t, "p1-a")
r.call(t, http.MethodPost, "p1-a", "DB_URL")
+ // Action
got := sc.ExpectEvent[ItemCreated](t, nameIs[ItemCreated]("DB_URL"))
- if got.Name != "DB_URL" {
- t.Errorf("got %q", got.Name)
- }
+
+ // Assert
+ require.Equal(t, "DB_URL", got.Name)
})
- t.Run("ok/an event that arrives while waiting is found", func(t *testing.T) {
+ t.Run("should find an event that arrives while waiting", func(t *testing.T) {
+ // Setup
r := newRig(t, "p2")
sc := r.scope(t, "p2-a")
go func() {
@@ -137,63 +134,76 @@ func TestEvents_Expect(t *testing.T) {
_ = res.Body.Close()
}
}()
+
+ // Action + Assert: ExpectEvent fails the test if the event never arrives.
sc.ExpectEvent[ItemCreated](t, nameIs[ItemCreated]("LATE"))
})
- t.Run("invalid/each event satisfies one expectation", func(t *testing.T) {
+ t.Run("should need a second occurrence when the same event is expected twice", func(t *testing.T) {
+ // Setup
r := newRig(t, "p3")
sc := r.scope(t, "p3-a")
r.call(t, http.MethodPost, "p3-a", "ONCE")
-
sc.ExpectEvent[ItemCreated](t, nameIs[ItemCreated]("ONCE"))
+
+ // Action
err := expectErr(t, sc, nameIs[ItemCreated]("ONCE"), Within(300*time.Millisecond))
- if err == nil || !strings.Contains(err.Error(), "already claimed") {
- t.Fatalf("a second expectation reused the event or misreported it: %v", err)
- }
+
+ // Assert
+ require.ErrorContains(t, err, "already claimed")
})
- t.Run("ok/different types do not depend on order", func(t *testing.T) {
+ t.Run("should not depend on order when the events differ in type", func(t *testing.T) {
+ // Setup
r := newRig(t, "p4")
sc := r.scope(t, "p4-a")
r.call(t, http.MethodPost, "p4-a", "X")
r.call(t, http.MethodDelete, "p4-a", "X")
+ // Action + Assert
sc.ExpectEvent[ItemDeleted](t, nil)
sc.ExpectEvent[ItemCreated](t, nil)
})
- t.Run("invalid/since ignores what happened before the mark", func(t *testing.T) {
+ t.Run("should ignore events before the mark when Since is given", func(t *testing.T) {
+ // Setup
r := newRig(t, "p5")
sc := r.scope(t, "p5-a")
r.call(t, http.MethodPost, "p5-a", "X")
mark := sc.Mark(t)
- if err := expectErr[ItemCreated](t, sc, nil, Since(mark), Within(300*time.Millisecond)); err == nil {
- t.Fatal("an event before the mark satisfied an expectation since it")
- }
+ // Action
+ before := expectErr[ItemCreated](t, sc, nil, Since(mark), Within(300*time.Millisecond))
r.call(t, http.MethodPost, "p5-a", "X")
+
+ // Assert
+ require.Error(t, before, "an event before the mark satisfied an expectation since it")
sc.ExpectEvent[ItemCreated](t, nil, Since(mark))
})
- t.Run("cross-tenant/one credential never sees another's events", func(t *testing.T) {
+ t.Run("should not deliver an event when it belongs to another credential", func(t *testing.T) {
+ // Setup
r := newRig(t, "p6")
mine, theirs := r.scope(t, "p6-a"), r.scope(t, "p6-b")
+
+ // Action
r.call(t, http.MethodPost, "p6-b", "THEIRS")
+ // Assert
theirs.ExpectEvent[ItemCreated](t, nil)
- if err := expectErr[ItemCreated](t, mine, nil, Within(300*time.Millisecond)); err == nil {
- t.Fatal("an event published under another credential was delivered to this one")
- }
+ require.Error(t, expectErr[ItemCreated](t, mine, nil, Within(300*time.Millisecond)))
})
- t.Run("ok/the stream only carries this binary's prefix", func(t *testing.T) {
+ t.Run("should not stream an event when it is outside this binary's prefix", func(t *testing.T) {
+ // Setup
r := newRig(t, "p7")
foreign := r.scope(t, "other-a")
+
+ // Action
r.call(t, http.MethodPost, "other-a", "X")
- if err := expectErr[ItemCreated](t, foreign, nil, Within(300*time.Millisecond)); err == nil {
- t.Fatal("an event outside this binary's prefix reached it")
- }
+ // Assert
+ require.Error(t, expectErr[ItemCreated](t, foreign, nil, Within(300*time.Millisecond)))
})
}
@@ -203,30 +213,37 @@ func TestEvents_ExpectNo(t *testing.T) {
return expectNoEvent[ItemCreated](st, b, sc.key, newWaitConfig(300*time.Millisecond, nil), nil)
}
- t.Run("ok/nothing published passes", func(t *testing.T) {
+ t.Run("should pass when nothing is published", func(t *testing.T) {
+ // Setup
r := newRig(t, "n1")
- if err := expectNoErr(t, r.scope(t, "n1-a")); err != nil {
- t.Fatal(err)
- }
+
+ // Action + Assert
+ require.NoError(t, expectNoErr(t, r.scope(t, "n1-a")))
})
- t.Run("invalid/an unused matching event fails", func(t *testing.T) {
+ t.Run("should fail when an unused matching event exists", func(t *testing.T) {
+ // Setup
r := newRig(t, "n2")
sc := r.scope(t, "n2-a")
+
+ // Action
r.call(t, http.MethodPost, "n2-a", "X")
- if err := expectNoErr(t, sc); err == nil {
- t.Fatal("ExpectNoEvent passed with a matching event present")
- }
+
+ // Assert
+ require.Error(t, expectNoErr(t, sc))
})
- t.Run("ok/an event already claimed is accounted for", func(t *testing.T) {
+ t.Run("should pass when the matching event was already claimed", func(t *testing.T) {
+ // Setup
r := newRig(t, "n3")
sc := r.scope(t, "n3-a")
r.call(t, http.MethodPost, "n3-a", "X")
+
+ // Action
sc.ExpectEvent[ItemCreated](t, nil)
- if err := expectNoErr(t, sc); err != nil {
- t.Fatalf("a claimed event failed ExpectNoEvent: %v", err)
- }
+
+ // Assert
+ require.NoError(t, expectNoErr(t, sc))
})
}
@@ -236,48 +253,56 @@ func TestEvents_Failure(t *testing.T) {
do func(r *rig, t *testing.T)
want string
}{
- {"nothing arrived", func(*rig, *testing.T) {}, "no events arrived in this scope"},
- {"something else arrived", func(r *rig, t *testing.T) { r.call(t, http.MethodDelete, "f-a", "X") }, "no items.item-created arrived"},
- {"rejected by the predicate", func(r *rig, t *testing.T) { r.call(t, http.MethodPost, "f-a", "WRONG") }, "none matched"},
+ {"should say nothing arrived when the scope is empty", func(*rig, *testing.T) {}, "no events arrived in this scope"},
+ {"should list other events when only a different type arrived", func(r *rig, t *testing.T) { r.call(t, http.MethodDelete, "f-a", "X") }, "no items.item-created arrived"},
+ {"should list near misses when the predicate rejected them", func(r *rig, t *testing.T) { r.call(t, http.MethodPost, "f-a", "WRONG") }, "none matched"},
}
for _, tc := range cases {
- t.Run("invalid/"+tc.name+" is reported as such", func(t *testing.T) {
+ t.Run(tc.name, func(t *testing.T) {
+ // Setup
r := newRig(t, "f")
sc := r.scope(t, "f-a")
tc.do(r, t)
+ // Action
err := expectErr(t, sc, nameIs[ItemCreated]("RIGHT"), Within(500*time.Millisecond))
- if err == nil || !strings.Contains(err.Error(), tc.want) {
- t.Fatalf("message does not say %q:\n%v", tc.want, err)
- }
+
+ // Assert
+ require.ErrorContains(t, err, tc.want)
})
}
}
func TestEvents_Loss(t *testing.T) {
- t.Run("invalid/overflow fails rather than dropping silently", func(t *testing.T) {
+ t.Run("should fail rather than drop silently when a buffer overflows", func(t *testing.T) {
+ // Setup
st := &stream{buffers: map[scopeID]*buffer{}}
b := &buffer{changed: make(chan struct{})}
st.buffers[scopeID{testHost, "k"}] = b
+
+ // Action
for i := range bufferCap + 1 {
st.deliver(EventRecord{Seq: uint64(i + 1), Host: testHost, Scope: "k", Event: "items.item-created", Details: []byte(`{}`)})
}
+
+ // Assert
_, err := expectEvent[ItemDeleted](st, b, "k", waitConfig{within: time.Second}, nil)
- if err == nil || !strings.Contains(err.Error(), "were not kept") {
- t.Fatalf("overflow was not reported: %v", err)
- }
+ require.ErrorContains(t, err, "were not kept")
})
- t.Run("invalid/resuming past retained history is a gap", func(t *testing.T) {
+ t.Run("should report a gap when resuming past retained history", func(t *testing.T) {
+ // Setup
l := newEventLog()
+
+ // Action
for range historyCap + 10 {
l.append(EventRecord{Scope: "k"})
}
- if _, gap, _ := l.since(1); !gap {
- t.Fatal("resuming from before retained history did not report a gap")
- }
- if _, gap, _ := l.since(l.current()); gap {
- t.Fatal("resuming from the latest event reported a gap")
- }
+
+ // Assert
+ _, early, _ := l.since(1)
+ _, latest, _ := l.since(l.current())
+ require.True(t, early, "resuming from before retained history did not report a gap")
+ require.False(t, latest, "resuming from the latest event reported a gap")
})
}
diff --git a/tests/infra/lock_test.go b/tests/infra/lock_test.go
index d4cdf03699..0840b427a6 100644
--- a/tests/infra/lock_test.go
+++ b/tests/infra/lock_test.go
@@ -11,6 +11,7 @@ import (
"github.com/Infisical/infisical/tests/infra"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
func TestLock_SerializesAcrossProcesses(t *testing.T) {
@@ -24,9 +25,7 @@ func TestLock_SerializesAcrossProcesses(t *testing.T) {
// Child: hold the lock briefly and append a start/end pair. Overlapping
// pairs in the file mean the lock did not hold.
release, err := infra.Lock("locktest")
- if err != nil {
- t.Fatalf("lock: %v", err)
- }
+ require.NoError(t, err)
defer release()
path := os.Getenv("INFRA_LOCK_FILE")
@@ -36,8 +35,12 @@ func TestLock_SerializesAcrossProcesses(t *testing.T) {
return
}
+ // Setup
record := filepath(t)
+
+ // Action
var wg sync.WaitGroup
+ failures := make(chan string, workers)
for range workers {
wg.Add(1)
go func() {
@@ -45,36 +48,35 @@ func TestLock_SerializesAcrossProcesses(t *testing.T) {
cmd := exec.Command(os.Args[0], "-test.run", "^TestLock_SerializesAcrossProcesses$")
cmd.Env = append(os.Environ(), "INFRA_LOCK_CHILD=1", "INFRA_LOCK_FILE="+record)
if out, err := cmd.CombinedOutput(); err != nil {
- t.Errorf("child failed: %v\n%s", err, out)
+ failures <- err.Error() + "\n" + string(out)
}
}()
}
wg.Wait()
+ close(failures)
+ // Assert
+ for f := range failures {
+ require.Fail(t, "a child process failed", f)
+ }
lines := strings.Fields(strings.ReplaceAll(readFile(t, record), "\n", " "))
depth := 0
for i := 0; i < len(lines); i += 2 {
switch lines[i] {
case "start":
depth++
- if depth > 1 {
- t.Fatalf("two processes held the lock at once:\n%s", readFile(t, record))
- }
+ require.LessOrEqualf(t, depth, 1, "two processes held the lock at once:\n%s", readFile(t, record))
case "end":
depth--
}
}
- if got := strings.Count(readFile(t, record), "start"); got != workers {
- t.Fatalf("expected %d critical sections, got %d", workers, got)
- }
+ require.Equal(t, workers, strings.Count(readFile(t, record), "start"))
}
func filepath(t *testing.T) string {
t.Helper()
f, err := os.CreateTemp("", "inf-locktest-*")
- if err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, err)
name := f.Name()
_ = f.Close()
t.Cleanup(func() { _ = os.Remove(name) })
@@ -84,20 +86,15 @@ func filepath(t *testing.T) string {
func appendLine(t *testing.T, path, line string) {
t.Helper()
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o644)
- if err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, err)
defer func() { _ = f.Close() }()
- if _, err := f.WriteString(line + "\n"); err != nil {
- t.Fatal(err)
- }
+ _, err = f.WriteString(line + "\n")
+ require.NoError(t, err)
}
func readFile(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
+ require.NoError(t, err)
return string(b)
}
diff --git a/tests/infra/logs_test.go b/tests/infra/logs_test.go
index 10d1362347..19f594cbd2 100644
--- a/tests/infra/logs_test.go
+++ b/tests/infra/logs_test.go
@@ -2,12 +2,12 @@ package infra_test
import (
"os"
- "strings"
"testing"
"time"
"github.com/Infisical/infisical/tests/infra"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
func TestRunner_FailedStartupCarriesContainerOutput(t *testing.T) {
@@ -18,12 +18,13 @@ func TestRunner_FailedStartupCarriesContainerOutput(t *testing.T) {
no evidence. Only a deliberately failing container exercises this, so a passing suite
never covers it.`)
+ // Setup
ctx := t.Context()
runner := infra.NewRunner(infra.Workspace(), infra.NewLogger())
- if err := runner.Network(ctx, infra.NetworkName); err != nil {
- t.Fatalf("network: %v", err)
- }
+ require.NoError(t, runner.Network(ctx, infra.NetworkName))
+ t.Cleanup(func() { _ = os.RemoveAll(infra.LogDir) })
+ // Action
const marker = "harness-log-capture-marker"
_, err := runner.Run(ctx, infra.ContainerSpec{
Name: infra.ContainerName(infra.NameParts{Scope: infra.Test, ScopeID: "logcap", Module: "alpine"}),
@@ -34,16 +35,9 @@ func TestRunner_FailedStartupCarriesContainerOutput(t *testing.T) {
Ready: infra.ForListeningPort("9999/tcp"),
StartupTimeout: 8 * time.Second,
})
- if err == nil {
- t.Fatal("expected the container to fail its wait strategy")
- }
-
- if !strings.Contains(err.Error(), marker) {
- t.Errorf("error does not carry the container's output, so a real failure would be undiagnosable.\ngot: %v", err)
- }
- if !strings.Contains(err.Error(), "full output:") {
- t.Errorf("error does not point at the captured log file.\ngot: %v", err)
- }
- t.Cleanup(func() { _ = os.RemoveAll(infra.LogDir) })
+ // Assert
+ require.Error(t, err, "the container should fail its wait strategy")
+ require.Contains(t, err.Error(), marker, "the error does not carry the container's output")
+ require.Contains(t, err.Error(), "full output:", "the error does not point at the captured log")
}
diff --git a/tests/infra/module_test.go b/tests/infra/module_test.go
index c5ae700fe6..83cff1bd97 100644
--- a/tests/infra/module_test.go
+++ b/tests/infra/module_test.go
@@ -2,10 +2,10 @@ package infra
import (
"context"
- "strings"
"testing"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
type fakeModule struct {
@@ -29,8 +29,10 @@ func mods(m ...Module) []Module { return m }
func TestResolve(t *testing.T) {
t.Parallel()
- t.Run("ok/orders dependencies before dependents", func(t *testing.T) {
+ t.Run("should order dependencies before dependents", func(t *testing.T) {
t.Parallel()
+
+ // Action
plan, err := Resolve(
mods(
fakeModule{key: "infisical", requires: []Key{"postgres", "redis"}},
@@ -39,65 +41,64 @@ func TestResolve(t *testing.T) {
),
map[Key]Scope{"infisical": Shared, "postgres": Shared, "redis": Shared},
)
- if err != nil {
- t.Fatalf("Resolve() = %v", err)
- }
+
+ // Assert
+ require.NoError(t, err)
got := keysOf(plan.Modules())
- if got[len(got)-1] != "infisical" {
- t.Fatalf("infisical must start last, got order %v", got)
- }
+ require.Equal(t, Key("infisical"), got[len(got)-1], "infisical must start last")
})
- t.Run("ok/an optional dependency that is absent is not an error", func(t *testing.T) {
+ t.Run("should accept an optional dependency that is absent", func(t *testing.T) {
t.Parallel()
+
+ // Action
_, err := Resolve(
- mods(fakeModule{key: "infisical", optional: []Key{"wiremock"}}),
+ mods(fakeModule{key: "infisical", optional: []Key{"fakenet"}}),
map[Key]Scope{"infisical": Shared},
)
- if err != nil {
- t.Fatalf("Resolve() = %v", err)
- }
+
+ // Assert
+ require.NoError(t, err)
})
- t.Run("invalid/a missing required dependency fails before any container starts", func(t *testing.T) {
+ t.Run("should fail before any container starts when a required dependency is missing", func(t *testing.T) {
t.Parallel()
+
+ // Action
_, err := Resolve(
mods(fakeModule{key: "infisical", requires: []Key{"postgres"}}),
map[Key]Scope{"infisical": Shared},
)
- if err == nil {
- t.Fatal("expected an error")
- }
- if !strings.Contains(err.Error(), "requires postgres") {
- t.Fatalf("error should name the missing module, got: %v", err)
- }
+
+ // Assert
+ require.ErrorContains(t, err, "requires postgres")
})
- t.Run("invalid/a module may not depend on something shorter lived", func(t *testing.T) {
+ t.Run("should refuse a module that depends on something shorter lived", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `A Shared Infisical takes HTTP_PROXY at container start. Pointing it at a
- Package-scoped WireMock breaks every other package the moment that one finishes.
- This is the shape the first draft of the design had, which is why it is checked.`)
+ spec.Why(t, `A shared container reads its configuration once at start, so it cannot
+ point at a package-scoped one that dies when that package finishes.`)
+ // Action
_, err := Resolve(
mods(
- fakeModule{key: "infisical", optional: []Key{"wiremock"}},
- fakeModule{key: "wiremock"},
+ fakeModule{key: "infisical", optional: []Key{"fakenet"}},
+ fakeModule{key: "fakenet"},
),
- map[Key]Scope{"infisical": Shared, "wiremock": Package},
+ map[Key]Scope{"infisical": Shared, "fakenet": Package},
)
- if err == nil {
- t.Fatal("expected an error")
- }
- for _, want := range []string{"infisical is shared-scoped", "wiremock which is pkg-scoped", "Either widen"} {
- if !strings.Contains(err.Error(), want) {
- t.Fatalf("error should contain %q, got: %v", want, err)
- }
+
+ // Assert
+ require.Error(t, err)
+ for _, want := range []string{"infisical is shared-scoped", "fakenet which is pkg-scoped", "Either widen"} {
+ require.ErrorContains(t, err, want)
}
})
- t.Run("ok/a package scoped module may depend on a shared one", func(t *testing.T) {
+ t.Run("should allow a package-scoped module to depend on a shared one", func(t *testing.T) {
t.Parallel()
+
+ // Action
_, err := Resolve(
mods(
fakeModule{key: "infisical", optional: []Key{"mailpit"}},
@@ -105,24 +106,28 @@ func TestResolve(t *testing.T) {
),
map[Key]Scope{"infisical": Package, "mailpit": Shared},
)
- if err != nil {
- t.Fatalf("Resolve() = %v", err)
- }
+
+ // Assert
+ require.NoError(t, err)
})
- t.Run("invalid/the same module declared twice points at Named", func(t *testing.T) {
+ t.Run("should point at Named when the same module is declared twice", func(t *testing.T) {
t.Parallel()
+
+ // Action
_, err := Resolve(
mods(fakeModule{key: "postgres"}, fakeModule{key: "postgres"}),
map[Key]Scope{"postgres": Shared},
)
- if err == nil || !strings.Contains(err.Error(), "Named()") {
- t.Fatalf("error should point at Named(), got: %v", err)
- }
+
+ // Assert
+ require.ErrorContains(t, err, "Named()")
})
- t.Run("invalid/a dependency cycle is reported with its path", func(t *testing.T) {
+ t.Run("should report a dependency cycle", func(t *testing.T) {
t.Parallel()
+
+ // Action
_, err := Resolve(
mods(
fakeModule{key: "a", requires: []Key{"b"}},
@@ -130,9 +135,9 @@ func TestResolve(t *testing.T) {
),
map[Key]Scope{"a": Shared, "b": Shared},
)
- if err == nil || !strings.Contains(err.Error(), "cycle") {
- t.Fatalf("expected a cycle error, got: %v", err)
- }
+
+ // Assert
+ require.ErrorContains(t, err, "cycle")
})
}
@@ -142,18 +147,16 @@ func TestDepsGet(t *testing.T) {
type pgHandle struct{ Handle }
deps := Deps{handles: map[Key]Handle{"postgres": pgHandle{}}}
- t.Run("ok/a declared module comes back typed", func(t *testing.T) {
+ t.Run("should return a declared module typed", func(t *testing.T) {
t.Parallel()
- if _, ok := deps.Get[pgHandle]("postgres"); !ok {
- t.Fatal("declared module was not found")
- }
+ _, ok := deps.Get[pgHandle]("postgres")
+ require.True(t, ok)
})
- t.Run("notfound/an absent optional module reports false rather than panicking", func(t *testing.T) {
+ t.Run("should report false rather than panic when a module is absent", func(t *testing.T) {
t.Parallel()
- if _, ok := deps.Get[pgHandle]("redis"); ok {
- t.Fatal("absent module reported as present")
- }
+ _, ok := deps.Get[pgHandle]("redis")
+ require.False(t, ok)
})
}
diff --git a/tests/infra/names_test.go b/tests/infra/names_test.go
index f9dc0b8444..0dcbb4b25a 100644
--- a/tests/infra/names_test.go
+++ b/tests/infra/names_test.go
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
func TestContainerName(t *testing.T) {
@@ -15,41 +16,39 @@ func TestContainerName(t *testing.T) {
want string
}{
{
- name: "ok/shared module has no scope id",
+ name: "should omit the scope id when shared",
in: NameParts{Scope: Shared, Module: "postgres"},
want: "inf-shared-postgres",
},
{
- name: "ok/a Named instance is distinct from the default",
+ name: "should differ from the default when the instance is named",
in: NameParts{Scope: Shared, Module: "postgres", Instance: "rotation"},
want: "inf-shared-postgres-rotation",
},
{
- name: "ok/infisical carries its image id",
+ name: "should carry the image id when one is fingerprinted",
in: NameParts{Scope: Shared, Module: "infisical", Fingerprint: "9f8e7d6c"},
want: "inf-shared-infisical-9f8e7d6c",
},
{
- name: "ok/package scope is qualified by package path",
+ name: "should qualify by package path when package scoped",
in: NameParts{Scope: Package, ScopeID: "suites/instance", Module: "postgres"},
want: "inf-pkg-suites-instance-postgres",
},
{
- name: "ok/test scope carries a unique id",
+ name: "should carry a unique id when test scoped",
in: NameParts{Scope: Test, ScopeID: "a1b2", Module: "infisical"},
want: "inf-test-a1b2-infisical",
},
{
- name: "ok/unsafe characters fold to hyphens",
+ name: "should fold unsafe characters to hyphens",
in: NameParts{Scope: Package, ScopeID: "Suites/PKI v2", Module: "postgres"},
want: "inf-pkg-suites-pki-v2-postgres",
},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
- if got := ContainerName(tc.in); got != tc.want {
- t.Fatalf("ContainerName() = %q, want %q", got, tc.want)
- }
+ require.Equal(t, tc.want, ContainerName(tc.in))
})
}
}
@@ -69,8 +68,6 @@ func TestContainerName_ScopesDoNotCollide(t *testing.T) {
pkgB := postgres(Package, "suites/sso")
for _, pair := range [][2]string{{shared, pkgA}, {shared, pkgB}, {pkgA, pkgB}} {
- if pair[0] == pair[1] {
- t.Errorf("names collide: %q", pair[0])
- }
+ require.NotEqual(t, pair[0], pair[1])
}
}
diff --git a/tests/infra/postgres/postgres_test.go b/tests/infra/postgres/postgres_test.go
index 06f41c3bf4..fca596751b 100644
--- a/tests/infra/postgres/postgres_test.go
+++ b/tests/infra/postgres/postgres_test.go
@@ -8,6 +8,7 @@ import (
"github.com/Infisical/infisical/tests/infra"
"github.com/Infisical/infisical/tests/infra/postgres"
+ "github.com/stretchr/testify/require"
)
// These need Docker. Skipped when INFRA_DOCKER_TESTS is unset so `make test-unit`
@@ -24,9 +25,7 @@ func start(t *testing.T, opts ...postgres.Option) *postgres.Handle {
ctx := t.Context()
log := infra.NewLogger()
runner := infra.NewRunner(infra.Workspace(), log)
- if err := runner.Network(ctx, infra.NetworkName); err != nil {
- t.Fatalf("network: %v", err)
- }
+ require.NoError(t, runner.Network(ctx, infra.NetworkName))
m := postgres.Module(opts...)
name := m.Name()
@@ -35,9 +34,7 @@ func start(t *testing.T, opts ...postgres.Option) *postgres.Handle {
began := time.Now()
h, err := m.Start(ctx, infra.NewDeps(nil, infra.NetworkName, infra.Workspace(), name, runner, log))
- if err != nil {
- t.Fatalf("start: %v", err)
- }
+ require.NoError(t, err)
pg := h.(*postgres.Handle)
log.Decision("create", infra.ContainerName(name), pg.Endpoint(infra.External), time.Since(began), "")
t.Cleanup(func() { _ = pg.Stop(context.WithoutCancel(ctx)) })
@@ -48,42 +45,41 @@ func TestPostgres_Start(t *testing.T) {
requireDocker(t)
t.Parallel()
- t.Run("ok/accepts connections by the time Start returns, not merely running", func(t *testing.T) {
+ t.Run("should accept connections on an ephemeral port once Start returns", func(t *testing.T) {
requireDocker(t)
t.Parallel()
+
+ // Action
pg := start(t)
- if got := pg.Endpoint(infra.External).Port; got == 0 || got == 5432 {
- t.Fatalf("external port should be an ephemeral mapping, got %d", got)
- }
+
+ // Assert
+ require.NotContains(t, []int{0, 5432}, pg.Endpoint(infra.External).Port)
})
- t.Run("ok/internal and external addresses differ", func(t *testing.T) {
+ t.Run("should give different internal and external addresses", func(t *testing.T) {
requireDocker(t)
t.Parallel()
+
+ // Action
pg := start(t)
+
+ // Assert
in, ex := pg.Endpoint(infra.Internal), pg.Endpoint(infra.External)
- if in.Port != 5432 {
- t.Errorf("internal port = %d, want the container port 5432", in.Port)
- }
- if in.HostPort() == ex.HostPort() {
- t.Errorf("internal and external addresses are identical: %s", in.HostPort())
- }
- if in.Host == "127.0.0.1" || in.Host == "localhost" {
- t.Errorf("internal host should be the network alias, got %q", in.Host)
- }
+ require.Equal(t, 5432, in.Port)
+ require.NotEqual(t, ex.HostPort(), in.HostPort())
+ require.NotContains(t, []string{"127.0.0.1", "localhost"}, in.Host)
})
- t.Run("ok/a Named instance is a separate container", func(t *testing.T) {
+ t.Run("should start a separate container when the instance is named", func(t *testing.T) {
requireDocker(t)
t.Parallel()
+
+ // Action
app := start(t)
target := start(t, postgres.Named("rotation"), postgres.WithDatabase("rotation_target"))
- if app.Endpoint(infra.External).Port == target.Endpoint(infra.External).Port {
- t.Fatal("Named() instance shares a container with the default")
- }
- if target.Database() != "rotation_target" {
- t.Fatalf("database = %q, want rotation_target", target.Database())
- }
+ // Assert
+ require.NotEqual(t, app.Endpoint(infra.External).Port, target.Endpoint(infra.External).Port)
+ require.Equal(t, "rotation_target", target.Database())
})
}
diff --git a/tests/infra/runner_test.go b/tests/infra/runner_test.go
index 66ab131ce5..b53864ad5e 100644
--- a/tests/infra/runner_test.go
+++ b/tests/infra/runner_test.go
@@ -7,6 +7,7 @@ import (
"github.com/Infisical/infisical/tests/infra"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
func requireDocker(t *testing.T) {
@@ -24,11 +25,10 @@ func TestRunner_AdoptOrCreate(t *testing.T) {
Nothing else in the suite exercises this, because a passing test looks identical
either way.`)
+ // Setup
ctx := t.Context()
runner := infra.NewRunner(infra.Workspace(), infra.NewLogger())
- if err := runner.Network(ctx, infra.NetworkName); err != nil {
- t.Fatalf("network: %v", err)
- }
+ require.NoError(t, runner.Network(ctx, infra.NetworkName))
name := infra.ContainerName(infra.NameParts{
Scope: infra.Shared,
@@ -45,29 +45,18 @@ func TestRunner_AdoptOrCreate(t *testing.T) {
}
first, err := runner.Run(ctx, spec)
- if err != nil {
- t.Fatalf("first run: %v", err)
- }
+ require.NoError(t, err)
t.Cleanup(func() { _ = first.Stop(context.WithoutCancel(ctx)) })
+ require.False(t, first.Adopted, "a container of this name was left behind by an earlier run")
- if first.Adopted {
- t.Fatal("first run reported adopt; a container of this name was left behind by an earlier run")
- }
-
+ // Action
second, err := runner.Run(ctx, spec)
- if err != nil {
- t.Fatalf("second run: %v", err)
- }
- if !second.Adopted {
- t.Error("second run created a new container instead of adopting the first")
- }
- if second.ID != first.ID {
- t.Errorf("adopted a different container: %s then %s", first.ID, second.ID)
- }
- if a, b := first.Endpoint(infra.External, 6379), second.Endpoint(infra.External, 6379); a != b {
- t.Errorf("adopted container moved ports: %s then %s", a.HostPort(), b.HostPort())
- }
+ // Assert
+ require.NoError(t, err)
+ require.True(t, second.Adopted, "the second run created instead of adopting")
+ require.Equal(t, first.ID, second.ID)
+ require.Equal(t, first.Endpoint(infra.External, 6379), second.Endpoint(infra.External, 6379))
}
func TestRunner_NameChangeCreatesNewContainer(t *testing.T) {
@@ -77,11 +66,10 @@ func TestRunner_NameChangeCreatesNewContainer(t *testing.T) {
container. A stale app container would run your previous code with every test still
passing, which is the worst outcome available.`)
+ // Setup
ctx := t.Context()
runner := infra.NewRunner(infra.Workspace(), infra.NewLogger())
- if err := runner.Network(ctx, infra.NetworkName); err != nil {
- t.Fatalf("network: %v", err)
- }
+ require.NoError(t, runner.Network(ctx, infra.NetworkName))
base := infra.NameParts{Scope: infra.Shared, Module: "redis", Instance: "fptest"}
run := func(fingerprint string) infra.Container {
@@ -94,14 +82,14 @@ func TestRunner_NameChangeCreatesNewContainer(t *testing.T) {
Ports: []int{6379},
Ready: infra.ForExec([]string{"redis-cli", "ping"}),
})
- if err != nil {
- t.Fatalf("run %s: %v", fingerprint, err)
- }
+ require.NoErrorf(t, err, "running %s", fingerprint)
t.Cleanup(func() { _ = c.Stop(context.WithoutCancel(ctx)) })
return c
}
- if a, b := run("aaaa1111"), run("bbbb2222"); a.ID == b.ID {
- t.Fatal("a different fingerprint adopted the same container")
- }
+ // Action
+ a, b := run("aaaa1111"), run("bbbb2222")
+
+ // Assert
+ require.NotEqual(t, a.ID, b.ID, "a different fingerprint adopted the same container")
}
diff --git a/tests/infra/stack_test.go b/tests/infra/stack_test.go
index ed49f5805d..35d8f17d21 100644
--- a/tests/infra/stack_test.go
+++ b/tests/infra/stack_test.go
@@ -9,6 +9,7 @@ import (
"github.com/Infisical/infisical/tests/infra/postgres"
"github.com/Infisical/infisical/tests/infra/redis"
"github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
// startAll resolves and starts a module set the way the harness will, so this
@@ -23,15 +24,11 @@ func startAll(t *testing.T, mods []infra.Module, scope infra.Scope) map[infra.Ke
scopes[m.Key()] = scope
}
plan, err := infra.Resolve(mods, scopes)
- if err != nil {
- t.Fatalf("resolve: %v", err)
- }
+ require.NoError(t, err)
log := infra.NewLogger()
runner := infra.NewRunner(infra.Workspace(), log)
- if err := runner.Network(ctx, infra.NetworkName); err != nil {
- t.Fatalf("network: %v", err)
- }
+ require.NoError(t, runner.Network(ctx, infra.NetworkName))
handles := map[infra.Key]infra.Handle{}
for _, m := range plan.Modules() {
@@ -40,9 +37,7 @@ func startAll(t *testing.T, mods []infra.Module, scope infra.Scope) map[infra.Ke
name.ScopeID = "m1smoke"
h, err := m.Start(ctx, infra.NewDeps(handles, infra.NetworkName, infra.Workspace(), name, runner, log))
- if err != nil {
- t.Fatalf("start %s: %v", m.Key(), err)
- }
+ require.NoErrorf(t, err, "starting %s", m.Key())
handles[m.Key()] = h
t.Cleanup(func() { _ = h.Stop(context.WithoutCancel(ctx)) })
log.Decision("ready", infra.ContainerName(name), h.Endpoint(infra.External), 0, "")
@@ -62,28 +57,25 @@ func TestStack_AllModulesComeUpTogether(t *testing.T) {
mailpit.Module(),
}, infra.Shared)
- t.Run("ok/every module reports a usable external address", func(t *testing.T) {
+ t.Run("should report a usable external address for every module", func(t *testing.T) {
for key, h := range handles {
- if e := h.Endpoint(infra.External); e.Host == "" || e.Port == 0 {
- t.Errorf("%s external endpoint is unusable: %+v", key, e)
- }
+ e := h.Endpoint(infra.External)
+ require.NotEmptyf(t, e.Host, "%s has no external host", key)
+ require.NotZerof(t, e.Port, "%s has no external port", key)
}
})
- t.Run("ok/internal addresses are container aliases, not host addresses", func(t *testing.T) {
+ t.Run("should use container aliases rather than host addresses internally", func(t *testing.T) {
for key, h := range handles {
- in := h.Endpoint(infra.Internal)
- if in.Host == "localhost" || in.Host == "127.0.0.1" {
- t.Errorf("%s internal host is a host address: %s", key, in.Host)
- }
+ require.NotContainsf(t, []string{"localhost", "127.0.0.1"}, h.Endpoint(infra.Internal).Host,
+ "%s internal host is a host address", key)
}
})
- t.Run("ok/mailpit exposes SMTP and its API on different ports", func(t *testing.T) {
+ t.Run("should expose mailpit SMTP and API on different ports", func(t *testing.T) {
mp := handles[mailpit.Key].(*mailpit.Handle)
- if smtp, api := mp.Endpoint(infra.Internal).Port, mp.API(infra.Internal).Port; smtp == api {
- t.Fatalf("SMTP and API share port %d; the application dials one and the harness reads the other", smtp)
- }
+ require.NotEqual(t, mp.Endpoint(infra.Internal).Port, mp.API(infra.Internal).Port,
+ "the application dials one and the harness reads the other")
})
}
diff --git a/tests/internal/mail/mail_test.go b/tests/internal/mail/mail_test.go
index 454ac0927a..079618b35a 100644
--- a/tests/internal/mail/mail_test.go
+++ b/tests/internal/mail/mail_test.go
@@ -1,67 +1,63 @@
package mail
-import "testing"
+import (
+ "testing"
-func TestParam_FindsTheInviteToken(t *testing.T) {
- // Shaped like the real OrgInvite mail: the same link appears in both the text and
- // the HTML part, and the HTML one is quoted inside an attribute.
- m := Message{Subject: "Infisical organization invitation", Body: `
+ "github.com/stretchr/testify/require"
+)
+
+func TestParam(t *testing.T) {
+ t.Run("should find the invite token when it appears in text and HTML parts", func(t *testing.T) {
+ // Setup: shaped like the real OrgInvite mail.
+ m := Message{Subject: "Infisical organization invitation", Body: `
Join the organization:
http://localhost:8080/signupinvite?token=abc123&to=alice%40acme.test&organization_id=org-1
<a href="http://localhost:8080/signupinvite?token=abc123&to=alice%40acme.test&organization_id=org-1">Accept</a>
`}
- got, err := Param(m, "token")
- if err != nil {
- t.Fatalf("extracting the token: %v", err)
- }
- if got != "abc123" {
- t.Errorf("token = %q, want abc123", got)
- }
-}
+ // Action
+ got, err := Param(m, "token")
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, "abc123", got)
+ })
-func TestParam_SkipsLinksWithoutIt(t *testing.T) {
- // Every Infisical mail carries unsubscribe and logo links, so the first URL in the
- // body is routinely not the one that matters.
- m := Message{Body: `
+ t.Run("should skip links that do not carry the parameter", func(t *testing.T) {
+ // Setup: real mails lead with logo and docs links.
+ m := Message{Body: `
<img src="https://cdn.infisical.com/logo.png">
https://infisical.com/docs
http://localhost:8080/signupinvite?token=wanted&to=bob%40acme.test
`}
- got, err := Param(m, "token")
- if err != nil {
- t.Fatalf("extracting the token: %v", err)
- }
- if got != "wanted" {
- t.Errorf("token = %q, want wanted", got)
- }
-}
+ // Action
+ got, err := Param(m, "token")
-func TestParam_ReportsTheBodyWhenAbsent(t *testing.T) {
- // The failure a wrong template produces. Without the body in the message there is
- // nothing to debug from: the mail arrived, it just did not carry what was expected.
- m := Message{Subject: "Welcome", Body: "https://infisical.com/docs\n"}
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, "wanted", got)
+ })
- if _, err := Param(m, "token"); err == nil {
- t.Fatal("expected an error when no link carries the parameter")
- } else if got := err.Error(); !contains(got, "Welcome") || !contains(got, "infisical.com/docs") {
- t.Errorf("error should name the subject and show the body, got: %s", got)
- }
-}
+ t.Run("should report the subject and body when no link carries the parameter", func(t *testing.T) {
+ // Setup
+ m := Message{Subject: "Welcome", Body: "https://infisical.com/docs\n"}
-func contains(s, sub string) bool {
- for i := 0; i+len(sub) <= len(s); i++ {
- if s[i:i+len(sub)] == sub {
- return true
- }
- }
- return false
+ // Action
+ _, err := Param(m, "token")
+
+ // Assert
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "Welcome")
+ require.Contains(t, err.Error(), "infisical.com/docs")
+ })
}
-func TestCode_FindsTheSignupCode(t *testing.T) {
- m := Message{Subject: "Your confirmation code", Body: `
+func TestCode(t *testing.T) {
+ t.Run("should find the signup code", func(t *testing.T) {
+ // Setup
+ m := Message{Subject: "Your confirmation code", Body: `
Confirm your email address with this code:
481920
@@ -69,25 +65,23 @@ Confirm your email address with this code:
This code expires in 5 minutes. Sent 2026-09-17.
`}
- got, err := Code(m, 6)
- if err != nil {
- t.Fatalf("extracting the code: %v", err)
- }
- if got != "481920" {
- t.Errorf("code = %q, want 481920", got)
- }
-}
+ // Action
+ got, err := Code(m, 6)
+
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, "481920", got)
+ })
+
+ t.Run("should ignore longer numbers in the footer", func(t *testing.T) {
+ // Setup
+ m := Message{Subject: "Your confirmation code", Body: "id=20260917120000 port=8080\ncode: 771234\n"}
+
+ // Action
+ got, err := Code(m, 6)
-func TestCode_IgnoresLongerNumbers(t *testing.T) {
- // A year, a port and a message id are all digits, and the footer of a real mail
- // is full of them. Matching a bare run of digits would pick up the wrong one.
- m := Message{Subject: "Your confirmation code", Body: "id=20260917120000 port=8080\ncode: 771234\n"}
-
- got, err := Code(m, 6)
- if err != nil {
- t.Fatalf("extracting the code: %v", err)
- }
- if got != "771234" {
- t.Errorf("code = %q, want 771234", got)
- }
+ // Assert
+ require.NoError(t, err)
+ require.Equal(t, "771234", got)
+ })
}
diff --git a/tests/suites/organization/organization_test.go b/tests/suites/organization/organization_test.go
index 29773a8742..77a66250ab 100644
--- a/tests/suites/organization/organization_test.go
+++ b/tests/suites/organization/organization_test.go
@@ -7,39 +7,41 @@ import (
"github.com/Infisical/infisical/tests/harness"
"github.com/Infisical/infisical/tests/internal/spec"
"github.com/google/uuid"
+ "github.com/stretchr/testify/require"
)
func TestOrganization_Create(t *testing.T) {
t.Parallel()
h := harness.From(t)
- t.Run("cross-tenant/another tenant's organization is not readable", func(t *testing.T) {
+ t.Run("should refuse a read when the organization belongs to another tenant", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `The claim the whole Shared profile rests on. If one tenant can reach
- another's organization, running tests in parallel against one instance is unsound
- and every result is suspect.`)
+ spec.Why(t, `The claim the Shared profile rests on: if one tenant can reach
+ another's organization, parallel tests against one instance are unsound.`)
+ // Setup
mine, theirs := h.NewTenant(t), h.NewTenant(t)
+ // Action
res, err := mine.Admin.API.GetOrganizationPlanWithResponse(t.Context(), theirs.OrgID.String(), nil)
- if err != nil {
- t.Fatalf("reading another organization: %v", err)
- }
- if res.StatusCode() == http.StatusOK {
- t.Fatalf("tenant %s read tenant %s's plan", mine.OrgSlug, theirs.OrgSlug)
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.NotEqualf(t, http.StatusOK, res.StatusCode(),
+ "tenant %s read tenant %s's plan", mine.OrgSlug, theirs.OrgSlug)
})
- t.Run("notfound/an organization that never existed", func(t *testing.T) {
+ t.Run("should refuse a read when the organization does not exist", func(t *testing.T) {
t.Parallel()
+
+ // Setup
tn := h.NewTenant(t)
+ // Action
res, err := tn.Admin.API.GetOrganizationPlanWithResponse(t.Context(), uuid.NewString(), nil)
- if err != nil {
- t.Fatalf("reading an absent organization: %v", err)
- }
- if res.StatusCode() == http.StatusOK {
- t.Fatal("an organization that does not exist returned a plan")
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.NotEqual(t, http.StatusOK, res.StatusCode(), "an organization that does not exist returned a plan")
})
}
diff --git a/tests/suites/project/project_test.go b/tests/suites/project/project_test.go
index a72b97ddc4..3e8677f4de 100644
--- a/tests/suites/project/project_test.go
+++ b/tests/suites/project/project_test.go
@@ -1,47 +1,39 @@
package project_test
import (
- "slices"
"testing"
"github.com/Infisical/infisical/tests/clients/api"
"github.com/Infisical/infisical/tests/harness"
+ "github.com/stretchr/testify/require"
)
func TestProject_Create(t *testing.T) {
t.Parallel()
h := harness.From(t)
- t.Run("ok/creates a project in the tenant's organization", func(t *testing.T) {
+ t.Run("should create the project in the caller's organization with default environments", func(t *testing.T) {
t.Parallel()
+
+ // Setup
tn := h.NewTenant(t)
+ // Action
res, err := tn.Admin.API.CreateProjectWithResponse(t.Context(), api.CreateProjectJSONRequestBody{
ProjectName: "app",
})
- if err != nil {
- t.Fatalf("creating a project: %v", err)
- }
- if res.JSON200 == nil {
- t.Fatalf("creating a project returned %d: %s", res.StatusCode(), res.Body)
- }
+ // Assert
+ require.NoError(t, err)
+ require.NotNilf(t, res.JSON200, "creating a project returned %d: %s", res.StatusCode(), res.Body)
proj := res.JSON200.Project
- if proj.OrgId != tn.OrgID {
- t.Errorf("project landed in organization %s, want the caller's %s", proj.OrgId, tn.OrgID)
- }
+ require.Equal(t, tn.OrgID, proj.OrgId)
- // Creating a project provisions its environments. A project without them is
- // not usable for anything, and the response is the only place a caller learns
- // what the slugs are.
+ // The response is the only place a caller learns the environment slugs.
var envs []string
for _, e := range proj.Environments {
envs = append(envs, e.Slug)
}
- for _, want := range []string{"dev", "staging", "prod"} {
- if !slices.Contains(envs, want) {
- t.Errorf("new project has environments %v, missing %q", envs, want)
- }
- }
+ require.Subset(t, envs, []string{"dev", "staging", "prod"})
})
}
diff --git a/tests/suites/secretmanager/secrets/create_test.go b/tests/suites/secretmanager/secrets/create_test.go
index fb3e8a06e3..629531674f 100644
--- a/tests/suites/secretmanager/secrets/create_test.go
+++ b/tests/suites/secretmanager/secrets/create_test.go
@@ -5,68 +5,57 @@ import (
"testing"
"github.com/Infisical/infisical/tests/clients/api"
- "github.com/Infisical/infisical/tests/fixture/project"
- "github.com/Infisical/infisical/tests/fixture/secret"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
"github.com/Infisical/infisical/tests/harness"
- "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
)
func TestSecret_Create(t *testing.T) {
t.Parallel()
h := harness.From(t)
- t.Run("ok/a created secret reads back with its value", func(t *testing.T) {
+ t.Run("should read back a created secret with its value", func(t *testing.T) {
t.Parallel()
- tn := h.NewTenant(t)
- proj := project.New(t, tn, project.WithType("secret-manager"))
-
- created := secret.Create(t, proj, "dev", "DB_URL", "postgres://localhost/app")
- if created.Version != 1 {
- t.Errorf("a new secret is at version %v, want 1", created.Version)
- }
-
- got := secret.Get(t, proj, "dev", "DB_URL")
- if got.Value != "postgres://localhost/app" {
- t.Errorf("secret read back as %q, want postgres://localhost/app", got.Value)
- }
- if got.ValueHidden {
- t.Error("the value came back hidden, so nothing downstream could use it")
- }
- if got.Path != "/" {
- t.Errorf("secret is at path %q, want /", got.Path)
- }
+ // Setup
+ proj := fixture.NewProject(t, h.NewTenant(t), fixture.WithProjectType("secret-manager"))
+
+ // Action
+ created := secretmanager.CreateSecret(t, proj, "dev", "DB_URL", "postgres://localhost/app")
+
+ // Assert
+ require.EqualValues(t, 1, created.Version, "a new secret starts at version 1")
+ got := secretmanager.GetSecret(t, proj, "dev", "DB_URL")
+ require.Equal(t, "postgres://localhost/app", got.Value)
+ require.False(t, got.ValueHidden, "a hidden value is useless to anything downstream")
+ require.Equal(t, "/", got.Path)
})
- t.Run("ok/the same name in two environments holds two values", func(t *testing.T) {
+ t.Run("should hold a separate value per environment when one name is created in two", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `Environments are the point of a secret manager: the same key carries a
- different value per environment, and a create in one must not touch another.`)
- tn := h.NewTenant(t)
- proj := project.New(t, tn, project.WithType("secret-manager"))
+ // Setup
+ proj := fixture.NewProject(t, h.NewTenant(t), fixture.WithProjectType("secret-manager"))
- secret.Create(t, proj, "dev", "API_KEY", "dev-value")
- secret.Create(t, proj, "prod", "API_KEY", "prod-value")
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "dev-value")
+ secretmanager.CreateSecret(t, proj, "prod", "API_KEY", "prod-value")
- if got := secret.Get(t, proj, "dev", "API_KEY"); got.Value != "dev-value" {
- t.Errorf("dev holds %q, want dev-value", got.Value)
- }
- if got := secret.Get(t, proj, "prod", "API_KEY"); got.Value != "prod-value" {
- t.Errorf("prod holds %q, want prod-value", got.Value)
- }
+ // Assert
+ require.Equal(t, "dev-value", secretmanager.GetSecret(t, proj, "dev", "API_KEY").Value)
+ require.Equal(t, "prod-value", secretmanager.GetSecret(t, proj, "prod", "API_KEY").Value)
})
- t.Run("conflict/creating the same name twice is refused", func(t *testing.T) {
+ t.Run("should refuse and keep the original when the same name is created twice", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `Create must not silently overwrite. If it did, a caller expecting to
- add a secret could replace one already in use and never learn about it.`)
+ // Setup
tn := h.NewTenant(t)
- proj := project.New(t, tn, project.WithType("secret-manager"))
-
- secret.Create(t, proj, "dev", "TOKEN", "first")
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ secretmanager.CreateSecret(t, proj, "dev", "TOKEN", "first")
+ // Action
res, err := tn.Admin.API.CreateSecretV4WithResponse(t.Context(), "TOKEN",
api.CreateSecretV4JSONRequestBody{
ProjectId: proj.ID,
@@ -74,23 +63,22 @@ func TestSecret_Create(t *testing.T) {
SecretPath: new("/"),
SecretValue: "second",
})
- if err != nil {
- t.Fatalf("creating a duplicate secret: %v", err)
- }
- if res.StatusCode() == http.StatusOK {
- t.Fatal("creating a secret that already exists was allowed")
- }
- if got := secret.Get(t, proj, "dev", "TOKEN"); got.Value != "first" {
- t.Errorf("the refused create still changed the value to %q", got.Value)
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.NotEqual(t, http.StatusOK, res.StatusCode(), "a duplicate create was allowed")
+ require.Equal(t, "first", secretmanager.GetSecret(t, proj, "dev", "TOKEN").Value,
+ "the refused create still changed the value")
})
- t.Run("invalid/an unknown environment is refused", func(t *testing.T) {
+ t.Run("should refuse a secret when the environment does not exist", func(t *testing.T) {
t.Parallel()
+ // Setup
tn := h.NewTenant(t)
- proj := project.New(t, tn, project.WithType("secret-manager"))
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ // Action
res, err := tn.Admin.API.CreateSecretV4WithResponse(t.Context(), "STRAY",
api.CreateSecretV4JSONRequestBody{
ProjectId: proj.ID,
@@ -98,20 +86,20 @@ func TestSecret_Create(t *testing.T) {
SecretPath: new("/"),
SecretValue: "value",
})
- if err != nil {
- t.Fatalf("creating a secret in an unknown environment: %v", err)
- }
- if res.StatusCode() == http.StatusOK {
- t.Fatal("a secret was created in an environment that does not exist")
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.NotEqual(t, http.StatusOK, res.StatusCode(), "a secret was created in an environment that does not exist")
})
- t.Run("cross-tenant/another tenant's project is not writable", func(t *testing.T) {
+ t.Run("should refuse a write when the project belongs to another tenant", func(t *testing.T) {
t.Parallel()
+ // Setup
mine, theirs := h.NewTenant(t), h.NewTenant(t)
- target := project.New(t, theirs, project.WithType("secret-manager"))
+ target := fixture.NewProject(t, theirs, fixture.WithProjectType("secret-manager"))
+ // Action
res, err := mine.Admin.API.CreateSecretV4WithResponse(t.Context(), "STOLEN",
api.CreateSecretV4JSONRequestBody{
ProjectId: target.ID,
@@ -119,11 +107,10 @@ func TestSecret_Create(t *testing.T) {
SecretPath: new("/"),
SecretValue: "value",
})
- if err != nil {
- t.Fatalf("writing into another tenant's project: %v", err)
- }
- if res.StatusCode() == http.StatusOK {
- t.Fatalf("tenant %s wrote a secret into tenant %s's project", mine.OrgSlug, theirs.OrgSlug)
- }
+
+ // Assert
+ require.NoError(t, err)
+ require.NotEqualf(t, http.StatusOK, res.StatusCode(),
+ "tenant %s wrote a secret into tenant %s's project", mine.OrgSlug, theirs.OrgSlug)
})
}
diff --git a/tests/suites/secretmanager/syncs/github_test.go b/tests/suites/secretmanager/syncs/github_test.go
index e097a781a6..6f7bdbf5f4 100644
--- a/tests/suites/secretmanager/syncs/github_test.go
+++ b/tests/suites/secretmanager/syncs/github_test.go
@@ -2,217 +2,197 @@ package syncs_test
import (
"fmt"
- "strings"
"testing"
"github.com/Infisical/infisical/tests/fakes/github"
- "github.com/Infisical/infisical/tests/fixture/appconnection"
- "github.com/Infisical/infisical/tests/fixture/project"
- "github.com/Infisical/infisical/tests/fixture/secret"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
"github.com/Infisical/infisical/tests/harness"
"github.com/Infisical/infisical/tests/infra/fakenet"
"github.com/Infisical/infisical/tests/internal/spec"
"github.com/Infisical/infisical/tests/provider"
+ "github.com/stretchr/testify/require"
)
-// setup is the arrangement every subtest starts from: a project, a GitHub connection,
-// and a handle on the GitHub account that connection addresses.
-func setup(t *testing.T) (*project.Project, *appconnection.Connection, *github.Handle) {
+// setup returns a project, a GitHub connection, and a handle on the account it uses.
+func setup(t *testing.T) (*fixture.Project, *fixture.AppConnection, *github.Handle) {
t.Helper()
-
tn := harness.From(t).NewTenant(t)
- proj := project.New(t, tn, project.WithType("secret-manager"))
- conn := appconnection.New(t, tn, provider.GitHub)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ conn := fixture.NewAppConnection(t, tn, provider.GitHub)
return proj, conn, github.Open(t, conn.FakenetAdmin(t), conn.Nonce())
}
+func named(name string) func(github.SecretDeleted) bool {
+ return func(e github.SecretDeleted) bool { return e.SecretName == name }
+}
+
func TestGitHubSync_SyncSecrets(t *testing.T) {
t.Parallel()
- t.Run("ok/a secret reaches the destination with its value intact", func(t *testing.T) {
+ t.Run("should deliver the value intact when a secret is synced", func(t *testing.T) {
t.Parallel()
+ // Setup
proj, conn, gh := setup(t)
s := newSync(t, proj, conn, repoScope("acme", "app"))
+ secretmanager.CreateSecret(t, proj, "dev", "DB_URL", "postgres://db/app")
- secret.Create(t, proj, "dev", "DB_URL", "postgres://db/app")
+ // Action
s.trigger(t)
- got := gh.Repo(t, "acme/app").Secrets
- if got["DB_URL"].Value != "postgres://db/app" {
- t.Errorf("GitHub holds %q for DB_URL, want postgres://db/app", got["DB_URL"].Value)
- }
+ // Assert
+ require.Equal(t, "postgres://db/app", gh.Repo(t, "acme/app").Secrets["DB_URL"].Value)
})
- t.Run("ok/a secret removed in Infisical is pruned at the destination", func(t *testing.T) {
+ t.Run("should prune the destination when a synced secret is deleted", func(t *testing.T) {
t.Parallel()
+ // Setup
proj, conn, gh := setup(t)
s := newSync(t, proj, conn, repoScope("acme", "app"))
-
- secret.Create(t, proj, "dev", "KEEP", "1")
- secret.Create(t, proj, "dev", "DROP", "2")
+ secretmanager.CreateSecret(t, proj, "dev", "KEEP", "1")
+ secretmanager.CreateSecret(t, proj, "dev", "DROP", "2")
s.trigger(t)
-
mark := gh.Mark(t)
- secret.Delete(t, proj, "dev", "DROP")
- s.trigger(t)
- gh.ExpectEvent[github.SecretDeleted](t, func(e github.SecretDeleted) bool {
- return e.SecretName == "DROP"
- }, fakenet.Since(mark))
+ // Action
+ secretmanager.DeleteSecret(t, proj, "dev", "DROP")
+ s.trigger(t)
+ // Assert
+ gh.ExpectEvent[github.SecretDeleted](t, named("DROP"), fakenet.Since(mark))
got := gh.Repo(t, "acme/app").Secrets
- if got["KEEP"].Value != "1" {
- t.Errorf("KEEP holds %q, want 1", got["KEEP"].Value)
- }
- if _, still := got["DROP"]; still {
- t.Error("DROP was deleted in Infisical but is still at the destination")
- }
+ require.Equal(t, "1", got["KEEP"].Value)
+ require.NotContains(t, got, "DROP")
})
- t.Run("ok/a secret outside the key schema is left alone", func(t *testing.T) {
+ t.Run("should leave a secret it does not own untouched when a key schema is set", func(t *testing.T) {
t.Parallel()
+ // Setup
proj, conn, gh := setup(t)
gh.Seed(t, github.RepoSecret("acme/app", "SOMEONE_ELSES", "do not touch"))
-
s := newSync(t, proj, conn, repoScope("acme", "app"), keySchema("INFISICAL_{{secretKey}}"))
+ secretmanager.CreateSecret(t, proj, "dev", "A", "1")
- secret.Create(t, proj, "dev", "A", "1")
+ // Action
s.trigger(t)
+ // Assert
got := gh.Repo(t, "acme/app").Secrets
- if got["SOMEONE_ELSES"].Value != "do not touch" {
- t.Errorf("a secret outside the key schema was modified or deleted: %#v", got["SOMEONE_ELSES"])
- }
- if _, ok := got["INFISICAL_A"]; !ok {
- t.Errorf("the managed secret did not arrive under the key schema: %v", keys(got))
- }
+ require.Equal(t, "do not touch", got["SOMEONE_ELSES"].Value, "a secret outside the key schema was changed")
+ require.Contains(t, got, "INFISICAL_A", "the managed secret did not arrive under the key schema")
})
- t.Run("ok/disableSecretDeletion keeps an orphan at the destination", func(t *testing.T) {
+ t.Run("should keep a deleted secret at the destination when deletion is disabled", func(t *testing.T) {
t.Parallel()
+ // Setup
proj, conn, gh := setup(t)
s := newSync(t, proj, conn, repoScope("acme", "app"), disableSecretDeletion())
-
- secret.Create(t, proj, "dev", "ORPHAN", "1")
+ secretmanager.CreateSecret(t, proj, "dev", "ORPHAN", "1")
s.trigger(t)
- secret.Delete(t, proj, "dev", "ORPHAN")
+ // Action
+ secretmanager.DeleteSecret(t, proj, "dev", "ORPHAN")
s.trigger(t)
- if got := gh.Repo(t, "acme/app").Secrets; got["ORPHAN"].Value != "1" {
- t.Errorf("ORPHAN was pruned despite disableSecretDeletion: %#v", got["ORPHAN"])
- }
+ // Assert
+ require.Equal(t, "1", gh.Repo(t, "acme/app").Secrets["ORPHAN"].Value)
})
- t.Run("ok/keys are upper-cased on the way out", func(t *testing.T) {
+ t.Run("should store the key upper-cased when it is lower-case in Infisical", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `syncSecrets upper-cases every key before sending it, because GitHub
- does. A test asserting on the request path would pass either way; only the
- destination's own key set shows which name it was actually stored under.`)
+ spec.Why(t, `A test on the request path would pass either way; only the
+ destination's key set shows the name it was stored under.`)
+ // Setup
proj, conn, gh := setup(t)
s := newSync(t, proj, conn, repoScope("acme", "app"))
+ secretmanager.CreateSecret(t, proj, "dev", "lower_case", "v")
- secret.Create(t, proj, "dev", "lower_case", "v")
+ // Action
s.trigger(t)
- got := gh.Repo(t, "acme/app").Secrets
- if _, ok := got["LOWER_CASE"]; !ok {
- t.Errorf("secret was not stored upper-cased: %v", keys(got))
- }
+ // Assert
+ require.Contains(t, gh.Repo(t, "acme/app").Secrets, "LOWER_CASE")
})
- t.Run("ok/a sync spanning several pages sends every secret", func(t *testing.T) {
+ t.Run("should deliver every secret when they span several pages", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `The client asks for 100 per page, reads the Link header, parses
- rel="last" for a page count and fetches the rest concurrently. A destination
- that answered everything on one page would leave that loop untested, and it is
- the loop that decides what gets pruned. Organization scope because the
- repository cap is 100, which is one page.`)
+ spec.Why(t, `The client reads the Link header and fetches pages 2..N concurrently;
+ that listing is what the prune decision is built from. Organization scope
+ because the repository cap of 100 is a single page.`)
+ // Setup
proj, conn, gh := setup(t)
s := newSync(t, proj, conn, orgScope("acme"))
-
const n = 120
for i := range n {
- secret.Create(t, proj, "dev", fmt.Sprintf("BULK_%03d", i), fmt.Sprintf("v%d", i))
+ secretmanager.CreateSecret(t, proj, "dev", fmt.Sprintf("BULK_%03d", i), fmt.Sprintf("v%d", i))
}
s.trigger(t)
- // Again, so the run has to list what is already there. That is the call that
- // paginates, and its result is what the prune decision is built from.
+ // Action: the second run has to list what is already there, which paginates.
s.trigger(t)
- if got := gh.OrgSecrets(t, "acme").Secrets; len(got) != n {
- t.Errorf("the destination holds %d secrets, want %d", len(got), n)
- }
+ // Assert
+ require.Len(t, gh.OrgSecrets(t, "acme").Secrets, n)
})
- t.Run("invalid/more than 100 secrets at repository scope is refused", func(t *testing.T) {
+ t.Run("should fail naming the limit when more than 100 go to a repository", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `GitHub caps repository secrets at 100 and Infisical checks before
- sending anything, so the sync fails with a message naming the limit rather than
- writing 100 and silently dropping the rest. Found by writing the pagination
- test above against the wrong scope.`)
+ spec.Why(t, `Infisical checks before sending, so the sync fails rather than writing
+ 100 and silently dropping the rest.`)
+ // Setup
proj, conn, _ := setup(t)
s := newSync(t, proj, conn, repoScope("acme", "app"))
-
for i := range 101 {
- secret.Create(t, proj, "dev", fmt.Sprintf("BULK_%03d", i), "v")
+ secretmanager.CreateSecret(t, proj, "dev", fmt.Sprintf("BULK_%03d", i), "v")
}
- status, message := s.triggerExpectingFailure(t)
- if status != "failed" {
- t.Fatalf("a sync of 101 secrets to a repository reported %q, want failed", status)
- }
- if !strings.Contains(message, "100") {
- t.Errorf("the failure does not name the limit, so nobody can act on it: %s", message)
- }
+ // Action
+ got := s.triggerExpectingFailure(t)
+
+ // Assert
+ require.Equal(t, "failed", got.status)
+ require.Contains(t, got.message, "100", "the failure does not name the limit")
})
}
func TestGitHubSync_Create(t *testing.T) {
t.Parallel()
- t.Run("ok/creating a sync with auto-sync on pushes immediately", func(t *testing.T) {
+ t.Run("should push existing secrets when created with auto-sync on", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `isAutoSyncEnabled defaults to true and queues a sync at creation, so
- a secret that already exists arrives without anyone triggering anything.`)
+ // Setup
proj, conn, gh := setup(t)
- secret.Create(t, proj, "dev", "PRESENT", "1")
+ secretmanager.CreateSecret(t, proj, "dev", "PRESENT", "1")
+ // Action
s := newSync(t, proj, conn, repoScope("acme", "app"), autoSync(true))
s.awaitTerminal(t)
- if got := gh.Repo(t, "acme/app").Secrets; got["PRESENT"].Value != "1" {
- t.Errorf("auto-sync did not push an existing secret: %#v", got)
- }
+ // Assert
+ require.Equal(t, "1", gh.Repo(t, "acme/app").Secrets["PRESENT"].Value)
})
- t.Run("ok/creating a sync with auto-sync off leaves the destination untouched", func(t *testing.T) {
+ t.Run("should write nothing when created with auto-sync off", func(t *testing.T) {
t.Parallel()
- spec.Why(t, `The inverse, and the one a response body cannot show: proving a write
- did not happen needs somewhere to look that would have recorded it.`)
+ spec.Why(t, `An immediate state read passes before an async push lands, so absence
+ is asserted by waiting out a window with ExpectNoEvent.`)
+ // Setup
proj, conn, gh := setup(t)
- secret.Create(t, proj, "dev", "PRESENT", "1")
+ secretmanager.CreateSecret(t, proj, "dev", "PRESENT", "1")
+ // Action
newSync(t, proj, conn, repoScope("acme", "app"), autoSync(false))
+ // Assert
gh.ExpectNoEvent[github.SecretCreated](t, nil)
})
}
-
-func keys[V any](m map[string]V) []string {
- out := make([]string, 0, len(m))
- for k := range m {
- out = append(out, k)
- }
- return out
-}
diff --git a/tests/suites/secretmanager/syncs/helpers_test.go b/tests/suites/secretmanager/syncs/helpers_test.go
index fec8347826..e8649d8fb6 100644
--- a/tests/suites/secretmanager/syncs/helpers_test.go
+++ b/tests/suites/secretmanager/syncs/helpers_test.go
@@ -5,19 +5,19 @@ import (
"testing"
"github.com/Infisical/infisical/tests/clients/api"
- "github.com/Infisical/infisical/tests/fixture/appconnection"
- "github.com/Infisical/infisical/tests/fixture/project"
+ "github.com/Infisical/infisical/tests/fixture"
"github.com/Infisical/infisical/tests/internal/apierr"
"github.com/Infisical/infisical/tests/internal/wait"
"github.com/google/uuid"
+ "github.com/stretchr/testify/require"
)
-// Suite-local rather than a fixture: only this package creates a sync. It moves under
-// fixture/ when a second one does.
+// Suite-local until a second package creates a sync; then it moves to
+// fixture/secretmanager.
type sync struct {
ID uuid.UUID
- proj *project.Project
+ proj *fixture.Project
}
type syncConfig struct {
@@ -28,14 +28,10 @@ type syncConfig struct {
secretPath string
}
-// syncOption adjusts a new sync. The destination is positional because the API has no
-// default for it; everything else has one.
type syncOption func(*syncConfig)
-// autoSync controls whether creating the sync immediately pushes.
-//
-// isAutoSyncEnabled defaults to true in the schema, so a test that wants to choose
-// when the first push happens has to turn it off.
+// autoSync defaults to true in the schema, so a test choosing when the first push
+// happens has to turn it off.
func autoSync(on bool) syncOption { return func(c *syncConfig) { c.autoSync = on } }
func keySchema(s string) syncOption { return func(c *syncConfig) { c.keySchema = s } }
@@ -44,40 +40,29 @@ func disableSecretDeletion() syncOption {
return func(c *syncConfig) { c.disableSecretDeletion = true }
}
-// destination is where a sync writes. Required, because the API has no default, and
-// the scopes differ enough that each gets its own constructor.
type destination func(*testing.T) api.CreateGitHubSecretSyncJSONBody_DestinationConfig
-// repoScope syncs to one repository. Capped at 100 secrets by GitHub.
+// repoScope is capped at 100 secrets by GitHub.
func repoScope(owner, repo string) destination {
return func(tt *testing.T) api.CreateGitHubSecretSyncJSONBody_DestinationConfig {
var d api.CreateGitHubSecretSyncJSONBody_DestinationConfig
- if err := d.FromCreateGitHubSecretSyncJSONBodyDestinationConfig1(
- api.CreateGitHubSecretSyncJSONBodyDestinationConfig1{
- Owner: owner, Repo: repo, Scope: "repository",
- }); err != nil {
- tt.Fatalf("syncs: building a repository destination: %v", err)
- }
+ require.NoError(tt, d.FromCreateGitHubSecretSyncJSONBodyDestinationConfig1(
+ api.CreateGitHubSecretSyncJSONBodyDestinationConfig1{Owner: owner, Repo: repo, Scope: "repository"}))
return d
}
}
-// orgScope syncs to an organization, where the cap is 1000 rather than 100.
+// orgScope is capped at 1000.
func orgScope(org string) destination {
return func(tt *testing.T) api.CreateGitHubSecretSyncJSONBody_DestinationConfig {
var d api.CreateGitHubSecretSyncJSONBody_DestinationConfig
- if err := d.FromCreateGitHubSecretSyncJSONBodyDestinationConfig0(
- api.CreateGitHubSecretSyncJSONBodyDestinationConfig0{
- Org: org, Scope: "organization", Visibility: "all",
- }); err != nil {
- tt.Fatalf("syncs: building an organization destination: %v", err)
- }
+ require.NoError(tt, d.FromCreateGitHubSecretSyncJSONBodyDestinationConfig0(
+ api.CreateGitHubSecretSyncJSONBodyDestinationConfig0{Org: org, Scope: "organization", Visibility: "all"}))
return d
}
}
-// newSync creates a GitHub sync.
-func newSync(tt *testing.T, p *project.Project, conn *appconnection.Connection,
+func newSync(tt *testing.T, p *fixture.Project, conn *fixture.AppConnection,
dest destination, opts ...syncOption) *sync {
tt.Helper()
@@ -95,7 +80,7 @@ func newSync(tt *testing.T, p *project.Project, conn *appconnection.Connection,
DestinationConfig: dest(tt),
IsAutoSyncEnabled: &cfg.autoSync,
}
- // GitHub cannot import, so the schema pins this to the one legal value.
+ // GitHub cannot import, so the schema allows only this.
body.SyncOptions.InitialSyncBehavior = "overwrite-destination"
if cfg.keySchema != "" {
body.SyncOptions.KeySchema = &cfg.keySchema
@@ -105,31 +90,31 @@ func newSync(tt *testing.T, p *project.Project, conn *appconnection.Connection,
}
res, err := p.Tenant().Admin.API.CreateGitHubSecretSyncWithResponse(tt.Context(), body)
- if err != nil {
- tt.Fatalf("syncs: creating a sync: %v", err)
- }
- if res.JSON200 == nil {
- tt.Fatalf("syncs: creating a sync returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
- }
+ require.NoError(tt, err, "creating a sync")
+ require.NotNilf(tt, res.JSON200, "creating a sync returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
return &sync{ID: res.JSON200.SecretSync.Id, proj: p}
}
-// trigger runs the sync and waits for it to reach a terminal status.
-//
-// Waiting on the sync rather than on the destination is the difference between a
-// useful failure and a mystery. A sync that fails records why on the row, so a broken
-// one reports the product's own message instead of timing out with nothing arriving.
+// trigger runs the sync and waits on its status rather than the destination, so a
+// failed sync reports the product's own reason instead of a timeout.
func (s *sync) trigger(tt *testing.T) {
tt.Helper()
+ s.start(tt)
+ s.awaitTerminal(tt)
+}
+// triggerExpectingFailure is trigger for when failing is the behaviour under test.
+func (s *sync) triggerExpectingFailure(tt *testing.T) outcome {
+ tt.Helper()
+ s.start(tt)
+ return s.awaitOutcome(tt)
+}
+
+func (s *sync) start(tt *testing.T) {
+ tt.Helper()
res, err := s.proj.Tenant().Admin.API.SyncGitHubSecretSyncWithResponse(tt.Context(), s.ID)
- if err != nil {
- tt.Fatalf("syncs: triggering: %v", err)
- }
- if res.JSON200 == nil {
- tt.Fatalf("syncs: triggering returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
- }
- s.awaitTerminal(tt)
+ require.NoError(tt, err, "triggering a sync")
+ require.NotNilf(tt, res.JSON200, "triggering a sync returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
}
type outcome struct {
@@ -137,29 +122,24 @@ type outcome struct {
message string
}
-// awaitTerminal blocks until the sync has succeeded or failed, and fails the test on
-// failure with what the product reported.
func (s *sync) awaitTerminal(tt *testing.T) {
tt.Helper()
- if got := s.awaitOutcome(tt); got.status == "failed" {
- tt.Fatalf("syncs: the sync failed: %s", got.message)
- }
+ got := s.awaitOutcome(tt)
+ require.NotEqualf(tt, "failed", got.status, "the sync failed: %s", got.message)
}
-// awaitOutcome blocks until the sync reaches a terminal status and reports it.
func (s *sync) awaitOutcome(tt *testing.T) outcome {
tt.Helper()
got, err := wait.For(tt.Context(), func(ctx context.Context) (outcome, bool, error) {
- res, rErr := s.proj.Tenant().Admin.API.GetGitHubSecretSyncWithResponse(ctx, s.ID)
- if rErr != nil {
- return outcome{}, false, rErr
+ res, err := s.proj.Tenant().Admin.API.GetGitHubSecretSyncWithResponse(ctx, s.ID)
+ if err != nil {
+ return outcome{}, false, err
}
if res.JSON200 == nil {
return outcome{}, false, nil
}
-
- out := outcome{}
+ var out outcome
if v := res.JSON200.SecretSync.SyncStatus; v != nil {
out.status = *v
}
@@ -168,25 +148,6 @@ func (s *sync) awaitOutcome(tt *testing.T) outcome {
}
return out, out.status == "succeeded" || out.status == "failed", nil
})
- if err != nil {
- tt.Fatalf("syncs: %v", err)
- }
+ require.NoError(tt, err, "waiting for the sync to finish")
return got
}
-
-// triggerExpectingFailure runs the sync and returns how it ended, for the cases where
-// failing is the behaviour under test.
-func (s *sync) triggerExpectingFailure(tt *testing.T) (status, message string) {
- tt.Helper()
-
- res, err := s.proj.Tenant().Admin.API.SyncGitHubSecretSyncWithResponse(tt.Context(), s.ID)
- if err != nil {
- tt.Fatalf("syncs: triggering: %v", err)
- }
- if res.JSON200 == nil {
- tt.Fatalf("syncs: triggering returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
- }
-
- got := s.awaitOutcome(tt)
- return got.status, got.message
-}