Files
team/server/channels/jobs/helper_test.go
9ed85b6850 Cherry-pick Go 1.25.8 upgrade and FIPS password fixes to release-11.4 (#36123)
* ci: shard server Postgres tests into 4 parallel runners (#35739)

Cherry-pick of 00296f9b49 from master.

* updated go to version 1.25.8 (#35817)

Cherry-pick of 32a10bac62 from master.

* Move password hashers from server/v8 to server/public (#35805)

Cherry-pick of cca3f08574 from master.

* Generate instead of hard-coding test passwords, enforce new minimum for FIPS, shard CI, fix FIPS builds (#35905)

Cherry-pick of 1bdd985b41 from master.

* upgrade golangci-lint (#35845)

Cherry-pick of 157e0400b2 from master.

On release-11.4 (unlike 11.5), UpdatePostsChannelTypeByChannelId and
BackfillPostsChannelType exist in the elasticsearch/opensearch files,
so the imports they require (fmt, updatebyquery, scriptlanguage) must
be added — they were not in the cherry-pick diff since they already
existed on master.

Also updates html2text/tablewriter/olekukonko deps to fix a workspace
conflict where enterprise's Go 1.25.8 bump pulled in a newer html2text
that requires tablewriter ≥ 1.1 (was pinned to 0.0.5 via a replace
directive). Matches the subset of 866f759e4b (Mm 66662 bump deps)
relevant to this incompatibility.

* Fix FIPS-incompatible passwords and config in e2e test suites (#36001)

Cherry-pick of b51b4a8937 from master.

release-11.4 differences vs release-11.5:
- demo_plugin_installation.spec.ts also deleted (modify/delete conflict, git rm)
- authentication_2_spec.ts conflict: HEAD missing check() call; took
  incoming (check + FIPS-length passwords)
- member_invitation_ui_spec.ts: HEAD has 'Create Account' (capital A)
  matching release-11.4 button text; kept HEAD's button text with
  incoming's newTestPassword()

* fix(cypress): demo plugin (#36056)

Cherry-pick of 39f1979aa5 from master.

demo_plugin_installation.spec.ts was deleted in step 10 (modify/delete);
re-created here with both the FIPS-password change and the URL fix.

* test: clean up channel store data after TestChannelStore (#36066)

TestChannelStore sub-tests create channels, members, and team members
using fake TeamIds and UserIds (model.NewId() for non-existent rows).
These records are left in the database and cause integrity tests
(TestCheck*) running in the same binary to fail their full-table scans.

Register a t.Cleanup on TestChannelStore that purges the affected
tables entirely. A blanket purge is safe: the schema enforces no FK
constraints, and every test suite creates its own data independently.

* Fix command injection in server-test-template workflow (#36080)

Cherry-pick of 9223935f16 from master.

* fix(ci): restore testname format in sharded gotestsum runs (#36078)

run-shard-tests.sh called gotestsum directly without --format, so it
fell back to gotestsum's default (pkgname) instead of the testname
format set by the Makefile. Pass --format "${GOTESTSUM_FORMAT:-testname}"
to match the Makefile default.

Co-authored-by: Mattermost Build <[email protected]>

* fixup: drop demo_plugin playwright specs — master-only APIs

demo_plugin/helpers.ts and demo_plugin_installation.spec.ts use
installAndEnablePlugin and isPluginActive which don't exist on
release-11.4's PlaywrightExtended type. These files were re-created
by the step-11 cherry-pick of 39f1979aa5, but they don't compile on
this branch (same class of problem as actions.spec.ts in step 10).

* fixup: add missing await in PluginLinkTooltip test

The test added in 39f1979aa5 is missing an await on renderWithContext,
causing the pointer-events assertion to race. Fix from 0c7d3f27c6
(on a feature branch, not yet on master).

* fixup: drop pointer-events test incompatible with jsdom@20

The 'should not block interaction with elements outside the tooltip' test
checks getComputedStyle for pointer-events: none, which is set only in SCSS.
release-11.4 uses jest-environment-jsdom@29 (jsdom@20), which does not apply
stylesheets, so getComputedStyle always returns "". The test passes on
release-11.5+ only because they use jest-environment-jsdom@30 (jsdom@25+).

Drop the test rather than backport the jsdom upgrade.

* fixup: add missing i18n keys for elasticsearch/opensearch functions

BackfillPostsChannelType and UpdatePostsChannelTypeByChannelId exist on
release-11.4 (unlike release-11.5+). The golangci-lint cherry-pick added
new error strings to those functions referencing i18n keys that weren't
in en.json.

* fixup: run make i18n-extract to reorder keys correctly

* fixup: drop terms-and-privacy checkbox from MM-T1774 on release-11.4

The #signup-body-card-form-check-terms-and-privacy element did not exist
on release-11.4's signup page. It was added to master after this branch
was cut, so the check() call from the incoming cherry-pick causes the test
to fail with "element never found".

* fixup: remove UpdatePostsChannelTypeByChannelId/BackfillPostsChannelType

These functions were introduced by MM-67540 (allow searching public channel
messages without channel membership), which never landed on release-11.4.
The golangci-lint cherry-pick only modernizes existing code; the rerere
resolution incorrectly added the full function bodies from master.

Remove both functions and their now-unused imports (fmt, updatebyquery,
scriptlanguage) from elasticsearch.go and opensearch.go. Also remove the
two i18n keys added to support them.

Same treatment as release-11.5, where these functions were also absent.

---------

Co-authored-by: Mattermost Build <[email protected]>
2026-04-16 12:10:03 -03:00

359 lines
9.9 KiB
Go

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package jobs_test
import (
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost/server/public/model"
"github.com/mattermost/mattermost/server/public/shared/mlog"
"github.com/mattermost/mattermost/server/public/shared/request"
"github.com/mattermost/mattermost/server/v8/channels/app"
"github.com/mattermost/mattermost/server/v8/channels/jobs"
"github.com/mattermost/mattermost/server/v8/channels/store"
"github.com/mattermost/mattermost/server/v8/config"
)
type TestHelper struct {
App *app.App
Context *request.Context
Server *app.Server
BasicTeam *model.Team
BasicUser *model.User
BasicUser2 *model.User
Store store.Store
SystemAdminUser *model.User
LogBuffer *mlog.Buffer
TestLogger *mlog.Logger
IncludeCacheLayer bool
ConfigStore *config.Store
tempWorkspace string
}
func setupTestHelper(tb testing.TB, dbStore store.Store, sqlSettings *model.SqlSettings, enterprise bool, includeCacheLayer bool,
updateCfg func(cfg *model.Config), options []app.Option,
) *TestHelper {
tempWorkspace, err := os.MkdirTemp("", "jobstest")
require.NoError(tb, err)
configStore := config.NewTestMemoryStore()
memoryConfig := configStore.Get()
memoryConfig.SqlSettings = *sqlSettings
*memoryConfig.PluginSettings.Directory = filepath.Join(tempWorkspace, "plugins")
*memoryConfig.PluginSettings.ClientDirectory = filepath.Join(tempWorkspace, "webapp")
*memoryConfig.PluginSettings.AutomaticPrepackagedPlugins = false
*memoryConfig.LogSettings.EnableSentry = false // disable error reporting during tests
// Check for environment variable override for console log level (useful for debugging tests)
consoleLevel := os.Getenv("MM_LOGSETTINGS_CONSOLELEVEL")
if consoleLevel == "" {
consoleLevel = mlog.LvlStdLog.Name
}
*memoryConfig.LogSettings.ConsoleLevel = consoleLevel
*memoryConfig.AnnouncementSettings.AdminNoticesEnabled = false
*memoryConfig.AnnouncementSettings.UserNoticesEnabled = false
if updateCfg != nil {
updateCfg(memoryConfig)
}
_, _, err = configStore.Set(memoryConfig)
require.NoError(tb, err)
buffer := &mlog.Buffer{}
options = append(options, app.ConfigStore(configStore))
if includeCacheLayer {
// Adds the cache layer to the test store
options = append(options, app.StoreOverrideWithCache(dbStore))
} else {
options = append(options, app.StoreOverride(dbStore))
}
testLogger, err := mlog.NewLogger()
require.NoError(tb, err)
logCfg, err := config.MloggerConfigFromLoggerConfig(&memoryConfig.LogSettings, nil, config.GetLogFileLocation)
require.NoError(tb, err)
err = testLogger.ConfigureTargets(logCfg, nil)
require.NoError(tb, err, "failed to configure test logger")
err = mlog.AddWriterTarget(testLogger, buffer, true, mlog.StdAll...)
require.NoError(tb, err, "failed to add writer target to test logger")
// lock logger config so server init cannot override it during testing.
testLogger.LockConfiguration()
options = append(options, app.SetLogger(testLogger))
s, err := app.NewServer(options...)
require.NoError(tb, err)
th := &TestHelper{
App: app.New(app.ServerConnector(s.Channels())),
Context: request.EmptyContext(testLogger),
Server: s,
LogBuffer: buffer,
TestLogger: testLogger,
IncludeCacheLayer: includeCacheLayer,
ConfigStore: configStore,
Store: dbStore,
tempWorkspace: tempWorkspace,
}
prevListenAddress := *th.App.Config().ServiceSettings.ListenAddress
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = "localhost:0" })
err = th.Server.Start()
require.NoError(tb, err)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress })
th.App.Srv().Store().MarkSystemRanUnitTests()
tb.Cleanup(func() {
if th.IncludeCacheLayer {
// Clean all the caches
appErr := th.App.Srv().InvalidateAllCaches()
require.Nil(tb, appErr)
}
done := make(chan bool)
go func() {
th.Server.Shutdown()
close(done)
}()
select {
case <-done:
case <-time.After(30 * time.Second):
// panic instead of fatal to terminate all tests in this package, otherwise the
// still running App could spuriously fail subsequent tests.
panic("failed to shutdown App within 30 seconds")
}
if th.tempWorkspace != "" {
os.RemoveAll(th.tempWorkspace)
}
})
return th
}
func Setup(tb testing.TB, options ...app.Option) *TestHelper {
return SetupWithUpdateCfg(tb, nil, options...)
}
func SetupWithUpdateCfg(tb testing.TB, updateCfg func(cfg *model.Config), options ...app.Option) *TestHelper {
tb.Helper()
if testing.Short() {
tb.SkipNow()
}
var dbStore store.Store
var dbSettings *model.SqlSettings
if mainHelper.Options.RunParallel {
dbStore, _, dbSettings, _ = mainHelper.GetNewStores(tb)
tb.Cleanup(func() {
dbStore.Close()
})
} else {
dbStore = mainHelper.GetStore()
dbSettings = mainHelper.GetSQLSettings()
dbStore.DropAllTables()
dbStore.MarkSystemRanUnitTests()
mainHelper.PreloadMigrations()
}
th := setupTestHelper(tb, dbStore, dbSettings, false, true, updateCfg, options)
return th
}
func (th *TestHelper) InitBasic(tb testing.TB) *TestHelper {
tb.Helper()
th.SystemAdminUser = th.CreateUser(tb)
_, appErr := th.App.UpdateUserRoles(th.Context, th.SystemAdminUser.Id, model.SystemUserRoleId+" "+model.SystemAdminRoleId, false)
require.Nil(tb, appErr)
th.SystemAdminUser, appErr = th.App.GetUser(th.SystemAdminUser.Id)
require.Nil(tb, appErr)
th.BasicUser = th.CreateUser(tb)
th.BasicUser, appErr = th.App.GetUser(th.BasicUser.Id)
require.Nil(tb, appErr)
th.BasicUser2 = th.CreateUser(tb)
th.BasicUser2, appErr = th.App.GetUser(th.BasicUser2.Id)
require.Nil(tb, appErr)
th.BasicTeam = th.CreateTeam(tb)
return th
}
func (th *TestHelper) CreateTeam(tb testing.TB) *model.Team {
tb.Helper()
id := model.NewId()
team := &model.Team{
DisplayName: "dn_" + id,
Name: "name" + id,
Email: "success+" + id + "@simulator.amazonses.com",
Type: model.TeamOpen,
}
team, err := th.App.CreateTeam(th.Context, team)
require.Nil(tb, err)
return team
}
func (th *TestHelper) CreateUser(tb testing.TB) *model.User {
tb.Helper()
return th.CreateUserOrGuest(tb, false)
}
func (th *TestHelper) CreateUserOrGuest(tb testing.TB, guest bool) *model.User {
tb.Helper()
id := model.NewId()
user := &model.User{
Email: "success+" + id + "@simulator.amazonses.com",
Username: "un_" + id,
Nickname: "nn_" + id,
Password: model.NewTestPassword(),
EmailVerified: true,
}
var err *model.AppError
if guest {
user, err = th.App.CreateGuest(th.Context, user)
} else {
user, err = th.App.CreateUser(th.Context, user)
}
require.Nil(tb, err)
return user
}
func (th *TestHelper) ShutdownApp() {
done := make(chan bool)
go func() {
th.Server.Shutdown()
close(done)
}()
select {
case <-done:
case <-time.After(30 * time.Second):
// panic instead of fatal to terminate all tests in this package, otherwise the
// still running App could spuriously fail subsequent tests.
panic("failed to shutdown App within 30 seconds")
}
}
func (th *TestHelper) SetupBatchWorker(tb testing.TB, worker *jobs.BatchWorker) *model.Job {
tb.Helper()
jobId := model.NewId()
th.Server.Jobs.RegisterJobType(jobId, worker, nil)
jobData := make(model.StringMap)
jobData["batch_number"] = "1"
job, appErr := th.Server.Jobs.CreateJob(th.Context, jobId, jobData)
require.Nil(tb, appErr)
done := make(chan bool)
go func() {
defer close(done)
worker.Run()
}()
// When ending the test, ensure we wait for the worker to finish.
tb.Cleanup(func() {
waitDone(tb, done, "worker did not stop running")
})
// Give the worker time to start running
time.Sleep(500 * time.Millisecond)
return job
}
func (th *TestHelper) WaitForJobStatus(tb testing.TB, job *model.Job, status string) {
tb.Helper()
require.Eventuallyf(tb, func() bool {
actualJob, appErr := th.Server.Jobs.GetJob(th.Context, job.Id)
require.Nil(tb, appErr)
require.Equal(tb, job.Id, actualJob.Id)
return actualJob.Status == status
}, 5*time.Second, 250*time.Millisecond, "job never transitioned to %s", status)
}
func (th *TestHelper) WaitForBatchNumber(tb testing.TB, job *model.Job, batchNumber int) {
tb.Helper()
require.Eventuallyf(tb, func() bool {
actualJob, appErr := th.Server.Jobs.GetJob(th.Context, job.Id)
require.Nil(tb, appErr)
require.Equal(tb, job.Id, actualJob.Id)
finalBatchNumber, err := strconv.Atoi(actualJob.Data["batch_number"])
require.NoError(tb, err)
return finalBatchNumber == batchNumber
}, 5*time.Second, 250*time.Millisecond, "job did not stop at batch %d", batchNumber)
}
func waitDone(tb testing.TB, done chan bool, msg string) {
tb.Helper()
require.Eventually(tb, func() bool {
select {
case <-done:
return true
default:
return false
}
}, 5*time.Second, 100*time.Millisecond, msg)
}
func (th *TestHelper) SetupWorkers(tb testing.TB) {
tb.Helper()
err := th.App.Srv().Jobs.StartWorkers()
require.NoError(tb, err)
}
func (th *TestHelper) RunJob(tb testing.TB, jobType string, jobData map[string]string) *model.Job {
tb.Helper()
job, appErr := th.Server.Jobs.CreateJob(th.Context, jobType, jobData)
require.Nil(tb, appErr)
// poll until completion
th.checkJobStatus(tb, job.Id, model.JobStatusSuccess)
job, appErr = th.Server.Jobs.GetJob(th.Context, job.Id)
require.Nil(tb, appErr)
return job
}
func (th *TestHelper) checkJobStatus(tb testing.TB, jobId string, status string) {
tb.Helper()
require.Eventuallyf(tb, func() bool {
// it's ok if there's an error, it might take awhile for the job to finish.
job, appErr := th.Server.Jobs.GetJob(th.Context, jobId)
assert.Nil(tb, appErr)
if jobId == job.Id {
return job.Status == status
}
return false
}, 15*time.Second, 100*time.Millisecond, "expected job's status to be %s", status)
}