Skip to content

Commit

Permalink
[BCF-2488] Fix flake in TestShell_Autologin (and others) (#10677)
Browse files Browse the repository at this point in the history
* [BCF-2488] Fix flakey TestShell_Autologin caused by lock timeout

* [BCF-2488] Fix flakey TestShell_Autologin caused by lock timeout
  • Loading branch information
cedric-cordenier authored Sep 19, 2023
1 parent 562ac5c commit 7db18d9
Show file tree
Hide file tree
Showing 34 changed files with 138 additions and 119 deletions.
2 changes: 1 addition & 1 deletion core/cmd/renderer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func TestRendererTable_RenderConfigurationV2(t *testing.T) {
app := cltest.NewApplicationEVMDisabled(t)
wantUser, wantEffective := app.Config.ConfigTOML()
require.NoError(t, app.Start(testutils.Context(t)))
client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

t.Run("effective", func(t *testing.T) {
resp, cleanup := client.Get("/v2/config/v2")
Expand Down
43 changes: 31 additions & 12 deletions core/internal/cltest/cltest.go
Original file line number Diff line number Diff line change
Expand Up @@ -595,10 +595,10 @@ func (ta *TestApplication) Stop() error {
return err
}

func (ta *TestApplication) MustSeedNewSession(roleFixtureUserAPIEmail string) (id string) {
func (ta *TestApplication) MustSeedNewSession(email string) (id string) {
session := NewSession()
ta.Logger.Infof("TestApplication creating session (id: %s, email: %s, last used: %s)", session.ID, roleFixtureUserAPIEmail, session.LastUsed.String())
err := ta.GetSqlxDB().Get(&id, `INSERT INTO sessions (id, email, last_used, created_at) VALUES ($1, $2, $3, NOW()) RETURNING id`, session.ID, roleFixtureUserAPIEmail, session.LastUsed)
ta.Logger.Infof("TestApplication creating session (id: %s, email: %s, last used: %s)", session.ID, email, session.LastUsed.String())
err := ta.GetSqlxDB().Get(&id, `INSERT INTO sessions (id, email, last_used, created_at) VALUES ($1, $2, $3, NOW()) RETURNING id`, session.ID, email, session.LastUsed)
require.NoError(ta.t, err)
return id
}
Expand All @@ -610,10 +610,29 @@ func (ta *TestApplication) Import(content string) {
require.NoError(ta.t, err)
}

func (ta *TestApplication) NewHTTPClient(roleFixtureUserAPIEmail string) HTTPClientCleaner {
type User struct {
Email string
Role clsessions.UserRole
}

func (ta *TestApplication) NewHTTPClient(user *User) HTTPClientCleaner {
ta.t.Helper()

sessionID := ta.MustSeedNewSession(roleFixtureUserAPIEmail)
if user.Email == "" {
user.Email = fmt.Sprintf("%[email protected]", uuid.New())
}

if user.Role == "" {
user.Role = clsessions.UserRoleAdmin
}

u, err := clsessions.NewUser(user.Email, Password, user.Role)
require.NoError(ta.t, err)

err = ta.SessionORM().CreateUser(&u)
require.NoError(ta.t, err)

sessionID := ta.MustSeedNewSession(user.Email)

return HTTPClientCleaner{
HTTPClient: NewMockAuthenticatedHTTPClient(ta.Logger, ta.NewClientOpts(), sessionID),
Expand All @@ -627,7 +646,7 @@ func (ta *TestApplication) NewClientOpts() cmd.ClientOpts {

// NewShellAndRenderer creates a new cmd.Shell for the test application
func (ta *TestApplication) NewShellAndRenderer() (*cmd.Shell, *RendererMock) {
sessionID := ta.MustSeedNewSession(APIEmailAdmin)
hc := ta.NewHTTPClient(&User{})
r := &RendererMock{}
lggr := logger.TestLogger(ta.t)
client := &cmd.Shell{
Expand All @@ -637,7 +656,7 @@ func (ta *TestApplication) NewShellAndRenderer() (*cmd.Shell, *RendererMock) {
AppFactory: seededAppFactory{ta.ChainlinkApplication},
FallbackAPIInitializer: NewMockAPIInitializer(ta.t),
Runner: EmptyRunner{},
HTTP: NewMockAuthenticatedHTTPClient(ta.Logger, ta.NewClientOpts(), sessionID),
HTTP: hc.HTTPClient,
CookieAuthenticator: MockCookieAuthenticator{t: ta.t},
FileSessionRequestBuilder: &MockSessionRequestBuilder{},
PromptingSessionRequestBuilder: &MockSessionRequestBuilder{},
Expand Down Expand Up @@ -789,7 +808,7 @@ func ParseJSONAPIResponseMetaCount(input []byte) (int, error) {
func CreateJobViaWeb(t testing.TB, app *TestApplication, request []byte) job.Job {
t.Helper()

client := app.NewHTTPClient(APIEmailAdmin)
client := app.NewHTTPClient(&User{})
resp, cleanup := client.Post("/v2/jobs", bytes.NewBuffer(request))
defer cleanup()
AssertServerResponse(t, resp, http.StatusOK)
Expand All @@ -803,7 +822,7 @@ func CreateJobViaWeb(t testing.TB, app *TestApplication, request []byte) job.Job
func CreateJobViaWeb2(t testing.TB, app *TestApplication, spec string) webpresenters.JobResource {
t.Helper()

client := app.NewHTTPClient(APIEmailAdmin)
client := app.NewHTTPClient(&User{})
resp, cleanup := client.Post("/v2/jobs", bytes.NewBufferString(spec))
defer cleanup()
AssertServerResponse(t, resp, http.StatusOK)
Expand All @@ -817,7 +836,7 @@ func CreateJobViaWeb2(t testing.TB, app *TestApplication, spec string) webpresen
func DeleteJobViaWeb(t testing.TB, app *TestApplication, jobID int32) {
t.Helper()

client := app.NewHTTPClient(APIEmailAdmin)
client := app.NewHTTPClient(&User{})
resp, cleanup := client.Delete(fmt.Sprintf("/v2/jobs/%v", jobID))
defer cleanup()
AssertServerResponse(t, resp, http.StatusNoContent)
Expand Down Expand Up @@ -866,7 +885,7 @@ func CreateJobRunViaUser(
t.Helper()

bodyBuf := bytes.NewBufferString(body)
client := app.NewHTTPClient(APIEmailAdmin)
client := app.NewHTTPClient(&User{})
resp, cleanup := client.Post("/v2/jobs/"+jobID.String()+"/runs", bodyBuf)
defer cleanup()
AssertServerResponse(t, resp, 200)
Expand All @@ -885,7 +904,7 @@ func CreateExternalInitiatorViaWeb(
) *webpresenters.ExternalInitiatorAuthentication {
t.Helper()

client := app.NewHTTPClient(APIEmailAdmin)
client := app.NewHTTPClient(&User{})
resp, cleanup := client.Post(
"/v2/external_initiators",
bytes.NewBufferString(payload),
Expand Down
1 change: 1 addition & 0 deletions core/internal/testutils/configtest/v2/general_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ func overrides(c *chainlink.Config, s *chainlink.Secrets) {
c.Database.MaxIdleConns = ptr[int64](20)
c.Database.MaxOpenConns = ptr[int64](20)
c.Database.MigrateOnStartup = ptr(false)
c.Database.DefaultLockTimeout = models.MustNewDuration(1 * time.Minute)

c.JobPipeline.ReaperInterval = models.MustNewDuration(0)

Expand Down
4 changes: 2 additions & 2 deletions core/services/job/runner_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -911,7 +911,7 @@ func TestRunner_Success_Callback_AsyncJob(t *testing.T) {
{
url, err := url.Parse(responseURL)
require.NoError(t, err)
client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})
body := strings.NewReader(`{"value": {"data":{"result":"123.45"}}}`)
response, cleanup := client.Patch(url.Path, body)
defer cleanup()
Expand Down Expand Up @@ -1092,7 +1092,7 @@ func TestRunner_Error_Callback_AsyncJob(t *testing.T) {
{
url, err := url.Parse(responseURL)
require.NoError(t, err)
client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})
body := strings.NewReader(`{"error": "something exploded in EA"}`)
response, cleanup := client.Patch(url.Path, body)
defer cleanup()
Expand Down
17 changes: 7 additions & 10 deletions core/web/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ func TestRBAC_Routemap_Admin(t *testing.T) {

// Assert all admin routes
// no endpoint should return StatusUnauthorized
client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})
for _, route := range routesRolesMap {
func() {
var resp *http.Response
Expand Down Expand Up @@ -344,9 +344,8 @@ func TestRBAC_Routemap_Edit(t *testing.T) {
defer ts.Close()

// Create a test edit user to work with
testUser := cltest.CreateUserWithRole(t, sessions.UserRoleEdit)
require.NoError(t, app.SessionORM().CreateUser(&testUser))
client := app.NewHTTPClient(testUser.Email)
u := &cltest.User{Role: sessions.UserRoleEdit}
client := app.NewHTTPClient(u)

// Assert all edit routes
for _, route := range routesRolesMap {
Expand Down Expand Up @@ -392,9 +391,8 @@ func TestRBAC_Routemap_Run(t *testing.T) {
defer ts.Close()

// Create a test run user to work with
testUser := cltest.CreateUserWithRole(t, sessions.UserRoleRun)
require.NoError(t, app.SessionORM().CreateUser(&testUser))
client := app.NewHTTPClient(testUser.Email)
u := &cltest.User{Role: sessions.UserRoleRun}
client := app.NewHTTPClient(u)

// Assert all run routes
for _, route := range routesRolesMap {
Expand Down Expand Up @@ -440,9 +438,8 @@ func TestRBAC_Routemap_ViewOnly(t *testing.T) {
defer ts.Close()

// Create a test run user to work with
testUser := cltest.CreateUserWithRole(t, sessions.UserRoleView)
require.NoError(t, app.SessionORM().CreateUser(&testUser))
client := app.NewHTTPClient(testUser.Email)
u := &cltest.User{Role: sessions.UserRoleView}
client := app.NewHTTPClient(u)

// Assert all view only routes
for i, route := range routesRolesMap {
Expand Down
16 changes: 8 additions & 8 deletions core/web/bridge_types_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func TestValidateBridgeNotExist(t *testing.T) {

func BenchmarkBridgeTypesController_Index(b *testing.B) {
app := cltest.NewApplication(b)
client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

b.ResetTimer()
for n := 0; n < b.N; n++ {
Expand All @@ -149,7 +149,7 @@ func TestBridgeTypesController_Index(t *testing.T) {

app := cltest.NewApplication(t)
require.NoError(t, app.Start(testutils.Context(t)))
client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

bt, err := setupBridgeControllerIndex(t, app.BridgeORM())
assert.NoError(t, err)
Expand Down Expand Up @@ -217,7 +217,7 @@ func TestBridgeTypesController_Create_Success(t *testing.T) {

app := cltest.NewApplication(t)
require.NoError(t, app.Start(testutils.Context(t)))
client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

resp, cleanup := client.Post(
"/v2/bridge_types",
Expand Down Expand Up @@ -245,7 +245,7 @@ func TestBridgeTypesController_Update_Success(t *testing.T) {

app := cltest.NewApplication(t)
require.NoError(t, app.Start(testutils.Context(t)))
client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

bridgeName := testutils.RandomizeName("BRidgea")
bt := &bridges.BridgeType{
Expand All @@ -271,7 +271,7 @@ func TestBridgeController_Show(t *testing.T) {
app := cltest.NewApplication(t)
require.NoError(t, app.Start(testutils.Context(t)))

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

bt := &bridges.BridgeType{
Name: bridges.MustParseBridgeName(testutils.RandomizeName("showbridge")),
Expand Down Expand Up @@ -301,7 +301,7 @@ func TestBridgeTypesController_Create_AdapterExistsError(t *testing.T) {
app := cltest.NewApplication(t)
require.NoError(t, app.Start(testutils.Context(t)))

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

resp, cleanup := client.Post(
"/v2/bridge_types",
Expand All @@ -317,7 +317,7 @@ func TestBridgeTypesController_Create_BindJSONError(t *testing.T) {
app := cltest.NewApplication(t)
require.NoError(t, app.Start(testutils.Context(t)))

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

resp, cleanup := client.Post(
"/v2/bridge_types",
Expand All @@ -333,7 +333,7 @@ func TestBridgeTypesController_Create_DatabaseError(t *testing.T) {
app := cltest.NewApplication(t)
require.NoError(t, app.Start(testutils.Context(t)))

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

resp, cleanup := client.Post(
"/v2/bridge_types",
Expand Down
2 changes: 1 addition & 1 deletion core/web/build_info_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func TestBuildInfoController_Show_APICredentials(t *testing.T) {
app := cltest.NewApplicationEVMDisabled(t)
require.NoError(t, app.Start(testutils.Context(t)))

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

resp, cleanup := client.Get("/v2/build_info")
defer cleanup()
Expand Down
4 changes: 2 additions & 2 deletions core/web/cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestCors_DefaultOrigins(t *testing.T) {
t.Run(test.origin, func(t *testing.T) {
app := cltest.NewApplicationWithConfig(t, config)

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

headers := map[string]string{"Origin": test.origin}
resp, cleanup := client.Get("/v2/chains/evm", headers)
Expand Down Expand Up @@ -61,7 +61,7 @@ func TestCors_OverrideOrigins(t *testing.T) {
})
app := cltest.NewApplicationWithConfig(t, config)

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

headers := map[string]string{"Origin": test.origin}
resp, cleanup := client.Get("/v2/chains/evm", headers)
Expand Down
2 changes: 1 addition & 1 deletion core/web/cosmos_chains_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ func setupCosmosChainsControllerTestV2(t *testing.T, cfgs ...*cosmos.CosmosConfi
app := cltest.NewApplicationWithConfig(t, cfg)
require.NoError(t, app.Start(testutils.Context(t)))

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

return &TestCosmosChainsController{
app: app,
Expand Down
4 changes: 2 additions & 2 deletions core/web/cosmos_keys_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func TestCosmosKeysController_Create_HappyPath(t *testing.T) {

app := cltest.NewApplicationEVMDisabled(t)
require.NoError(t, app.Start(testutils.Context(t)))
client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})
keyStore := app.GetKeyStore()

response, cleanup := client.Post("/v2/keys/cosmos", nil)
Expand Down Expand Up @@ -98,7 +98,7 @@ func setupCosmosKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, key
require.NoError(t, app.Start(testutils.Context(t)))
require.NoError(t, app.KeyStore.Cosmos().Add(cltest.DefaultCosmosKey))

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

return client, app.GetKeyStore()
}
2 changes: 1 addition & 1 deletion core/web/dkgencrypt_keys_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func setupDKGEncryptKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner,
require.NoError(t, app.Start(testutils.Context(t)))
require.NoError(t, app.KeyStore.DKGEncrypt().Add(cltest.DefaultDKGEncryptKey))

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

return client, app.GetKeyStore()
}
2 changes: 1 addition & 1 deletion core/web/dkgsign_keys_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func setupDKGSignKeysControllerTests(t *testing.T) (cltest.HTTPClientCleaner, ke
require.NoError(t, app.Start(testutils.Context(t)))
require.NoError(t, app.KeyStore.DKGSign().Add(cltest.DefaultDKGSignKey))

client := app.NewHTTPClient(cltest.APIEmailAdmin)
client := app.NewHTTPClient(&cltest.User{})

return client, app.GetKeyStore()
}
Loading

0 comments on commit 7db18d9

Please sign in to comment.