chore(tests): use a coverage server binary (#8407)

# Which Problems Are Solved

Use a single server instance for API integration tests. This optimizes
the time taken for the integration test pipeline,
because it allows running tests on multiple packages in parallel. Also,
it saves time by not start and stopping a zitadel server for every
package.

# How the Problems Are Solved

- Build a binary with `go build -race -cover ....`
- Integration tests only construct clients. The server remains running
in the background.
- The integration package and tested packages now fully utilize the API.
No more direct database access trough `query` and `command` packages.
- Use Makefile recipes to setup, start and stop the server in the
background.
- The binary has the race detector enabled
- Init and setup jobs are configured to halt immediately on race
condition
- Because the server runs in the background, races are only logged. When
the server is stopped and race logs exist, the Makefile recipe will
throw an error and print the logs.
- Makefile recipes include logic to print logs and convert coverage
reports after the server is stopped.
- Some tests need a downstream HTTP server to make requests, like quota
and milestones. A new `integration/sink` package creates an HTTP server
and uses websockets to forward HTTP request back to the test packages.
The package API uses Go channels for abstraction and easy usage.

# Additional Changes

- Integration test files already used the `//go:build integration`
directive. In order to properly split integration from unit tests,
integration test files need to be in a `integration_test` subdirectory
of their package.
- `UseIsolatedInstance` used to overwrite the `Tester.Client` for each
instance. Now a `Instance` object is returned with a gRPC client that is
connected to the isolated instance's hostname.
- The `Tester` type is now `Instance`. The object is created for the
first instance, used by default in any test. Isolated instances are also
`Instance` objects and therefore benefit from the same methods and
values. The first instance and any other us capable of creating an
isolated instance over the system API.
- All test packages run in an Isolated instance by calling
`NewInstance()`
- Individual tests that use an isolated instance use `t.Parallel()`

# Additional Context

- Closes #6684
- https://go.dev/doc/articles/race_detector
- https://go.dev/doc/build-cover

---------

Co-authored-by: Stefan Benz <[email protected]>
This commit is contained in:
Tim Möhlmann
2024-09-06 14:47:57 +02:00
committed by GitHub
co-authored by Stefan Benz
parent b522588d98
commit d2e0ac07f1
115 changed files with 3632 additions and 3348 deletions
@@ -8,13 +8,16 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/zitadel/zitadel/internal/integration"
"github.com/zitadel/zitadel/pkg/grpc/instance"
"github.com/zitadel/zitadel/pkg/grpc/object"
system_pb "github.com/zitadel/zitadel/pkg/grpc/system"
)
func TestServer_ListInstances(t *testing.T) {
domain, instanceID, _, _ := Tester.UseIsolatedInstance(t, CTX, SystemCTX)
t.Parallel()
isoInstance := integration.NewInstance(CTX)
tests := []struct {
name string
@@ -51,13 +54,13 @@ func TestServer_ListInstances(t *testing.T) {
Queries: []*instance.Query{{
Query: &instance.Query_IdQuery{
IdQuery: &instance.IdsQuery{
Ids: []string{instanceID},
Ids: []string{isoInstance.ID()},
},
},
}},
},
want: []*instance.Instance{{
Id: instanceID,
Id: isoInstance.ID(),
}},
},
{
@@ -82,19 +85,19 @@ func TestServer_ListInstances(t *testing.T) {
Queries: []*instance.Query{{
Query: &instance.Query_DomainQuery{
DomainQuery: &instance.DomainsQuery{
Domains: []string{domain},
Domains: []string{isoInstance.Domain},
},
},
}},
},
want: []*instance.Instance{{
Id: instanceID,
Id: isoInstance.ID(),
}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
resp, err := Tester.Client.System.ListInstances(SystemCTX, tt.req)
resp, err := integration.SystemClient().ListInstances(CTX, tt.req)
if tt.wantErr {
require.Error(t, err)
return
@@ -14,6 +14,7 @@ import (
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/integration"
"github.com/zitadel/zitadel/pkg/grpc/admin"
"github.com/zitadel/zitadel/pkg/grpc/auth"
"github.com/zitadel/zitadel/pkg/grpc/management"
@@ -21,44 +22,47 @@ import (
)
func TestServer_Limits_AuditLogRetention(t *testing.T) {
_, instanceID, _, iamOwnerCtx := Tester.UseIsolatedInstance(t, CTX, SystemCTX)
userID, projectID, appID, projectGrantID := seedObjects(iamOwnerCtx, t)
t.Parallel()
isoInstance := integration.NewInstance(CTX)
iamOwnerCtx := isoInstance.WithAuthorization(CTX, integration.UserTypeIAMOwner)
userID, projectID, appID, projectGrantID := seedObjects(iamOwnerCtx, t, isoInstance.Client)
beforeTime := time.Now()
farPast := timestamppb.New(beforeTime.Add(-10 * time.Hour).UTC())
zeroCounts := &eventCounts{}
seededCount := requireEventually(t, iamOwnerCtx, userID, projectID, appID, projectGrantID, func(c assert.TestingT, counts *eventCounts) {
seededCount := requireEventually(t, iamOwnerCtx, isoInstance.Client, userID, projectID, appID, projectGrantID, func(c assert.TestingT, counts *eventCounts) {
counts.assertAll(t, c, "seeded events are > 0", assert.Greater, zeroCounts)
}, "wait for seeded event assertions to pass")
produceEvents(iamOwnerCtx, t, userID, appID, projectID, projectGrantID)
addedCount := requireEventually(t, iamOwnerCtx, userID, projectID, appID, projectGrantID, func(c assert.TestingT, counts *eventCounts) {
produceEvents(iamOwnerCtx, t, isoInstance.Client, userID, appID, projectID, projectGrantID)
addedCount := requireEventually(t, iamOwnerCtx, isoInstance.Client, userID, projectID, appID, projectGrantID, func(c assert.TestingT, counts *eventCounts) {
counts.assertAll(t, c, "added events are > seeded events", assert.Greater, seededCount)
}, "wait for added event assertions to pass")
_, err := Tester.Client.System.SetLimits(SystemCTX, &system.SetLimitsRequest{
InstanceId: instanceID,
_, err := integration.SystemClient().SetLimits(CTX, &system.SetLimitsRequest{
InstanceId: isoInstance.ID(),
AuditLogRetention: durationpb.New(time.Now().Sub(beforeTime)),
})
require.NoError(t, err)
var limitedCounts *eventCounts
requireEventually(t, iamOwnerCtx, userID, projectID, appID, projectGrantID, func(c assert.TestingT, counts *eventCounts) {
requireEventually(t, iamOwnerCtx, isoInstance.Client, userID, projectID, appID, projectGrantID, func(c assert.TestingT, counts *eventCounts) {
counts.assertAll(t, c, "limited events < added events", assert.Less, addedCount)
counts.assertAll(t, c, "limited events > 0", assert.Greater, zeroCounts)
limitedCounts = counts
}, "wait for limited event assertions to pass")
listedEvents, err := Tester.Client.Admin.ListEvents(iamOwnerCtx, &admin.ListEventsRequest{CreationDateFilter: &admin.ListEventsRequest_From{
listedEvents, err := isoInstance.Client.Admin.ListEvents(iamOwnerCtx, &admin.ListEventsRequest{CreationDateFilter: &admin.ListEventsRequest_From{
From: farPast,
}})
require.NoError(t, err)
assert.LessOrEqual(t, len(listedEvents.GetEvents()), limitedCounts.all, "ListEvents with from query older than retention doesn't return more events")
listedEvents, err = Tester.Client.Admin.ListEvents(iamOwnerCtx, &admin.ListEventsRequest{CreationDateFilter: &admin.ListEventsRequest_Range{Range: &admin.ListEventsRequestCreationDateRange{
listedEvents, err = isoInstance.Client.Admin.ListEvents(iamOwnerCtx, &admin.ListEventsRequest{CreationDateFilter: &admin.ListEventsRequest_Range{Range: &admin.ListEventsRequestCreationDateRange{
Since: farPast,
}}})
require.NoError(t, err)
assert.LessOrEqual(t, len(listedEvents.GetEvents()), limitedCounts.all, "ListEvents with since query older than retention doesn't return more events")
_, err = Tester.Client.System.ResetLimits(SystemCTX, &system.ResetLimitsRequest{
InstanceId: instanceID,
_, err = integration.SystemClient().ResetLimits(CTX, &system.ResetLimitsRequest{
InstanceId: isoInstance.ID(),
})
require.NoError(t, err)
requireEventually(t, iamOwnerCtx, userID, projectID, appID, projectGrantID, func(c assert.TestingT, counts *eventCounts) {
requireEventually(t, iamOwnerCtx, isoInstance.Client, userID, projectID, appID, projectGrantID, func(c assert.TestingT, counts *eventCounts) {
counts.assertAll(t, c, "with reset limit, added events are > seeded events", assert.Greater, seededCount)
}, "wait for reset event assertions to pass")
}
@@ -66,6 +70,7 @@ func TestServer_Limits_AuditLogRetention(t *testing.T) {
func requireEventually(
t *testing.T,
ctx context.Context,
cc *integration.Client,
userID, projectID, appID, projectGrantID string,
assertCounts func(assert.TestingT, *eventCounts),
msg string,
@@ -75,7 +80,7 @@ func requireEventually(
countCtx, cancel := context.WithTimeout(ctx, countTimeout)
defer cancel()
require.EventuallyWithT(t, func(c *assert.CollectT) {
counts = countEvents(countCtx, t, userID, projectID, appID, projectGrantID)
counts = countEvents(countCtx, c, cc, userID, projectID, appID, projectGrantID)
assertCounts(c, counts)
}, assertTimeout, time.Second, msg)
return counts
@@ -91,68 +96,68 @@ func randomString(resourceType string, n int) string {
return "test" + resourceType + "-" + string(b)
}
func seedObjects(ctx context.Context, t *testing.T) (string, string, string, string) {
func seedObjects(ctx context.Context, t *testing.T, cc *integration.Client) (string, string, string, string) {
t.Helper()
project, err := Tester.Client.Mgmt.AddProject(ctx, &management.AddProjectRequest{
project, err := cc.Mgmt.AddProject(ctx, &management.AddProjectRequest{
Name: randomString("project", 5),
})
require.NoError(t, err)
app, err := Tester.Client.Mgmt.AddOIDCApp(ctx, &management.AddOIDCAppRequest{
app, err := cc.Mgmt.AddOIDCApp(ctx, &management.AddOIDCAppRequest{
Name: randomString("app", 5),
ProjectId: project.GetId(),
})
org, err := Tester.Client.Mgmt.AddOrg(ctx, &management.AddOrgRequest{
org, err := cc.Mgmt.AddOrg(ctx, &management.AddOrgRequest{
Name: randomString("org", 5),
})
require.NoError(t, err)
role := randomString("role", 5)
require.NoError(t, err)
_, err = Tester.Client.Mgmt.AddProjectRole(ctx, &management.AddProjectRoleRequest{
_, err = cc.Mgmt.AddProjectRole(ctx, &management.AddProjectRoleRequest{
ProjectId: project.GetId(),
RoleKey: role,
DisplayName: role,
})
require.NoError(t, err)
projectGrant, err := Tester.Client.Mgmt.AddProjectGrant(ctx, &management.AddProjectGrantRequest{
projectGrant, err := cc.Mgmt.AddProjectGrant(ctx, &management.AddProjectGrantRequest{
ProjectId: project.GetId(),
GrantedOrgId: org.GetId(),
RoleKeys: []string{role},
})
require.NoError(t, err)
user, err := Tester.Client.Auth.GetMyUser(ctx, &auth.GetMyUserRequest{})
user, err := cc.Auth.GetMyUser(ctx, &auth.GetMyUserRequest{})
require.NoError(t, err)
userID := user.GetUser().GetId()
requireUserEvent(ctx, t, userID)
requireUserEvent(ctx, t, cc, userID)
return userID, project.GetId(), app.GetAppId(), projectGrant.GetGrantId()
}
func produceEvents(ctx context.Context, t *testing.T, machineID, appID, projectID, grantID string) {
func produceEvents(ctx context.Context, t *testing.T, cc *integration.Client, machineID, appID, projectID, grantID string) {
t.Helper()
_, err := Tester.Client.Mgmt.UpdateOrg(ctx, &management.UpdateOrgRequest{
_, err := cc.Mgmt.UpdateOrg(ctx, &management.UpdateOrgRequest{
Name: randomString("org", 5),
})
require.NoError(t, err)
_, err = Tester.Client.Mgmt.UpdateProject(ctx, &management.UpdateProjectRequest{
_, err = cc.Mgmt.UpdateProject(ctx, &management.UpdateProjectRequest{
Id: projectID,
Name: randomString("project", 5),
})
require.NoError(t, err)
_, err = Tester.Client.Mgmt.UpdateApp(ctx, &management.UpdateAppRequest{
_, err = cc.Mgmt.UpdateApp(ctx, &management.UpdateAppRequest{
AppId: appID,
ProjectId: projectID,
Name: randomString("app", 5),
})
require.NoError(t, err)
requireUserEvent(ctx, t, machineID)
_, err = Tester.Client.Mgmt.UpdateProjectGrant(ctx, &management.UpdateProjectGrantRequest{
requireUserEvent(ctx, t, cc, machineID)
_, err = cc.Mgmt.UpdateProjectGrant(ctx, &management.UpdateProjectGrantRequest{
ProjectId: projectID,
GrantId: grantID,
})
require.NoError(t, err)
}
func requireUserEvent(ctx context.Context, t *testing.T, machineID string) {
_, err := Tester.Client.Mgmt.UpdateMachine(ctx, &management.UpdateMachineRequest{
func requireUserEvent(ctx context.Context, t *testing.T, cc *integration.Client, machineID string) {
_, err := cc.Mgmt.UpdateMachine(ctx, &management.UpdateMachineRequest{
UserId: machineID,
Name: randomString("machine", 5),
})
@@ -175,51 +180,50 @@ func (e *eventCounts) assertAll(t *testing.T, c assert.TestingT, name string, co
})
}
func countEvents(ctx context.Context, t *testing.T, userID, projectID, appID, grantID string) *eventCounts {
t.Helper()
func countEvents(ctx context.Context, t assert.TestingT, cc *integration.Client, userID, projectID, appID, grantID string) *eventCounts {
counts := new(eventCounts)
var wg sync.WaitGroup
wg.Add(7)
go func() {
defer wg.Done()
result, err := Tester.Client.Admin.ListEvents(ctx, &admin.ListEventsRequest{})
require.NoError(t, err)
result, err := cc.Admin.ListEvents(ctx, &admin.ListEventsRequest{})
assert.NoError(t, err)
counts.all = len(result.GetEvents())
}()
go func() {
defer wg.Done()
result, err := Tester.Client.Auth.ListMyUserChanges(ctx, &auth.ListMyUserChangesRequest{})
require.NoError(t, err)
result, err := cc.Auth.ListMyUserChanges(ctx, &auth.ListMyUserChangesRequest{})
assert.NoError(t, err)
counts.myUser = len(result.GetResult())
}()
go func() {
defer wg.Done()
result, err := Tester.Client.Mgmt.ListUserChanges(ctx, &management.ListUserChangesRequest{UserId: userID})
require.NoError(t, err)
result, err := cc.Mgmt.ListUserChanges(ctx, &management.ListUserChangesRequest{UserId: userID})
assert.NoError(t, err)
counts.aUser = len(result.GetResult())
}()
go func() {
defer wg.Done()
result, err := Tester.Client.Mgmt.ListAppChanges(ctx, &management.ListAppChangesRequest{ProjectId: projectID, AppId: appID})
require.NoError(t, err)
result, err := cc.Mgmt.ListAppChanges(ctx, &management.ListAppChangesRequest{ProjectId: projectID, AppId: appID})
assert.NoError(t, err)
counts.app = len(result.GetResult())
}()
go func() {
defer wg.Done()
result, err := Tester.Client.Mgmt.ListOrgChanges(ctx, &management.ListOrgChangesRequest{})
require.NoError(t, err)
result, err := cc.Mgmt.ListOrgChanges(ctx, &management.ListOrgChangesRequest{})
assert.NoError(t, err)
counts.org = len(result.GetResult())
}()
go func() {
defer wg.Done()
result, err := Tester.Client.Mgmt.ListProjectChanges(ctx, &management.ListProjectChangesRequest{ProjectId: projectID})
require.NoError(t, err)
result, err := cc.Mgmt.ListProjectChanges(ctx, &management.ListProjectChangesRequest{ProjectId: projectID})
assert.NoError(t, err)
counts.project = len(result.GetResult())
}()
go func() {
defer wg.Done()
result, err := Tester.Client.Mgmt.ListProjectGrantChanges(ctx, &management.ListProjectGrantChangesRequest{ProjectId: projectID, GrantId: grantID})
require.NoError(t, err)
result, err := cc.Mgmt.ListProjectGrantChanges(ctx, &management.ListProjectGrantChangesRequest{ProjectId: projectID, GrantId: grantID})
assert.NoError(t, err)
counts.grant = len(result.GetResult())
}()
wg.Wait()
@@ -20,41 +20,35 @@ import (
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/durationpb"
"github.com/zitadel/zitadel/internal/api/authz"
"github.com/zitadel/zitadel/internal/query"
"github.com/zitadel/zitadel/internal/integration"
"github.com/zitadel/zitadel/pkg/grpc/admin"
"github.com/zitadel/zitadel/pkg/grpc/system"
)
func TestServer_Limits_Block(t *testing.T) {
domain, instanceID, _, iamOwnerCtx := Tester.UseIsolatedInstance(t, CTX, SystemCTX)
t.Parallel()
isoInstance := integration.NewInstance(CTX)
iamOwnerCtx := isoInstance.WithAuthorization(CTX, integration.UserTypeIAMOwner)
tests := []*test{
publicAPIBlockingTest(domain),
publicAPIBlockingTest(isoInstance.Domain),
{
name: "mutating API",
testGrpc: func(tt assert.TestingT, expectBlocked bool) {
randomGrpcIdpName := randomString("idp-grpc", 5)
_, err := Tester.Client.Admin.AddGitHubProvider(iamOwnerCtx, &admin.AddGitHubProviderRequest{
_, err := isoInstance.Client.Admin.AddGitHubProvider(iamOwnerCtx, &admin.AddGitHubProviderRequest{
Name: randomGrpcIdpName,
ClientId: "client-id",
ClientSecret: "client-secret",
})
assertGrpcError(tt, err, expectBlocked)
//nolint:contextcheck
idpExists := idpExistsCondition(tt, instanceID, randomGrpcIdpName)
if expectBlocked {
// We ensure that the idp really is not created
assert.Neverf(tt, idpExists, 5*time.Second, 1*time.Second, "idp should never be created")
} else {
assert.Eventuallyf(tt, idpExists, 5*time.Second, 1*time.Second, "idp should be created")
}
},
testHttp: func(tt assert.TestingT) (*http.Request, error, func(assert.TestingT, *http.Response, bool)) {
randomHttpIdpName := randomString("idp-http", 5)
req, err := http.NewRequestWithContext(
CTX,
"POST",
fmt.Sprintf("http://%s/admin/v1/idps/github", net.JoinHostPort(domain, "8080")),
fmt.Sprintf("http://%s/admin/v1/idps/github", net.JoinHostPort(isoInstance.Domain, "8080")),
strings.NewReader(`{
"name": "`+randomHttpIdpName+`",
"clientId": "client-id",
@@ -64,7 +58,7 @@ func TestServer_Limits_Block(t *testing.T) {
if err != nil {
return nil, err, nil
}
req.Header.Set("Authorization", Tester.BearerToken(iamOwnerCtx))
req.Header.Set("Authorization", isoInstance.BearerToken(iamOwnerCtx))
return req, nil, func(ttt assert.TestingT, response *http.Response, expectBlocked bool) {
assertLimitResponse(ttt, response, expectBlocked)
assertSetLimitingCookie(ttt, response, expectBlocked)
@@ -76,7 +70,7 @@ func TestServer_Limits_Block(t *testing.T) {
req, err := http.NewRequestWithContext(
CTX,
"GET",
fmt.Sprintf("http://%s/.well-known/openid-configuration", net.JoinHostPort(domain, "8080")),
fmt.Sprintf("http://%s/.well-known/openid-configuration", net.JoinHostPort(isoInstance.Domain, "8080")),
nil,
)
return req, err, func(ttt assert.TestingT, response *http.Response, expectBlocked bool) {
@@ -90,7 +84,7 @@ func TestServer_Limits_Block(t *testing.T) {
req, err := http.NewRequestWithContext(
CTX,
"GET",
fmt.Sprintf("http://%s/ui/login/login/externalidp/callback", net.JoinHostPort(domain, "8080")),
fmt.Sprintf("http://%s/ui/login/login/externalidp/callback", net.JoinHostPort(isoInstance.Domain, "8080")),
nil,
)
return req, err, func(ttt assert.TestingT, response *http.Response, expectBlocked bool) {
@@ -109,7 +103,7 @@ func TestServer_Limits_Block(t *testing.T) {
req, err := http.NewRequestWithContext(
CTX,
"GET",
fmt.Sprintf("http://%s/ui/console/", net.JoinHostPort(domain, "8080")),
fmt.Sprintf("http://%s/ui/console/", net.JoinHostPort(isoInstance.Domain, "8080")),
nil,
)
return req, err, func(ttt assert.TestingT, response *http.Response, expectBlocked bool) {
@@ -125,7 +119,7 @@ func TestServer_Limits_Block(t *testing.T) {
req, err := http.NewRequestWithContext(
CTX,
"GET",
fmt.Sprintf("http://%s/ui/console/assets/environment.json", net.JoinHostPort(domain, "8080")),
fmt.Sprintf("http://%s/ui/console/assets/environment.json", net.JoinHostPort(isoInstance.Domain, "8080")),
nil,
)
return req, err, func(ttt assert.TestingT, response *http.Response, expectBlocked bool) {
@@ -142,14 +136,14 @@ func TestServer_Limits_Block(t *testing.T) {
}
},
}}
_, err := Tester.Client.System.SetLimits(SystemCTX, &system.SetLimitsRequest{
InstanceId: instanceID,
_, err := integration.SystemClient().SetLimits(CTX, &system.SetLimitsRequest{
InstanceId: isoInstance.ID(),
Block: gu.Ptr(true),
})
require.NoError(t, err)
// The following call ensures that an undefined bool is not deserialized to false
_, err = Tester.Client.System.SetLimits(SystemCTX, &system.SetLimitsRequest{
InstanceId: instanceID,
_, err = integration.SystemClient().SetLimits(CTX, &system.SetLimitsRequest{
InstanceId: isoInstance.ID(),
AuditLogRetention: durationpb.New(time.Hour),
})
require.NoError(t, err)
@@ -160,8 +154,8 @@ func TestServer_Limits_Block(t *testing.T) {
testBlockingAPI(t, tt, true, isFirst)
})
}
_, err = Tester.Client.System.SetLimits(SystemCTX, &system.SetLimitsRequest{
InstanceId: instanceID,
_, err = integration.SystemClient().SetLimits(CTX, &system.SetLimitsRequest{
InstanceId: isoInstance.ID(),
Block: gu.Ptr(false),
})
require.NoError(t, err)
@@ -183,7 +177,7 @@ type test struct {
func testBlockingAPI(t *testing.T, tt *test, expectBlocked bool, isFirst bool) {
req, err, assertResponse := tt.testHttp(t)
require.NoError(t, err)
testHTTP := func(tt assert.TestingT) {
testHTTP := func(t require.TestingT) {
resp, err := (&http.Client{
// Don't follow redirects
CheckRedirect: func(req *http.Request, via []*http.Request) error {
@@ -200,7 +194,7 @@ func testBlockingAPI(t *testing.T, tt *test, expectBlocked bool, isFirst bool) {
// limits are eventually consistent, so we need to wait for the blocking to be set on the first test
assert.EventuallyWithT(t, func(c *assert.CollectT) {
testHTTP(c)
}, 15*time.Second, time.Second, "wait for blocking to be set")
}, time.Minute, time.Second, "wait for blocking to be set")
} else {
testHTTP(t)
}
@@ -249,7 +243,7 @@ func assertSetLimitingCookie(t assert.TestingT, response *http.Response, expectS
return
}
}
assert.FailNow(t, "cookie not found")
assert.Fail(t, "cookie not found")
}
func assertGrpcError(t assert.TestingT, err error, expectBlocked bool) {
@@ -268,20 +262,3 @@ func assertLimitResponse(t assert.TestingT, response *http.Response, expectBlock
assert.GreaterOrEqual(t, response.StatusCode, 200)
assert.Less(t, response.StatusCode, 300)
}
func idpExistsCondition(t assert.TestingT, instanceID, idpName string) func() bool {
return func() bool {
nameQuery, err := query.NewIDPTemplateNameSearchQuery(query.TextEquals, idpName)
assert.NoError(t, err)
instanceQuery, err := query.NewIDPTemplateResourceOwnerSearchQuery(instanceID)
assert.NoError(t, err)
idps, err := Tester.Queries.IDPTemplates(authz.WithInstanceID(CTX, instanceID), &query.IDPTemplateSearchQueries{
Queries: []query.SearchQuery{
instanceQuery,
nameQuery,
},
}, false)
assert.NoError(t, err)
return len(idps.Templates) > 0
}
}
@@ -18,7 +18,7 @@ func TestServer_Limits_Bulk(t *testing.T) {
instances := make([]*instance, len)
for i := 0; i < len; i++ {
domain := integration.RandString(5) + ".integration.localhost"
resp, err := Tester.Client.System.CreateInstance(SystemCTX, &system.CreateInstanceRequest{
resp, err := integration.SystemClient().CreateInstance(CTX, &system.CreateInstanceRequest{
InstanceName: "testinstance",
CustomDomain: domain,
Owner: &system.CreateInstanceRequest_Machine_{
@@ -31,7 +31,7 @@ func TestServer_Limits_Bulk(t *testing.T) {
require.NoError(t, err)
instances[i] = &instance{domain, resp.GetInstanceId()}
}
resp, err := Tester.Client.System.BulkSetLimits(SystemCTX, &system.BulkSetLimitsRequest{
resp, err := integration.SystemClient().BulkSetLimits(CTX, &system.BulkSetLimitsRequest{
Limits: []*system.SetLimitsRequest{{
InstanceId: instances[0].id,
Block: gu.Ptr(true),
@@ -14,21 +14,25 @@ import (
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/zitadel/zitadel/internal/integration"
"github.com/zitadel/zitadel/internal/integration/sink"
"github.com/zitadel/zitadel/internal/repository/quota"
"github.com/zitadel/zitadel/pkg/grpc/admin"
quota_pb "github.com/zitadel/zitadel/pkg/grpc/quota"
"github.com/zitadel/zitadel/pkg/grpc/system"
)
var callURL = "http://localhost:" + integration.PortQuotaServer
var callURL = sink.CallURL(sink.ChannelQuota)
func TestServer_QuotaNotification_Limit(t *testing.T) {
instance := integration.NewInstance(CTX)
iamCTX := instance.WithAuthorization(CTX, integration.UserTypeIAMOwner)
amount := 10
percent := 50
percentAmount := amount * percent / 100
_, err := Tester.Client.System.SetQuota(SystemCTX, &system.SetQuotaRequest{
InstanceId: Tester.Instance.InstanceID(),
_, err := integration.SystemClient().SetQuota(CTX, &system.SetQuotaRequest{
InstanceId: instance.Instance.Id,
Unit: quota_pb.Unit_UNIT_REQUESTS_ALL_AUTHENTICATED,
From: timestamppb.Now(),
ResetInterval: durationpb.New(time.Minute * 5),
@@ -49,30 +53,35 @@ func TestServer_QuotaNotification_Limit(t *testing.T) {
})
require.NoError(t, err)
sub := sink.Subscribe(CTX, sink.ChannelQuota)
defer sub.Close()
for i := 0; i < percentAmount; i++ {
_, err := Tester.Client.Admin.GetDefaultOrg(IAMOwnerCTX, &admin.GetDefaultOrgRequest{})
_, err := instance.Client.Admin.GetDefaultOrg(iamCTX, &admin.GetDefaultOrgRequest{})
require.NoErrorf(t, err, "error in %d call of %d", i, percentAmount)
}
awaitNotification(t, Tester.QuotaNotificationChan, quota.RequestsAllAuthenticated, percent)
awaitNotification(t, sub, quota.RequestsAllAuthenticated, percent)
for i := 0; i < (amount - percentAmount); i++ {
_, err := Tester.Client.Admin.GetDefaultOrg(IAMOwnerCTX, &admin.GetDefaultOrgRequest{})
_, err := instance.Client.Admin.GetDefaultOrg(iamCTX, &admin.GetDefaultOrgRequest{})
require.NoErrorf(t, err, "error in %d call of %d", i, percentAmount)
}
awaitNotification(t, Tester.QuotaNotificationChan, quota.RequestsAllAuthenticated, 100)
awaitNotification(t, sub, quota.RequestsAllAuthenticated, 100)
_, limitErr := Tester.Client.Admin.GetDefaultOrg(IAMOwnerCTX, &admin.GetDefaultOrgRequest{})
_, limitErr := instance.Client.Admin.GetDefaultOrg(iamCTX, &admin.GetDefaultOrgRequest{})
require.Error(t, limitErr)
}
func TestServer_QuotaNotification_NoLimit(t *testing.T) {
_, instanceID, _, IAMOwnerCTX := Tester.UseIsolatedInstance(t, CTX, SystemCTX)
instance := integration.NewInstance(CTX)
iamCTX := instance.WithAuthorization(CTX, integration.UserTypeIAMOwner)
amount := 10
percent := 50
percentAmount := amount * percent / 100
_, err := Tester.Client.System.SetQuota(SystemCTX, &system.SetQuotaRequest{
InstanceId: instanceID,
_, err := integration.SystemClient().SetQuota(CTX, &system.SetQuotaRequest{
InstanceId: instance.Instance.Id,
Unit: quota_pb.Unit_UNIT_REQUESTS_ALL_AUTHENTICATED,
From: timestamppb.Now(),
ResetInterval: durationpb.New(time.Minute * 5),
@@ -93,34 +102,39 @@ func TestServer_QuotaNotification_NoLimit(t *testing.T) {
})
require.NoError(t, err)
sub := sink.Subscribe(CTX, sink.ChannelQuota)
defer sub.Close()
for i := 0; i < percentAmount; i++ {
_, err := Tester.Client.Admin.GetDefaultOrg(IAMOwnerCTX, &admin.GetDefaultOrgRequest{})
_, err := instance.Client.Admin.GetDefaultOrg(iamCTX, &admin.GetDefaultOrgRequest{})
require.NoErrorf(t, err, "error in %d call of %d", i, percentAmount)
}
awaitNotification(t, Tester.QuotaNotificationChan, quota.RequestsAllAuthenticated, percent)
awaitNotification(t, sub, quota.RequestsAllAuthenticated, percent)
for i := 0; i < (amount - percentAmount); i++ {
_, err := Tester.Client.Admin.GetDefaultOrg(IAMOwnerCTX, &admin.GetDefaultOrgRequest{})
_, err := instance.Client.Admin.GetDefaultOrg(iamCTX, &admin.GetDefaultOrgRequest{})
require.NoErrorf(t, err, "error in %d call of %d", i, percentAmount)
}
awaitNotification(t, Tester.QuotaNotificationChan, quota.RequestsAllAuthenticated, 100)
awaitNotification(t, sub, quota.RequestsAllAuthenticated, 100)
for i := 0; i < amount; i++ {
_, err := Tester.Client.Admin.GetDefaultOrg(IAMOwnerCTX, &admin.GetDefaultOrgRequest{})
_, err := instance.Client.Admin.GetDefaultOrg(iamCTX, &admin.GetDefaultOrgRequest{})
require.NoErrorf(t, err, "error in %d call of %d", i, percentAmount)
}
awaitNotification(t, Tester.QuotaNotificationChan, quota.RequestsAllAuthenticated, 200)
awaitNotification(t, sub, quota.RequestsAllAuthenticated, 200)
_, limitErr := Tester.Client.Admin.GetDefaultOrg(IAMOwnerCTX, &admin.GetDefaultOrgRequest{})
_, limitErr := instance.Client.Admin.GetDefaultOrg(iamCTX, &admin.GetDefaultOrgRequest{})
require.NoError(t, limitErr)
}
func awaitNotification(t *testing.T, bodies chan []byte, unit quota.Unit, percent int) {
func awaitNotification(t *testing.T, sub *sink.Subscription, unit quota.Unit, percent int) {
for {
select {
case body := <-bodies:
case req, ok := <-sub.Recv():
require.True(t, ok, "channel closed")
plain := new(bytes.Buffer)
if err := json.Indent(plain, body, "", " "); err != nil {
if err := json.Indent(plain, req.Body, "", " "); err != nil {
t.Fatal(err)
}
t.Log("received notificationDueEvent", plain.String())
@@ -132,7 +146,7 @@ func awaitNotification(t *testing.T, bodies chan []byte, unit quota.Unit, percen
Threshold uint16 `json:"threshold"`
Usage uint64 `json:"usage"`
}{}
if err := json.Unmarshal(body, &event); err != nil {
if err := json.Unmarshal(req.Body, &event); err != nil {
t.Error(err)
}
if event.ID == "" {
@@ -148,10 +162,10 @@ func awaitNotification(t *testing.T, bodies chan []byte, unit quota.Unit, percen
}
func TestServer_AddAndRemoveQuota(t *testing.T) {
_, instanceID, _, _ := Tester.UseIsolatedInstance(t, CTX, SystemCTX)
instance := integration.NewInstance(CTX)
got, err := Tester.Client.System.SetQuota(SystemCTX, &system.SetQuotaRequest{
InstanceId: instanceID,
got, err := integration.SystemClient().SetQuota(CTX, &system.SetQuotaRequest{
InstanceId: instance.Instance.Id,
Unit: quota_pb.Unit_UNIT_REQUESTS_ALL_AUTHENTICATED,
From: timestamppb.Now(),
ResetInterval: durationpb.New(time.Minute),
@@ -166,10 +180,10 @@ func TestServer_AddAndRemoveQuota(t *testing.T) {
},
})
require.NoError(t, err)
require.Equal(t, got.Details.ResourceOwner, instanceID)
require.Equal(t, got.Details.ResourceOwner, instance.Instance.Id)
gotAlreadyExisting, errAlreadyExisting := Tester.Client.System.SetQuota(SystemCTX, &system.SetQuotaRequest{
InstanceId: instanceID,
gotAlreadyExisting, errAlreadyExisting := integration.SystemClient().SetQuota(CTX, &system.SetQuotaRequest{
InstanceId: instance.Instance.Id,
Unit: quota_pb.Unit_UNIT_REQUESTS_ALL_AUTHENTICATED,
From: timestamppb.Now(),
ResetInterval: durationpb.New(time.Minute),
@@ -184,17 +198,17 @@ func TestServer_AddAndRemoveQuota(t *testing.T) {
},
})
require.Nil(t, errAlreadyExisting)
require.Equal(t, gotAlreadyExisting.Details.ResourceOwner, instanceID)
require.Equal(t, gotAlreadyExisting.Details.ResourceOwner, instance.Instance.Id)
gotRemove, errRemove := Tester.Client.System.RemoveQuota(SystemCTX, &system.RemoveQuotaRequest{
InstanceId: instanceID,
gotRemove, errRemove := integration.SystemClient().RemoveQuota(CTX, &system.RemoveQuotaRequest{
InstanceId: instance.Instance.Id,
Unit: quota_pb.Unit_UNIT_REQUESTS_ALL_AUTHENTICATED,
})
require.NoError(t, errRemove)
require.Equal(t, gotRemove.Details.ResourceOwner, instanceID)
require.Equal(t, gotRemove.Details.ResourceOwner, instance.Instance.Id)
gotRemoveAlready, errRemoveAlready := Tester.Client.System.RemoveQuota(SystemCTX, &system.RemoveQuotaRequest{
InstanceId: instanceID,
gotRemoveAlready, errRemoveAlready := integration.SystemClient().RemoveQuota(CTX, &system.RemoveQuotaRequest{
InstanceId: instance.Instance.Id,
Unit: quota_pb.Unit_UNIT_REQUESTS_ALL_AUTHENTICATED,
})
require.Error(t, errRemoveAlready)
@@ -0,0 +1,23 @@
//go:build integration
package quotas_enabled_test
import (
"context"
"os"
"testing"
"time"
)
var (
CTX context.Context
)
func TestMain(m *testing.M) {
os.Exit(func() int {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
CTX = ctx
return m.Run()
}())
}
@@ -0,0 +1,24 @@
//go:build integration
package system_test
import (
"context"
"os"
"testing"
"time"
)
var (
CTX context.Context
)
func TestMain(m *testing.M) {
os.Exit(func() int {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
CTX = ctx
return m.Run()
}())
}
@@ -1,37 +0,0 @@
//go:build integration
package quotas_enabled_test
import (
"context"
"os"
"testing"
"time"
"github.com/zitadel/zitadel/internal/integration"
)
var (
CTX context.Context
SystemCTX context.Context
IAMOwnerCTX context.Context
Tester *integration.Tester
)
func TestMain(m *testing.M) {
os.Exit(func() int {
ctx, _, cancel := integration.Contexts(5 * time.Minute)
defer cancel()
CTX = ctx
Tester = integration.NewTester(ctx, `
Quotas:
Access:
Enabled: true
`)
defer Tester.Done()
SystemCTX = Tester.WithAuthorization(ctx, integration.SystemUser)
IAMOwnerCTX = Tester.WithAuthorization(ctx, integration.IAMOwner)
return m.Run()
}())
}
@@ -1,32 +0,0 @@
//go:build integration
package system_test
import (
"context"
"os"
"testing"
"time"
"github.com/zitadel/zitadel/internal/integration"
)
var (
CTX context.Context
SystemCTX context.Context
Tester *integration.Tester
)
func TestMain(m *testing.M) {
os.Exit(func() int {
ctx, _, cancel := integration.Contexts(5 * time.Minute)
defer cancel()
CTX = ctx
Tester = integration.NewTester(ctx)
defer Tester.Done()
SystemCTX = Tester.WithAuthorization(ctx, integration.SystemUser)
return m.Run()
}())
}