navidrome/tests/test_helpers.go
Deluan Quintão 2e7e24a023
chore(lint): ban panic (#6478)
* chore(lint): ban panic in production code

Add a forbidigo rule that rejects panic outside tests and test helpers
(_test.go, tests/ and storagetest/). Its message says to return an error,
and to use log.Fatal only for startup failures.

The existing production panics are gone:
- model.MustParseArtworkID was only used by core/artwork tests. It is now a
  Gomega helper in those test suites, and it also panicked with the parsed
  ID instead of the error.
- isDBInitialized in db/migrations panicked on a query error and never
  closed its rows. It now uses QueryRowContext and logs the error.

The two http.ErrAbortHandler panics in the stream and API v1 handlers stay,
because net/http requires them to abort a response. They are marked with
//nolint:forbidigo. cmd/wire_injectors.go is not linted, because of its
wireinject build tag.

* chore(lint): ban panic in tests too

The panic ban excluded test files and test helpers, so agents could read it as permission to panic in tests. The rule now applies everywhere, and its message says what to use instead: return an error, or Expect(...)/Fail(...) in tests.

Test panics are replaced with Gomega assertions, and the helpers that assert call GinkgoHelper() so failures point at the calling spec. The fake HTTP clients in the deezer tests and getDirEntry use Fail(...). storagetest.FakeFS.UpdateTags now asserts with Gomega instead of panicking.

Seven test panics stay, marked //nolint:forbidigo: they exercise panic recovery or stand in for log.Fatal.

* refactor(tests): share panicking test helpers

Move mustParseArtworkID out of the two core/artwork suites into tests.MustParseArtworkID, and add conf.PanicOnLogFatal so the conf specs share one panicking logFatal stub and one //nolint. The MustPath spec now asserts the fatal message instead of capturing it. Also merge the back-to-back user and artist loops in the persistence suite setup.
2026-11-15 19:07:43 -05:00

90 lines
2.6 KiB
Go

package tests
import (
"context"
"os"
"path/filepath"
"runtime"
"github.com/navidrome/navidrome/db"
"github.com/navidrome/navidrome/log"
"github.com/navidrome/navidrome/model"
"github.com/navidrome/navidrome/model/id"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
"github.com/sirupsen/logrus"
"github.com/sirupsen/logrus/hooks/test"
)
// SkipOnWindows marks the current spec (or surrounding BeforeEach) as skipped
// when running on Windows. The reason is included in the Ginkgo output so the
// backlog of Windows-skipped tests stays auditable.
func SkipOnWindows(reason string) {
if runtime.GOOS == "windows" {
ginkgo.Skip("not supported on Windows: " + reason)
}
}
type testingT interface {
TempDir() string
}
func TempFileName(t testingT, prefix, suffix string) string {
return filepath.Join(t.TempDir(), prefix+id.NewRandom()+suffix)
}
// TempFile creates an empty file in t.TempDir() and returns the closed handle.
// The handle is returned for backward compatibility, but is already closed so
// callers don't need to. On Windows, leaving the handle open would hold a file
// lock and block Ginkgo's TempDir cleanup.
func TempFile(t testingT, prefix, suffix string) (*os.File, string, error) {
name := TempFileName(t, prefix, suffix)
f, err := os.Create(name)
if err != nil {
return nil, name, err
}
if cerr := f.Close(); cerr != nil {
return f, name, cerr
}
return f, name, nil
}
// ClearDB deletes all tables and data from the database
// https://stackoverflow.com/questions/525512/drop-all-tables-command
func ClearDB(ctx context.Context) error {
_, err := db.Db().ExecContext(ctx, `
PRAGMA writable_schema = 1;
DELETE FROM sqlite_master;
PRAGMA writable_schema = 0;
VACUUM;
PRAGMA integrity_check;
`)
return err
}
// LogHook sets up a logrus test hook and configures the default logger to use it.
// It returns the hook and a cleanup function to restore the default logger.
// Example usage:
//
// hook, cleanup := LogHook()
// defer cleanup()
// // ... perform logging operations ...
// Expect(hook.LastEntry()).ToNot(BeNil())
// Expect(hook.LastEntry().Level).To(Equal(logrus.WarnLevel))
// Expect(hook.LastEntry().Message).To(Equal("log message"))
func LogHook() (*test.Hook, func()) {
l, hook := test.NewNullLogger()
log.SetLevel(log.LevelWarn)
log.SetDefaultLogger(l)
return hook, func() {
// Restore default logger after test
log.SetDefaultLogger(logrus.New())
}
}
func MustParseArtworkID(id string) model.ArtworkID {
ginkgo.GinkgoHelper()
artID, err := model.ParseArtworkID(id)
gomega.Expect(err).ToNot(gomega.HaveOccurred())
return artID
}