testutil

package
v0.0.0-...-bfb10b8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: AGPL-3.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = gorm.ErrRecordNotFound

ErrNotFound is returned by mock repositories when an entity is not found.

production の GORM repositories は record-not-found 時に gorm.ErrRecordNotFound を返すので、mock 側もこれと同一 sentinel に 揃える。これにより上位 layer で `errors.Is(err, gorm.ErrRecordNotFound)` で分岐するコード (例: activitypub.UserMentionResolver) が mock テスト 経路でも production と同じ挙動になる (#572 item 2)。

Functions

func ApplyMigrations

func ApplyMigrations(db *gorm.DB)

ApplyMigrations applies the up migration SQL files that this schema has not seen yet.

台帳は **ファイル名 + 内容のハッシュ**で持つ。名前だけだと、migration を書き 換えながら開発しているときに反映されなくなる。

**記録するのは成功したときだけ。** 失敗したものを「適用済み」にすると、 一過性の失敗 (並行 DDL / lock timeout / 新しい migration の実バグ) が恒久的に 隠れる。

既存 schema への再適用でエラーになるのは実測で **147 本中 2 本だけ** (`000001_initial` の制約重複と `000075_signup_application`)。どちらも 1 ファイル = 1 つの暗黙トランザクションなので丸ごとロールバックし、列枠を 食わない。**列枠を食う `000033` (ADD) / `000036` (DROP) は成功する側**なので、 成功時のみの記録でも #2756 は解消する。

func AssertFastifyError

func AssertFastifyError(t *testing.T, rec *httptest.ResponseRecorder, status int, code string)

AssertFastifyError verifies that the recorder body is the upstream Misskey TS Fastify-style reply error shape:

{"statusCode": <status>, "error": <http.StatusText(status)>, "message": "Error: <code>"}

対応する production helper は internal/api/apierr.FastifyReply。drop-in 互換 fix (#802 / #809 / #810) の handler_test 群が共有する assertion で、 signup / signin endpoint をまたいで重複定義していた assertion を集約する。

失敗時は require 経由で fail-fast (= subtest 単位で打ち切り)。

func AssertInvalidParam

func AssertInvalidParam(t *testing.T, rec *httptest.ResponseRecorder)

AssertInvalidParam verifies that the recorder holds a 400 INVALID_PARAM Misskey API error with upstream's id.

func AssertUpstreamDates

func AssertUpstreamDates(t DateChecker, body []byte, keys ...string)

AssertUpstreamDates checks that every value of the named keys, at any depth of the JSON body, is null or a time in upstream's format (#4091). Each key must appear at least once with a string value, so that a key that is renamed or no longer set fails instead of passing with nothing to check.

Go の encoding/json は time.Time を RFC3339Nano で書く (末尾の 0 が落ち、 オフセットは値のロケーションに従う)。名前で見るのは、応答の文字列のうち どれが日時かを本文だけからは決められないため。

func DeadAddr

func DeadAddr(t testing.TB) string

DeadAddr returns "127.0.0.1:<port>" for a port from DeadPort.

func DeadPort

func DeadPort(t testing.TB) int

DeadPort returns a TCP port on 127.0.0.1 that refuses connections until the test ends, even while other tests or processes are binding ports.

Use it wherever a test needs a destination nothing answers on. A port that was listened on and then closed is not enough: another process can take it before the test dials it.

listenして閉じたポートは、閉じた直後に並行して動く別のテスト(testcontainersの Redisなど)が取ることがあり、「繋がらない先」のつもりが繋がってしまう(#3369)。 listenせずにbindだけしたソケットをテストの終わりまで持てば、接続はRSTで即座に 拒否され、そのポートは他のプロセスにbindされず、カーネルもephemeral portとして 配らない。SO_REUSEADDRは付けない。Linuxでは、listenしていないソケットに両方が SO_REUSEADDRを付けていると、後から来た側もbindできてしまうため。

func EnvOrDefault

func EnvOrDefault(key, fallback string) string

EnvOrDefault returns the environment variable value or the fallback.

func MiniredisDown

func MiniredisDown(mr *miniredis.Miniredis)

MiniredisDown makes mr behave like a Redis server that went away, while mr keeps listening on its port until the test closes it.

From then on, every command on an existing or a new connection is answered by closing that connection, so clients see an I/O error. Use it instead of mr.Close() when the test goes on to expect the clients to fail.

A connection is cut only when it sends a command. A connection already waiting in a blocking command (BLPOP and the like), or a subscription that only waits in ReceiveMessage, stays open until it sends its next command (go-redis PubSub.Channel pings every few seconds, so that connection is cut then and keeps reconnecting). So this does not fit a test that expects such a connection to be dropped at once. MiniredisDown takes the same pre-hook slot as mr.SetError, so a later mr.SetError call silently replaces it: mr.SetError("") brings the server back, and mr.SetError("msg") turns it into error replies.

mr.Close()でポートを手放すと、閉じた直後に並行して動く別のテスト(testcontainers のRedisなど)が同じポートを取ることがあり、残ったclientが再接続でそちらへ 繋がってしまう(#3369)。miniredisにlistenを続けさせたまま、全てのコマンドで 接続を切らせれば、ポートは他に渡らず、clientからは落ちたサーバーに見える。

func MockPollVoted

func MockPollVoted(userID, noteID string)

MockPollVoted records a vote so MockPollRepository.ListRecommendation excludes the note for that viewer. Test helper.

func MustOpenTestDB

func MustOpenTestDB() *gorm.DB

MustOpenTestDB は OpenTestDB のパニック版。init() で使う。

func OpenSharedTestDB

func OpenSharedTestDB() (*gorm.DB, error)

OpenSharedTestDB connects to the shared `public` schema without creating a per-package one.

`internal/db` のように **接続処理そのもの**を試すテスト専用。データを読み書き するテストからは使わないこと (#2450 の干渉が戻る)。

func OpenTestDB

func OpenTestDB() (*gorm.DB, error)

OpenTestDB connects to the test database with search_path pinned to a schema dedicated to the calling package, creating that schema on first use.

接続情報は環境変数 TEST_DB_HOST, TEST_DB_PORT, TEST_DB_NAME, TEST_DB_USER, TEST_DB_PASS, TEST_DB_SSLMODE、無ければ .env.test から読み取る。

なぜパッケージごとに schema を分けるか (#2450)

CI は shard ごとに PostgreSQL を 1 つ立て、`go test <pkgs...>` が**パッケージの テストバイナリを並行実行**する。全パッケージが同じ DB を共有していると、 一方の後片付けが他方の前提を壊す。

実際に `internal/charttick` の `DELETE FROM "user"` が `internal/api/gallery` の 所有者 user を消し、無関係な PR で CI が落ちた。しかも charttick は **テーブル全体の絶対件数**をアサートするので、削除を絞ると今度は他パッケージの 行が混ざって charttick 自身が落ちる。**干渉は双方向で、削除範囲を絞るだけでは 解けない。**

shard の割り当ては `go list` の出力順に対する `NR % 4` なので、テストパッケージを 1 つ足すだけで同居の組み合わせが変わる。個別の衝突を潰す対処では再発するため、 **共有そのものをやめる**。

schema 名は呼び出し元のパッケージから機械的に決める。新しいパッケージが `MustOpenTestDB` を呼んでも自動で隔離されるので、この問題を再び持ち込めない。

func OpenTestDBSchema

func OpenTestDBSchema(suffix string) (*gorm.DB, error)

OpenTestDBSchema connects to a **sibling schema** of the calling package's one, named `<package>_<suffix>`, creating it on first use.

**shared な schema を実行中に作り変えるテスト向け** (#2756)。列を DROP して 戻すような操作は、PostgreSQL が DROP した列も 1600 の上限に数えるため実行の たびに枠を食う。専用 schema を一度だけその形に作って使い回せば、繰り返し 回しても増えない。同じパッケージの他のテストと状態を共有しない利点もある。

migration は呼び出し側が ApplyMigrations で流すこと (台帳があるので 2 回目 以降は skip される)。

func SkipIfNoDocker

func SkipIfNoDocker(t *testing.T)

SkipIfNoDocker skips the test if Docker is not available.

func SortMockPage

func SortMockPage[T any](rows []T, sinceID, untilID string, id func(T) string)

SortMockPage orders rows the same way the repository package's paginationOrder helper does: ascending when only sinceID is supplied, descending otherwise. Mocks that page by id cursor must call this before truncating to limit, because the direction decides which rows survive the cut, not just how they are arranged.

The id argument extracts the cursor column from a row.

func TestDSNForSchema

func TestDSNForSchema(schema string) string

TestDSNForSchema exposes the test DSN builder so tests that need to open a second connection (e.g. registering a replica for dbresolver) can reuse the same credentials. An empty schema leaves search_path at its default.

Types

type DateChecker

type DateChecker interface {
	Helper()
	Errorf(format string, args ...any)
}

DateChecker is the part of *testing.T that AssertUpstreamDates uses.

type MockAbuseReportNotificationRecipientRepository

type MockAbuseReportNotificationRecipientRepository struct {
	Recipients map[string]*model.AbuseReportNotificationRecipient
	CreateErr  error
	UpdateErr  error
}

MockAbuseReportNotificationRecipientRepository is a test double for repository.AbuseReportNotificationRecipientRepository.

func NewMockAbuseReportNotificationRecipientRepository

func NewMockAbuseReportNotificationRecipientRepository() *MockAbuseReportNotificationRecipientRepository

NewMockAbuseReportNotificationRecipientRepository creates an empty mock.

func (*MockAbuseReportNotificationRecipientRepository) Create

func (*MockAbuseReportNotificationRecipientRepository) Delete

func (*MockAbuseReportNotificationRecipientRepository) FindByID

func (*MockAbuseReportNotificationRecipientRepository) List

func (*MockAbuseReportNotificationRecipientRepository) Update

type MockAbuseReportRepository

type MockAbuseReportRepository struct {
	Reports map[string]*model.AbuseUserReport
}

func NewMockAbuseReportRepository

func NewMockAbuseReportRepository() *MockAbuseReportRepository

func (*MockAbuseReportRepository) CountUnresolved

func (m *MockAbuseReportRepository) CountUnresolved() (int64, error)

CountUnresolved counts the reports that are not resolved yet (#3200).

func (*MockAbuseReportRepository) Create

func (*MockAbuseReportRepository) FindByID

func (*MockAbuseReportRepository) FindStatesByIDs

func (m *MockAbuseReportRepository) FindStatesByIDs(ids []string) (map[string]model.AbuseReportState, error)

FindStatesByIDs returns the scalar resolution state of the given reports (#2868). 存在しない ID は map から単に落とす。

func (*MockAbuseReportRepository) HasOlderUnresolvedByPair

func (m *MockAbuseReportRepository) HasOlderUnresolvedByPair(reporterID, targetUserID, beforeID string) (bool, error)

HasOlderUnresolvedByPair mirrors the production query (#3200).

func (*MockAbuseReportRepository) HasOlderUnresolvedFromHost

func (m *MockAbuseReportRepository) HasOlderUnresolvedFromHost(host, beforeID string) (bool, error)

HasOlderUnresolvedFromHost mirrors the production query (#3200).

func (*MockAbuseReportRepository) List

func (m *MockAbuseReportRepository) List(resolved *bool, reporterOrigin, targetUserOrigin, sinceID, untilID string, limit int) ([]*model.AbuseUserReport, error)

func (*MockAbuseReportRepository) UpdateFields

func (m *MockAbuseReportRepository) UpdateFields(id string, fields map[string]any) error

type MockAccessTokenRepository

type MockAccessTokenRepository struct {
	Tokens map[string]*model.AccessToken // keyed by hash
	// Apps は ListByUserIDPreloadApp 用の App map。テスト側で SetApp 経由で
	// 埋めると、AppID 経由で Token に Preload された状態のコピーが返る。
	Apps map[string]*model.App
}

MockAccessTokenRepository is a test double for repository.AccessTokenRepository.

func NewMockAccessTokenRepository

func NewMockAccessTokenRepository() *MockAccessTokenRepository

func (*MockAccessTokenRepository) Create

Create inserts a token keyed by its hash (mirrors the real repo's INSERT).

func (*MockAccessTokenRepository) DeleteByID

func (m *MockAccessTokenRepository) DeleteByID(id string) error

func (*MockAccessTokenRepository) FindByHash

func (m *MockAccessTokenRepository) FindByHash(hash string) (*model.AccessToken, error)

func (*MockAccessTokenRepository) FindByHashOrToken

func (m *MockAccessTokenRepository) FindByHashOrToken(hash, rawToken string) (*model.AccessToken, error)

FindByHashOrToken は実 repo の WHERE hash = ? OR token = ? OR hash = lower(token) を再現する。 実 repo は hash 列と token 列の OR 検索を 1 query で行うため、mock も 両条件を順に評価する。Tokens map は hash key で持っているので、token 列 検索は線形探索になるが test scope では問題ない。

func (*MockAccessTokenRepository) FindByID

func (*MockAccessTokenRepository) ListAuthorizedApps

func (m *MockAccessTokenRepository) ListAuthorizedApps(userID string, limit, offset int, sortAsc bool) ([]*model.AccessToken, error)

ListAuthorizedApps は実 repo の appId IS NOT NULL filter + Preload("App") + id sort (asc/desc) + limit/offset を再現する。

func (*MockAccessTokenRepository) ListByUserID

func (m *MockAccessTokenRepository) ListByUserID(userID string) ([]*model.AccessToken, error)

func (*MockAccessTokenRepository) ListByUserIDPreloadApp

func (m *MockAccessTokenRepository) ListByUserIDPreloadApp(userID, sort string) ([]*model.AccessToken, error)

ListByUserIDPreloadApp は実 repo の Preload("App") + sort 順を再現する。 sort 値は Misskey TS 互換 (+/-createdAt, +/-lastUsedAt, default は id ASC)。

func (*MockAccessTokenRepository) SetApp

func (m *MockAccessTokenRepository) SetApp(app *model.App)

SetApp wires an App into the mock so ListByUserIDPreloadApp は AppID 経由 で Token に App を埋めて返す。

type MockAdRepository

type MockAdRepository struct {
	Ads       map[string]*model.Ad
	CreateErr error
	ListErr   error
}

MockAdRepository is a test double for repository.AdRepository.

func NewMockAdRepository

func NewMockAdRepository() *MockAdRepository

NewMockAdRepository creates an empty MockAdRepository.

func (*MockAdRepository) Create

func (m *MockAdRepository) Create(a *model.Ad) error

func (*MockAdRepository) Delete

func (m *MockAdRepository) Delete(id string) error

func (*MockAdRepository) FindByID

func (m *MockAdRepository) FindByID(id string) (*model.Ad, error)

func (*MockAdRepository) ListActive

func (m *MockAdRepository) ListActive(now time.Time) ([]*model.Ad, error)

func (*MockAdRepository) ListFiltered

func (m *MockAdRepository) ListFiltered(publishing *bool, sinceID, untilID string, limit int, now time.Time) ([]*model.Ad, error)

ListFiltered applies the publishing filter + cursor pagination (#1545).

func (*MockAdRepository) UpdateFields

func (m *MockAdRepository) UpdateFields(id string, fields map[string]any) error

type MockAllowlistChecker

type MockAllowlistChecker struct {
	AllowedURLs map[string]bool
}

MockAllowlistChecker is a test double for mediaproxy.AllowlistChecker.

func (*MockAllowlistChecker) IsAllowedURL

func (m *MockAllowlistChecker) IsAllowedURL(_ context.Context, url string) (bool, error)

IsAllowedURL returns true if the URL is in the AllowedURLs map.

type MockAnnouncementRepository

type MockAnnouncementRepository struct {
	Items map[string]*model.Announcement
	Reads map[string]bool // keyed by "userId:announcementId"
}

func NewMockAnnouncementRepository

func NewMockAnnouncementRepository() *MockAnnouncementRepository

func (*MockAnnouncementRepository) ArchiveExpired

func (m *MockAnnouncementRepository) ArchiveExpired(now time.Time) (int64, error)

ArchiveExpired mirrors the repository: active announcements whose autoArchiveAt is at or before now become inactive.

func (*MockAnnouncementRepository) CountReadsByAnnouncementIDs

func (m *MockAnnouncementRepository) CountReadsByAnnouncementIDs(ids []string) (map[string]int64, error)

func (*MockAnnouncementRepository) Create

func (*MockAnnouncementRepository) Delete

func (m *MockAnnouncementRepository) Delete(id string) error

func (*MockAnnouncementRepository) FindByID

func (*MockAnnouncementRepository) IsRead

func (m *MockAnnouncementRepository) IsRead(userID, announcementID string) (bool, error)

func (*MockAnnouncementRepository) List

func (m *MockAnnouncementRepository) List(activeOnly bool, limit, offset int, sinceID, untilID string) ([]*model.Announcement, error)

func (*MockAnnouncementRepository) ListForAdmin

func (m *MockAnnouncementRepository) ListForAdmin(userID, status string, limit int, sinceID, untilID string, now time.Time) ([]*model.Announcement, error)

func (*MockAnnouncementRepository) ListForUser

func (m *MockAnnouncementRepository) ListForUser(userID string, activeOnly bool, limit int, sinceID, untilID string) ([]*model.Announcement, error)

func (*MockAnnouncementRepository) ListGlobal

func (m *MockAnnouncementRepository) ListGlobal(activeOnly bool, limit int, sinceID, untilID string) ([]*model.Announcement, error)

func (*MockAnnouncementRepository) ListScheduledArchives

func (m *MockAnnouncementRepository) ListScheduledArchives(now time.Time) ([]*model.Announcement, error)

ListScheduledArchives mirrors the repository: active announcements whose autoArchiveAt is after now, ordered by id.

func (*MockAnnouncementRepository) MarkRead

func (*MockAnnouncementRepository) UnreadForUser

func (m *MockAnnouncementRepository) UnreadForUser(userID string) ([]*model.Announcement, error)

func (*MockAnnouncementRepository) UpdateFields

func (m *MockAnnouncementRepository) UpdateFields(id string, fields map[string]any) error

type MockAntennaNoteUnreadRepository

type MockAntennaNoteUnreadRepository struct {
	Rows []*model.AntennaNoteUnread
}

MockAntennaNoteUnreadRepository is a test double for repository.AntennaNoteUnreadRepository.

func NewMockAntennaNoteUnreadRepository

func NewMockAntennaNoteUnreadRepository() *MockAntennaNoteUnreadRepository

NewMockAntennaNoteUnreadRepository returns an empty repository.

func (*MockAntennaNoteUnreadRepository) Create

Create records the unread row.

func (*MockAntennaNoteUnreadRepository) DeleteByAntennaUser

func (m *MockAntennaNoteUnreadRepository) DeleteByAntennaUser(userID, antennaID string) error

DeleteByAntennaUser removes all rows for the (user, antenna) pair.

func (*MockAntennaNoteUnreadRepository) HasAnyByUser

func (m *MockAntennaNoteUnreadRepository) HasAnyByUser(userID string) (bool, error)

HasAnyByUser returns whether any row exists for the userID.

type MockAntennaRepository

type MockAntennaRepository struct {
	Antennas  map[string]*model.Antenna
	CreateErr error
	UpdateErr error
	// LastUpdates は UpdateFields に最後に渡された fields map を capture
	// する。caller が model.StringArray 等で正しく wrap しているかを test 側で
	// assert するため (#896 と同 pattern)。
	LastUpdates map[string]any
}

MockAntennaRepository is a test double for repository.AntennaRepository.

func NewMockAntennaRepository

func NewMockAntennaRepository() *MockAntennaRepository

NewMockAntennaRepository creates an empty MockAntennaRepository.

func (*MockAntennaRepository) CountByUser

func (m *MockAntennaRepository) CountByUser(userID string) (int64, error)

func (*MockAntennaRepository) Create

func (m *MockAntennaRepository) Create(a *model.Antenna) error

func (*MockAntennaRepository) DeactivateUnusedSince

func (m *MockAntennaRepository) DeactivateUnusedSince(cutoff time.Time) (int64, error)

func (*MockAntennaRepository) Delete

func (m *MockAntennaRepository) Delete(a *model.Antenna) error

func (*MockAntennaRepository) FindByID

func (m *MockAntennaRepository) FindByID(id string) (*model.Antenna, error)

func (*MockAntennaRepository) ListAllActive

func (m *MockAntennaRepository) ListAllActive() ([]*model.Antenna, error)

func (*MockAntennaRepository) ListByUser

func (m *MockAntennaRepository) ListByUser(userID string) ([]*model.Antenna, error)

func (*MockAntennaRepository) UpdateFields

func (m *MockAntennaRepository) UpdateFields(antennaID string, fields map[string]any) error

type MockAuthSessionRepository

type MockAuthSessionRepository struct {
	Apps         map[string]*model.App         // keyed by ID
	Sessions     map[string]*model.AuthSession // keyed by ID
	AccessTokens map[string]*model.AccessToken // keyed by ID
}

MockAuthSessionRepository is a test double for repository.AuthSessionRepository.

func NewMockAuthSessionRepository

func NewMockAuthSessionRepository() *MockAuthSessionRepository

func (*MockAuthSessionRepository) CreateAccessToken

func (m *MockAuthSessionRepository) CreateAccessToken(token *model.AccessToken) error

func (*MockAuthSessionRepository) CreateApp

func (m *MockAuthSessionRepository) CreateApp(app *model.App) error

func (*MockAuthSessionRepository) CreateSession

func (m *MockAuthSessionRepository) CreateSession(session *model.AuthSession) error

func (*MockAuthSessionRepository) DeleteSession

func (m *MockAuthSessionRepository) DeleteSession(sessionID string) error

func (*MockAuthSessionRepository) FindAccessTokenByAppAndUser

func (m *MockAuthSessionRepository) FindAccessTokenByAppAndUser(appID, userID string) (*model.AccessToken, error)

func (*MockAuthSessionRepository) FindAccessTokenBySession

func (m *MockAuthSessionRepository) FindAccessTokenBySession(session string) (*model.AccessToken, error)

func (*MockAuthSessionRepository) FindAppByID

func (m *MockAuthSessionRepository) FindAppByID(id string) (*model.App, error)

func (*MockAuthSessionRepository) FindAppBySecret

func (m *MockAuthSessionRepository) FindAppBySecret(secret string) (*model.App, error)

func (*MockAuthSessionRepository) FindSessionByToken

func (m *MockAuthSessionRepository) FindSessionByToken(token string) (*model.AuthSession, error)

func (*MockAuthSessionRepository) FindSessionByTokenAndAppID

func (m *MockAuthSessionRepository) FindSessionByTokenAndAppID(token, appID string) (*model.AuthSession, error)

func (*MockAuthSessionRepository) ListAppsByUserID

func (m *MockAuthSessionRepository) ListAppsByUserID(userID string, limit, offset int) ([]*model.App, error)

func (*MockAuthSessionRepository) MarkAccessTokenFetched

func (m *MockAuthSessionRepository) MarkAccessTokenFetched(id string) (bool, error)

func (*MockAuthSessionRepository) UpdateSessionUserID

func (m *MockAuthSessionRepository) UpdateSessionUserID(sessionID, userID string) error

type MockAvatarDecorationRepository

type MockAvatarDecorationRepository struct {
	Decorations map[string]*model.AvatarDecoration
	CreateErr   error
}

MockAvatarDecorationRepository is a test double for repository.AvatarDecorationRepository.

func NewMockAvatarDecorationRepository

func NewMockAvatarDecorationRepository() *MockAvatarDecorationRepository

NewMockAvatarDecorationRepository creates an empty mock.

func (*MockAvatarDecorationRepository) Create

func (*MockAvatarDecorationRepository) Delete

func (*MockAvatarDecorationRepository) FindByID

func (*MockAvatarDecorationRepository) List

func (*MockAvatarDecorationRepository) UpdateFields

func (m *MockAvatarDecorationRepository) UpdateFields(id string, fields map[string]any) error

type MockBlockingRepository

type MockBlockingRepository struct {
	Blockings map[string]*model.Blocking // keyed by ID
	// ExistsErr, when set, is returned by Exists to exercise fail-closed paths.
	ExistsErr error
}

MockBlockingRepository is a test double for repository.BlockingRepository.

func NewMockBlockingRepository

func NewMockBlockingRepository() *MockBlockingRepository

func (*MockBlockingRepository) Create

func (*MockBlockingRepository) Delete

func (*MockBlockingRepository) Exists

func (m *MockBlockingRepository) Exists(blockerID, blockeeID string) (bool, error)

func (*MockBlockingRepository) FindByPair

func (m *MockBlockingRepository) FindByPair(blockerID, blockeeID string) (*model.Blocking, error)

func (*MockBlockingRepository) ListBlockeeIDs

func (m *MockBlockingRepository) ListBlockeeIDs(blockerID string) ([]string, error)

ListBlockeeIDs returns blockeeIDs of every block row whose blockerId equals blockerID (#2106 N3).

func (*MockBlockingRepository) ListBlockerIDs

func (m *MockBlockingRepository) ListBlockerIDs(blockeeID string) ([]string, error)

ListBlockerIDs returns blockerIDs of every block row whose blockeeId equals the given user. Mirrors the production blocking repo used by note-list endpoints to drop notes from users who blocked the viewer (#1544). ExistsErr is reused to exercise the fail-closed path on repository error.

func (*MockBlockingRepository) ListByBlocker

func (m *MockBlockingRepository) ListByBlocker(blockerID, sinceID, untilID string, limit, offset int) ([]*model.Blocking, error)

type MockChannelFavoriteRepository

type MockChannelFavoriteRepository struct {
	Favorites map[string]*model.ChannelFavorite // keyed by "userId:channelId"
}

MockChannelFavoriteRepository is a test double for repository.ChannelFavoriteRepository.

func NewMockChannelFavoriteRepository

func NewMockChannelFavoriteRepository() *MockChannelFavoriteRepository

func (*MockChannelFavoriteRepository) Create

func (*MockChannelFavoriteRepository) Delete

func (m *MockChannelFavoriteRepository) Delete(userID, channelID string) error

func (*MockChannelFavoriteRepository) Exists

func (m *MockChannelFavoriteRepository) Exists(userID, channelID string) (bool, error)

func (*MockChannelFavoriteRepository) ExistsMany

func (m *MockChannelFavoriteRepository) ExistsMany(userID string, channelIDs []string) (map[string]bool, error)

func (*MockChannelFavoriteRepository) ListByUser

func (m *MockChannelFavoriteRepository) ListByUser(userID string) ([]*model.ChannelFavorite, error)

type MockChannelFollowingRepository

type MockChannelFollowingRepository struct {
	Followings map[string]*model.ChannelFollowing
}

MockChannelFollowingRepository is a test double for the channel_following repository.

func NewMockChannelFollowingRepository

func NewMockChannelFollowingRepository() *MockChannelFollowingRepository

NewMockChannelFollowingRepository creates an empty MockChannelFollowingRepository.

func (*MockChannelFollowingRepository) Create

func (*MockChannelFollowingRepository) Delete

func (*MockChannelFollowingRepository) Exists

func (m *MockChannelFollowingRepository) Exists(followerID, channelID string) (bool, error)

func (*MockChannelFollowingRepository) ExistsMany

func (m *MockChannelFollowingRepository) ExistsMany(followerID string, channelIDs []string) (map[string]bool, error)

func (*MockChannelFollowingRepository) FindByPair

func (m *MockChannelFollowingRepository) FindByPair(followerID, channelID string) (*model.ChannelFollowing, error)

func (*MockChannelFollowingRepository) ListFollowed

func (m *MockChannelFollowingRepository) ListFollowed(userID, sinceID, untilID string, limit, offset int) ([]*model.ChannelFollowing, error)

func (*MockChannelFollowingRepository) ListFollowerIDsPage

func (m *MockChannelFollowingRepository) ListFollowerIDsPage(channelID, afterRowID string, limit int) ([]string, string, error)

ListFollowerIDsPage returns a page of followerIds for a given channel, ordered by row id ASC. Follows the production repository's cursor-based pagination contract (#320).

type MockChannelMutingRepository

type MockChannelMutingRepository struct {
	Mutings map[string]*model.ChannelMuting // keyed by "userId:channelId"
}

MockChannelMutingRepository is a test double for repository.ChannelMutingRepository.

func NewMockChannelMutingRepository

func NewMockChannelMutingRepository() *MockChannelMutingRepository

func (*MockChannelMutingRepository) Create

func (*MockChannelMutingRepository) Delete

func (m *MockChannelMutingRepository) Delete(userID, channelID string) error

func (*MockChannelMutingRepository) DeleteExpired

func (m *MockChannelMutingRepository) DeleteExpired(now time.Time) ([]string, error)

DeleteExpired removes channel mutes whose ExpiresAt has passed. Returns the userId of every removed row (one entry per row, so duplicates are possible), matching repository.ChannelMutingRepository. 返る順序は保証しない。

func (*MockChannelMutingRepository) Exists

func (m *MockChannelMutingRepository) Exists(userID, channelID string) (bool, error)

func (*MockChannelMutingRepository) ListByUser

func (m *MockChannelMutingRepository) ListByUser(userID string) ([]*model.ChannelMuting, error)

type MockChannelNoteUnreadRepository

type MockChannelNoteUnreadRepository struct {
	Rows []*model.ChannelNoteUnread
}

MockChannelNoteUnreadRepository is a test double for repository.ChannelNoteUnreadRepository.

func NewMockChannelNoteUnreadRepository

func NewMockChannelNoteUnreadRepository() *MockChannelNoteUnreadRepository

NewMockChannelNoteUnreadRepository returns an empty repository.

func (*MockChannelNoteUnreadRepository) Create

Create records the unread row.

func (*MockChannelNoteUnreadRepository) CreateMany

CreateMany appends all rows, silently skipping entries whose (UserID, ChannelID, NoteID) triple already exists (mirrors the real repository's ON CONFLICT DO NOTHING semantics).

func (*MockChannelNoteUnreadRepository) DeleteByChannelUser

func (m *MockChannelNoteUnreadRepository) DeleteByChannelUser(userID, channelID string) error

DeleteByChannelUser removes all rows for the (user, channel) pair.

func (*MockChannelNoteUnreadRepository) HasAnyByUser

func (m *MockChannelNoteUnreadRepository) HasAnyByUser(userID string) (bool, error)

HasAnyByUser returns whether any row exists for the userID.

type MockChannelRepository

type MockChannelRepository struct {
	Channels  map[string]*model.Channel
	CreateErr error
	UpdateErr error
	// PostedAuthors records the authors IncrementUsersCountOnFirstPost has
	// seen per channel. The mock treats the first call for an author as the
	// first post (it has no note table to look at).
	PostedAuthors map[string]map[string]bool
}

MockChannelRepository is a test double for repository.ChannelRepository.

func NewMockChannelRepository

func NewMockChannelRepository() *MockChannelRepository

NewMockChannelRepository creates an empty MockChannelRepository.

func (*MockChannelRepository) Create

func (m *MockChannelRepository) Create(c *model.Channel) error

func (*MockChannelRepository) FindByID

func (m *MockChannelRepository) FindByID(id string) (*model.Channel, error)

func (*MockChannelRepository) FindByIDs

func (m *MockChannelRepository) FindByIDs(ids []string) ([]*model.Channel, error)

func (*MockChannelRepository) IncrementCount

func (m *MockChannelRepository) IncrementCount(channelID, column string, delta int) error

func (*MockChannelRepository) IncrementUsersCountOnFirstPost

func (m *MockChannelRepository) IncrementUsersCountOnFirstPost(channelID, authorID, _ string) error

IncrementUsersCountOnFirstPost adds 1 to usersCount on the first call for (channelID, authorID). 実装は note を見て判定するが、mock は呼び出しの記録で 代える。判定そのものは repository の実 DB テストが見ている。

func (*MockChannelRepository) List

List returns channels matching the most common filter predicates. テストの 安定性のため id 昇順で返す。

func (*MockChannelRepository) UpdateFields

func (m *MockChannelRepository) UpdateFields(channelID string, fields map[string]any) error

type MockChatRepository

type MockChatRepository struct {

	// Rooms keyed by room ID.
	Rooms map[string]*model.ChatRoom
	// Messages keyed by message ID. Stored as cloned copies.
	Messages map[string]*model.ChatMessage
	// Memberships keyed by "<userID>:<roomID>".
	Memberships map[string]*model.ChatRoomMembership
	// Invitations keyed by invitation ID.
	Invitations map[string]*model.ChatRoomInvitation
	// AddedReactions / RemovedReactions record the keys passed to
	// AddReaction / RemoveReaction so tests can assert canonicalisation (#2106 N4).
	AddedReactions   []string
	RemovedReactions []string
	// ReadAllCalls records MarkAllReadFromUser ("user:<reader>:<other>") and
	// MarkAllReadInRoom ("room:<reader>:<room>") calls so stream tests can
	// assert whether a read was performed.
	ReadAllCalls []string

	// CreateErr forces Create* to return this error without persisting.
	CreateErr error
	// UpdateErr forces UpdateMessage to return this error without persisting.
	UpdateErr error
	// DeleteErr forces DeleteMessage to return this error without removing.
	DeleteErr error
	// ListMembershipsErr forces ListMembershipsByUser to return this error.
	ListMembershipsErr error
	// TransferOwnershipErr forces TransferRoomOwnership to return this error
	// without touching the store.
	TransferOwnershipErr error
	// FindRoomErr / FindMembershipErr / ListMembersErr force the corresponding
	// lookup to fail. Used to cover the "DB 障害を not-found に丸めない" branches
	// (#2792), which are otherwise unreachable against an in-memory store.
	FindRoomErr       error
	FindMembershipErr error
	ListMembersErr    error
	// FindInvitationErr は FindInvitation と FindInvitationByID の両方に効く
	// (どちらも同じ「招待を引く」経路で、#2792 の判断も同じであるべきなため)。
	FindInvitationErr error
	// contains filtered or unexported fields
}

MockChatRepository is an in-memory implementation of repository.ChatRepository shared across api/chat, core/chat and stream/channels test packages (#709).

各 test ファイルで重複していた mockChatRepo / fakeChatRepo / chatFakeRepo を集約。ChatRepository に新メソッドを追加するたびに複数 stub に実装を生やす 苦痛を解消する。

設計の意図:

  • 全 map 操作は内部 mutex 配下で行うため goroutine 並列 (例: ap_delivery のジョブ送出) でも race にならない。
  • メッセージ書き込み / 読み込みは clone して保持することで、呼び出し側が 返り値を mutate しても store 内が壊れないようにする。
  • CreateErr / UpdateErr / DeleteErr で error path をテストできる。
  • 各 List* / FindInvitation 等 filter 操作はテストで実際に必要だった ものだけ実装している。残り (ListRoomsByOwner, ListMembersByRoom 等) は記録された state を元に予測可能な順序で返す。

func NewMockChatRepository

func NewMockChatRepository() *MockChatRepository

NewMockChatRepository constructs an empty MockChatRepository ready for use.

func (*MockChatRepository) AddReaction

func (m *MockChatRepository) AddReaction(messageID, key string) error

AddReaction records the attempt and updates the stored message.

**状態を更新するのが要点 (#3037 レビュー)。** 更新しないと、`RemoveReaction` が「消えたか」を返すようになったこと (#3037) と噛み合わず、 `React` → `Unreact` を通すテストで unreact が一度も publish されなくなる。 それでもテストが緑になる形があり (最後のイベントが react なので同じ アサーションを満たす)、**有効だった検査が黙って空虚になっていた**。

func (*MockChatRepository) CountUnread

func (m *MockChatRepository) CountUnread(_ string) (int64, error)

func (*MockChatRepository) CreateInvitation

func (m *MockChatRepository) CreateInvitation(inv *model.ChatRoomInvitation) error

func (*MockChatRepository) CreateMembership

func (m *MockChatRepository) CreateMembership(mem *model.ChatRoomMembership) error

func (*MockChatRepository) CreateMessage

func (m *MockChatRepository) CreateMessage(msg *model.ChatMessage) error

func (*MockChatRepository) CreateRoom

func (m *MockChatRepository) CreateRoom(room *model.ChatRoom) error

func (*MockChatRepository) DeleteInvitation

func (m *MockChatRepository) DeleteInvitation(id string) error

func (*MockChatRepository) DeleteInvitationsToOwnedRooms

func (m *MockChatRepository) DeleteInvitationsToOwnedRooms(ownerID, userID string) error

func (*MockChatRepository) DeleteMembership

func (m *MockChatRepository) DeleteMembership(userID, roomID string) error

func (*MockChatRepository) DeleteMessage

func (m *MockChatRepository) DeleteMessage(id string) error

func (*MockChatRepository) DeleteRoom

func (m *MockChatRepository) DeleteRoom(id string) error

func (*MockChatRepository) FindInvitation

func (m *MockChatRepository) FindInvitation(userID, roomID string) (*model.ChatRoomInvitation, error)

func (*MockChatRepository) FindInvitationByID

func (m *MockChatRepository) FindInvitationByID(id string) (*model.ChatRoomInvitation, error)

func (*MockChatRepository) FindMembership

func (m *MockChatRepository) FindMembership(userID, roomID string) (*model.ChatRoomMembership, error)

func (*MockChatRepository) FindMessageByID

func (m *MockChatRepository) FindMessageByID(id string) (*model.ChatMessage, error)

func (*MockChatRepository) FindMessageByURI

func (m *MockChatRepository) FindMessageByURI(uri string) (*model.ChatMessage, error)

func (*MockChatRepository) FindMessageDetailedByID

func (m *MockChatRepository) FindMessageDetailedByID(id string) (*model.ChatMessage, error)

FindMessageDetailedByID returns the stored row as FindMessageByID does; the mock keeps whatever relations the test stored.

func (*MockChatRepository) FindRoomByID

func (m *MockChatRepository) FindRoomByID(id string) (*model.ChatRoom, error)

func (*MockChatRepository) FindRoomByURI

func (m *MockChatRepository) FindRoomByURI(uri string) (*model.ChatRoom, error)

FindRoomByURI looks a room up by its canonical AP URI (#2994). ローカル room は `uri` が NULL なので一致しない (本物の SQL と同じ)。

func (*MockChatRepository) HasUnreadFromUser

func (m *MockChatRepository) HasUnreadFromUser(readerID, otherID string) (bool, error)

HasUnreadFromUser reports whether readerID has an unread 1-on-1 message from otherID (readerID not in reads). Mirrors the production WHERE clause.

func (*MockChatRepository) HasUnreadInRoom

func (m *MockChatRepository) HasUnreadInRoom(readerID, roomID string) (bool, error)

HasUnreadInRoom reports whether readerID has an unread room message (authored by someone else) in roomID.

func (*MockChatRepository) ListHistory

func (m *MockChatRepository) ListHistory(_ string, _ int) ([]*model.ChatMessage, error)

func (*MockChatRepository) ListInvitationsByRoom

func (m *MockChatRepository) ListInvitationsByRoom(roomID, sinceID, untilID string, limit int) ([]*model.ChatRoomInvitation, error)

func (*MockChatRepository) ListInvitationsByUser

func (m *MockChatRepository) ListInvitationsByUser(_ string, _ bool, _, _ string, _ int) ([]*model.ChatRoomInvitation, error)

func (*MockChatRepository) ListJoinedRooms

func (m *MockChatRepository) ListJoinedRooms(userID, sinceID, untilID string, limit int) ([]*model.ChatRoom, error)

func (*MockChatRepository) ListMembersByRoom

func (m *MockChatRepository) ListMembersByRoom(roomID string) ([]*model.ChatRoomMembership, error)

func (*MockChatRepository) ListMembersByRoomPaged

func (m *MockChatRepository) ListMembersByRoomPaged(roomID, sinceID, untilID string, limit int) ([]*model.ChatRoomMembership, error)

func (*MockChatRepository) ListMembershipsByUser

func (m *MockChatRepository) ListMembershipsByUser(userID, sinceID, untilID string, limit int) ([]*model.ChatRoomMembership, error)

func (*MockChatRepository) ListMessagesByFileID

func (m *MockChatRepository) ListMessagesByFileID(fileID, untilID, sinceID string, limit int) ([]*model.ChatMessage, error)

func (*MockChatRepository) ListMessagesByRoom

func (m *MockChatRepository) ListMessagesByRoom(roomID, sinceID, untilID string, limit int) ([]*model.ChatMessage, error)

func (*MockChatRepository) ListMessagesByUser

func (m *MockChatRepository) ListMessagesByUser(userID, otherUserID, sinceID, untilID string, limit int) ([]*model.ChatMessage, error)

func (*MockChatRepository) ListRoomHistory

func (m *MockChatRepository) ListRoomHistory(_ string, _ int, _ string) ([]*model.ChatMessage, error)

func (*MockChatRepository) ListRoomsByOwner

func (m *MockChatRepository) ListRoomsByOwner(ownerID, sinceID, untilID string, limit int) ([]*model.ChatRoom, error)

func (*MockChatRepository) ListUserHistory

func (m *MockChatRepository) ListUserHistory(_ string, _ int, _ string) ([]*model.ChatMessage, error)

func (*MockChatRepository) MarkAllRead

func (m *MockChatRepository) MarkAllRead(_ string) error

func (*MockChatRepository) MarkAllReadFromUser

func (m *MockChatRepository) MarkAllReadFromUser(readerID, otherID string) error

func (*MockChatRepository) MarkAllReadInRoom

func (m *MockChatRepository) MarkAllReadInRoom(readerID, roomID string) error

func (*MockChatRepository) MarkRead

func (m *MockChatRepository) MarkRead(userID, messageID string) error

MarkRead appends userID to the message's reads slice (idempotency は real impl 側のクエリで担保される。テスト用なので重複防止はしない)。

func (*MockChatRepository) RemoveReaction

func (m *MockChatRepository) RemoveReaction(messageID, key string) (bool, error)

func (*MockChatRepository) SearchMessages

func (m *MockChatRepository) SearchMessages(meID, query string, limit int, userID, roomID string) ([]*model.ChatMessage, error)

func (*MockChatRepository) TransferRoomOwnership

func (m *MockChatRepository) TransferRoomOwnership(roomID, oldOwnerID, newOwnerID, oldOwnerMembershipID string) error

TransferRoomOwnership mirrors the real repository: it moves ownership only when the room is still owned by oldOwnerID, and swaps the membership rows so that the owner never holds one (see repository.TransferRoomOwnership).

**意味論を実装に揃えておくこと。** ここが単なる ownerId 代入だと、 membership 行の入れ替えを検証しているつもりのテストが素通りする。

func (*MockChatRepository) UnreadFromUsers

func (m *MockChatRepository) UnreadFromUsers(readerID string, otherIDs []string) (map[string]bool, error)

UnreadFromUsers is the batched HasUnreadFromUser.

func (*MockChatRepository) UnreadInRooms

func (m *MockChatRepository) UnreadInRooms(readerID string, roomIDs []string) (map[string]bool, error)

UnreadInRooms is the batched HasUnreadInRoom.

func (*MockChatRepository) UpdateDeliveryStatus

func (m *MockChatRepository) UpdateDeliveryStatus(_ string, _, _ bool) error

func (*MockChatRepository) UpdateInvitation

func (m *MockChatRepository) UpdateInvitation(inv *model.ChatRoomInvitation) error

func (*MockChatRepository) UpdateMembership

func (m *MockChatRepository) UpdateMembership(mem *model.ChatRoomMembership) error

func (*MockChatRepository) UpdateMessage

func (m *MockChatRepository) UpdateMessage(msg *model.ChatMessage) error

func (*MockChatRepository) UpdateRoom

func (m *MockChatRepository) UpdateRoom(room *model.ChatRoom) error

type MockClipFavoriteRepository

type MockClipFavoriteRepository struct {
	Favorites map[string]*model.ClipFavorite // keyed by "userId:clipId"
}

MockClipFavoriteRepository is a test double for repository.ClipFavoriteRepository.

func NewMockClipFavoriteRepository

func NewMockClipFavoriteRepository() *MockClipFavoriteRepository

func (*MockClipFavoriteRepository) CountByClip

func (m *MockClipFavoriteRepository) CountByClip(clipID string) (int64, error)

func (*MockClipFavoriteRepository) Create

func (*MockClipFavoriteRepository) Delete

func (m *MockClipFavoriteRepository) Delete(userID, clipID string) error

func (*MockClipFavoriteRepository) Exists

func (m *MockClipFavoriteRepository) Exists(userID, clipID string) (bool, error)

func (*MockClipFavoriteRepository) ListByUser

func (m *MockClipFavoriteRepository) ListByUser(userID string) ([]*model.ClipFavorite, error)

type MockClipNoteRepository

type MockClipNoteRepository struct {
	Entries map[string]*model.ClipNote
	// Notes / Following は ListByClipVisible の visibility push-down 再現に
	// 使う。Notes は noteID -> note (visibility 判定用)、Following は
	// followerID -> followeeIDs。未設定なら note 不在扱い (= 非可視)。
	Notes     map[string]*model.Note
	Following map[string][]string
}

MockClipNoteRepository is a test double for repository.ClipNoteRepository.

func NewMockClipNoteRepository

func NewMockClipNoteRepository() *MockClipNoteRepository

NewMockClipNoteRepository creates an empty MockClipNoteRepository.

func (*MockClipNoteRepository) CountByClip

func (m *MockClipNoteRepository) CountByClip(clipID string) (int64, error)

func (*MockClipNoteRepository) Create

func (m *MockClipNoteRepository) Create(cn *model.ClipNote) error

func (*MockClipNoteRepository) Delete

func (m *MockClipNoteRepository) Delete(cn *model.ClipNote) error

func (*MockClipNoteRepository) DeleteByPair

func (m *MockClipNoteRepository) DeleteByPair(clipID, noteID string) (int64, error)

DeleteByPair removes the matching entries and returns how many were removed.

func (*MockClipNoteRepository) FindByPair

func (m *MockClipNoteRepository) FindByPair(clipID, noteID string) (*model.ClipNote, error)

func (*MockClipNoteRepository) ListByClip

func (m *MockClipNoteRepository) ListByClip(clipID string, untilID, sinceID string, limit int) ([]*model.ClipNote, error)

func (*MockClipNoteRepository) ListByClipVisible

func (m *MockClipNoteRepository) ListByClipVisible(clipID, viewerID, untilID, sinceID string, limit int, searchWords []string) ([]*model.ClipNote, error)

ListByClipVisible mirrors the real repo's visibility push-down: clip entries whose note the viewer cannot see are dropped before the limit slice. searchWords は実 repo と同じく text / cw への部分一致 (語内 OR、語間 AND) を case-insensitive で再現する (#1562)。

func (*MockClipNoteRepository) ListClipIDsByNote

func (m *MockClipNoteRepository) ListClipIDsByNote(noteID string) ([]string, error)

ListClipIDsByNote returns the distinct clipIds containing noteID.

type MockClipRepository

type MockClipRepository struct {
	Clips     map[string]*model.Clip
	CreateErr error
	UpdateErr error
}

MockClipRepository is a test double for repository.ClipRepository.

func NewMockClipRepository

func NewMockClipRepository() *MockClipRepository

NewMockClipRepository creates an empty MockClipRepository.

func (*MockClipRepository) CountByUser

func (m *MockClipRepository) CountByUser(userID string) (int64, error)

func (*MockClipRepository) Create

func (m *MockClipRepository) Create(c *model.Clip) error

func (*MockClipRepository) Delete

func (m *MockClipRepository) Delete(c *model.Clip) error

func (*MockClipRepository) FindByID

func (m *MockClipRepository) FindByID(id string) (*model.Clip, error)

func (*MockClipRepository) ListByUser

func (m *MockClipRepository) ListByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.Clip, error)

func (*MockClipRepository) ListPublicByIDs

func (m *MockClipRepository) ListPublicByIDs(ids []string) ([]*model.Clip, error)

ListPublicByIDs returns the public clips whose id is in ids (any owner).

func (*MockClipRepository) ListPublicByUser

func (m *MockClipRepository) ListPublicByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.Clip, error)

func (*MockClipRepository) UpdateFields

func (m *MockClipRepository) UpdateFields(clipID string, fields map[string]any) error

type MockDriveFileRepository

type MockDriveFileRepository struct {
	Files map[string]*model.DriveFile // keyed by ID
	// EmojiReferencedURLs は DeleteOrphans / ListOrphans の guard を mock する
	// ための「emoji が参照している drive_file.url 集合」。production の SQL
	// (`emojiReferencesFile`) は
	// `EXISTS (SELECT 1 FROM emoji WHERE originalUrl = url OR publicUrl = url)`
	// で、**2 列のどちらか**が一致すれば除外する (#722)。本フィールドはその
	// 和集合を表すので、片方の列だけを模倣しているわけではない。
	// IsReferencedByEmoji (#3678) も同じ集合を見る (production はローカルの
	// 絵文字だけを数えるが、mock は絵文字のホストを区別しない)。
	//
	// 空なら emoji guard は効かない。ただしそれは「userId NULL を全削除」を
	// 意味しない — userHost 条件が別にあるため、リモートの owner 無し行は
	// emoji 参照が無くても残る (#2721)。
	EmojiReferencedURLs map[string]bool
	// IsReferencedByEmojiErr forces IsReferencedByEmoji to fail.
	IsReferencedByEmojiErr error

	// NoteReferencedFileIDs は ListOrphanRemoteAttachmentCandidates の guard を
	// mock するための「いずれかの note.fileIds に載っている drive_file.id 集合」
	// (#2722)。production の SQL は
	// `NOT EXISTS (SELECT 1 FROM note WHERE "fileIds" @> ARRAY[id])`。
	NoteReferencedFileIDs map[string]bool

	// BulkFolderUserID / BulkFolderFileIDs record the last UpdateBulkFolder
	// call so handler tests can assert the owning user is scoped (IDOR guard).
	BulkFolderUserID  string
	BulkFolderFileIDs []string

	// 以下は bulk cleanup (clean-remote-files / delete-all-files) のエラー経路を
	// テストするための注入フィールド。nil なら通常動作。
	ListRemoteCacheErr error
	ListByUserAllErr   error
	ListOrphansErr     error
	DeleteByIDsErr     error
	// DeleteByIDsNoOp を true にすると DeleteByIDs が err=nil で 0 件削除する
	// (= 行が縮小しない degenerate ケース。maxBatches 安全弁の終了性検証用)。
	DeleteByIDsNoOp bool
}

MockDriveFileRepository is a test double for repository.DriveFileRepository.

func NewMockDriveFileRepository

func NewMockDriveFileRepository() *MockDriveFileRepository

func (*MockDriveFileRepository) CountByFolder

func (m *MockDriveFileRepository) CountByFolder(folderID string) (int, error)

func (*MockDriveFileRepository) Create

func (*MockDriveFileRepository) Delete

func (*MockDriveFileRepository) DeleteByHost

func (m *MockDriveFileRepository) DeleteByHost(host string) (int64, error)

func (*MockDriveFileRepository) DeleteByIDs

func (m *MockDriveFileRepository) DeleteByIDs(ids []string) (int64, error)

func (*MockDriveFileRepository) DeleteByUser

func (m *MockDriveFileRepository) DeleteByUser(userID string) (int64, error)

func (*MockDriveFileRepository) DeleteOrphans

func (m *MockDriveFileRepository) DeleteOrphans() (int64, error)

DeleteOrphans の mock は production SQL の semantics を model 化する: userId NULL かつ userHost NULL かつ EmojiReferencedURLs に URL が 含まれない drive file を削除する (#722 / #2721)。

`userHost` を見る条件は後から入ったもので、mock 側が追随していない間は 「リモートの owner 無し行が消える」という production では起きない挙動を 通していた。production の条件は internal/repository/drive_file.go の orphanWhere を参照。

func (*MockDriveFileRepository) ExistsByMD5

func (m *MockDriveFileRepository) ExistsByMD5(userID, md5 string) (bool, error)

func (*MockDriveFileRepository) ExpireByIDs

func (m *MockDriveFileRepository) ExpireByIDs(ids []string) (int64, error)

ExpireByIDs turns the given rows into link rows (#3102)。

func (*MockDriveFileRepository) ExpireRemoteCache

func (m *MockDriveFileRepository) ExpireRemoteCache() (int64, error)

ExpireRemoteCache mirrors the repository: cached remote rows become link rows instead of being deleted (#3102)。`uri` を持たない行だけ消す。

func (*MockDriveFileRepository) FindAllByMD5

func (m *MockDriveFileRepository) FindAllByMD5(userID, md5 string) ([]*model.DriveFile, error)

FindAllByMD5 returns every md5-matching file of the user, id ASC (production 実装と同じ決定的順序)。

func (*MockDriveFileRepository) FindByAccessKey

func (m *MockDriveFileRepository) FindByAccessKey(accessKey string) (*model.DriveFile, error)

func (*MockDriveFileRepository) FindByAnyAccessKey

func (m *MockDriveFileRepository) FindByAnyAccessKey(accessKey string) (*model.DriveFile, error)

func (*MockDriveFileRepository) FindByAnyURL

func (m *MockDriveFileRepository) FindByAnyURL(url string) (*model.DriveFile, error)

func (*MockDriveFileRepository) FindByID

func (m *MockDriveFileRepository) FindByID(id string) (*model.DriveFile, error)

func (*MockDriveFileRepository) FindByIDs

func (m *MockDriveFileRepository) FindByIDs(ids []string) ([]*model.DriveFile, error)

FindByIDs mirrors production's `id IN ?`: **重複した id を渡しても行は 1 度 しか返らない** (#2755)。

旧実装は入力の重複をそのまま重複行で返していた。漏れる先は **AP renderer の `addAttachments`** で、あそこは戻り行をそのまま `attachment` に並べるので 重複 id で Document が二重になる。到達可能な乖離だったので production に揃える。

(entity の pack は `n.FileIDs` を回すので、`note.fileIds` の重複は production でも二重に pack される。#2755 の issue 本文にあった「pack が二重になる」は誤り。)

func (*MockDriveFileRepository) FindByMD5

func (m *MockDriveFileRepository) FindByMD5(userID, md5 string) (*model.DriveFile, error)

func (*MockDriveFileRepository) FindByName

func (m *MockDriveFileRepository) FindByName(userID, name string, folderID *string) ([]*model.DriveFile, error)

func (*MockDriveFileRepository) FindByURI

func (m *MockDriveFileRepository) FindByURI(uri string) (*model.DriveFile, error)

func (*MockDriveFileRepository) IsReferencedByEmoji

func (m *MockDriveFileRepository) IsReferencedByEmoji(id string) (bool, error)

IsReferencedByEmoji mirrors the repository (#3678). IsReferencedByEmojiErr forces it to fail.

func (*MockDriveFileRepository) ListByFileIDs

func (m *MockDriveFileRepository) ListByFileIDs(ids []string) ([]*model.DriveFile, error)

func (*MockDriveFileRepository) ListByHost

func (m *MockDriveFileRepository) ListByHost(host string) ([]*model.DriveFile, error)

func (*MockDriveFileRepository) ListByUser

func (m *MockDriveFileRepository) ListByUser(userID string, folderID *string, anyFolder bool, fileType, sort, untilID, sinceID string, limit int) ([]*model.DriveFile, error)

ListByUser mirrors the production predicates and ordering. caller が知って おくべき差は 3 つで、うち 1 つは**意図的な簡略化**:

  • `limit <= 0` を「無制限」として扱う。**乖離するのは `limit == 0` だけ** — production は生の値を GORM に渡し、GORM は負値では LIMIT 句自体を出さない ので `limit < 0` は production も無制限になる (#2755 のレビューで発見)。 handler は `pagination.ResolveLimit` が 1 未満を 400 で弾くので endpoint 経由では到達しない。**mock を直に叩くときは実値を渡すこと**

残り 2 つは関数本体のコメントにある: name 比較の collation 差と、tie が id 昇順に落ちること (production は tie 順を保証しない)。

func (*MockDriveFileRepository) ListByUserAll

func (m *MockDriveFileRepository) ListByUserAll(userID string, limit int) ([]*model.DriveFile, error)

func (*MockDriveFileRepository) ListForAdmin

func (m *MockDriveFileRepository) ListForAdmin(userID, origin, host, fileType, untilID, sinceID string, limit int) ([]*model.DriveFile, error)

func (*MockDriveFileRepository) ListOrphanRemoteAttachmentCandidates

func (m *MockDriveFileRepository) ListOrphanRemoteAttachmentCandidates(cutoffID, afterID string, limit int) ([]string, error)

ListOrphanRemoteAttachmentCandidates mirrors the production candidate query for owner-less remote link attachments (#2722).

**参照チェックは NoteReferencedFileIDs で模倣する。** production は `note.fileIds @> ARRAY[id]` で「どの note からも参照されていない」ことを 確かめており、この述語が materialize 済み / dedup 再利用された添付を守る。 空にすると「参照されている行も候補に出る」という production では起きない 挙動を通してしまう。

func (*MockDriveFileRepository) ListOrphans

func (m *MockDriveFileRepository) ListOrphans(limit int) ([]*model.DriveFile, error)

ListOrphans mirrors DeleteOrphans's selection without deleting (#1724).

func (*MockDriveFileRepository) ListRemoteCache

func (m *MockDriveFileRepository) ListRemoteCache(limit int) ([]*model.DriveFile, error)

func (*MockDriveFileRepository) ListSystemFiles

func (m *MockDriveFileRepository) ListSystemFiles(fileType, untilID, sinceID string, limit int) ([]*model.DriveFile, error)

func (*MockDriveFileRepository) Update

func (m *MockDriveFileRepository) Update(id string, fields map[string]any) error

func (*MockDriveFileRepository) UpdateBulkFolder

func (m *MockDriveFileRepository) UpdateBulkFolder(userID string, fileIDs []string, folderID *string) error

UpdateBulkFolder records the call **and applies it** (#2755)。

旧実装は呼び出しを記録するだけで Files を変更しなかったため、「移動後に読み 直す」テストが書けなかった。production と同じく **userID で絞る** ので、 他人の file を指定しても動かない。

**記録 (BulkFolderUserID) は今も要る。** handler が自分の user.ID を渡して いるかを確かめられるのは記録だけで、この述語は production の guard を 模しているだけ。層が違う。

func (*MockDriveFileRepository) UsageByUser

func (m *MockDriveFileRepository) UsageByUser(userID string) (int64, error)

type MockDriveFolderRepository

type MockDriveFolderRepository struct {
	Folders map[string]*model.DriveFolder
	// FilesRef は HasChildren が参照するファイルストア。テストで紐づける。
	FilesRef *MockDriveFileRepository
}

MockDriveFolderRepository is a test double for repository.DriveFolderRepository.

func NewMockDriveFolderRepository

func NewMockDriveFolderRepository() *MockDriveFolderRepository

func (*MockDriveFolderRepository) CountChildFolders

func (m *MockDriveFolderRepository) CountChildFolders(parentID string) (int, error)

func (*MockDriveFolderRepository) Create

func (*MockDriveFolderRepository) Delete

func (*MockDriveFolderRepository) FindByID

func (*MockDriveFolderRepository) FindByIDs

func (m *MockDriveFolderRepository) FindByIDs(ids []string) ([]*model.DriveFolder, error)

FindByIDs returns the folders present in the mock for the given ID set (missing IDs are skipped, mirroring an IN query).

file 側と同じく**重複した id は 1 度しか返さない** (#2755)。production の `Where("id IN ?")` (repository/drive_folder.go) がそうで、doc も「IN を模す」と 言っている以上ここだけ違うと主張が偽になる。

func (*MockDriveFolderRepository) FindByName

func (m *MockDriveFolderRepository) FindByName(userID, name string, parentID *string) ([]*model.DriveFolder, error)

func (*MockDriveFolderRepository) HasChildren

func (m *MockDriveFolderRepository) HasChildren(folderID string) (bool, error)

func (*MockDriveFolderRepository) ListByUser

func (m *MockDriveFolderRepository) ListByUser(userID string, parentID *string, untilID, sinceID string, limit int) ([]*model.DriveFolder, error)

func (*MockDriveFolderRepository) Update

func (m *MockDriveFolderRepository) Update(id string, fields map[string]any) error

type MockEmojiRepository

type MockEmojiRepository struct {
	// keyed by "name@host" (host="" for local)
	Emojis map[string]*model.Emoji
	// CreateErr/UpdateErr forces Create/UpdateFields to return the given error
	// without persisting. Used to exercise upsertEmojis error handling paths.
	CreateErr error
	UpdateErr error
	// DeleteErr forces Delete to return the given error (#2966 の補償処理で
	// 「絵文字は消せなかったが drive の複製は片付ける」経路を作るため)。
	DeleteErr error
}

MockEmojiRepository is a test double for repository.EmojiRepository.

func NewMockEmojiRepository

func NewMockEmojiRepository() *MockEmojiRepository

func (*MockEmojiRepository) CountV2

func (m *MockEmojiRepository) CountV2(filter model.EmojiV2Filter) (int64, error)

func (*MockEmojiRepository) Create

func (m *MockEmojiRepository) Create(e *model.Emoji) error

func (*MockEmojiRepository) Delete

func (m *MockEmojiRepository) Delete(id string) error

func (*MockEmojiRepository) DeleteMany

func (m *MockEmojiRepository) DeleteMany(ids []string) error

func (*MockEmojiRepository) FindByID

func (m *MockEmojiRepository) FindByID(id string) (*model.Emoji, error)

func (*MockEmojiRepository) FindByNameAndHost

func (m *MockEmojiRepository) FindByNameAndHost(name string, host *string) (*model.Emoji, error)

func (*MockEmojiRepository) FindManyByIDs

func (m *MockEmojiRepository) FindManyByIDs(ids []string) ([]*model.Emoji, error)

func (*MockEmojiRepository) FindManyByKeys

func (m *MockEmojiRepository) FindManyByKeys(keys []model.EmojiKey) ([]*model.Emoji, error)

FindManyByKeys returns emojis matching any of the given (name, host) pairs.

func (*MockEmojiRepository) FindManyByNamesAndHost

func (m *MockEmojiRepository) FindManyByNamesAndHost(names []string, host *string) ([]*model.Emoji, error)

FindManyByNamesAndHost returns emojis matching any of the given names for a specific host.

func (*MockEmojiRepository) ListLocal

func (m *MockEmojiRepository) ListLocal() ([]*model.Emoji, error)

func (*MockEmojiRepository) ListRemoteWithFilter

func (m *MockEmojiRepository) ListRemoteWithFilter(query, host, sinceID, untilID string, limit, offset int) ([]*model.Emoji, error)

func (*MockEmojiRepository) ListV2

func (m *MockEmojiRepository) ListV2(filter model.EmojiV2Filter) ([]*model.Emoji, error)

func (*MockEmojiRepository) ListWithFilter

func (m *MockEmojiRepository) ListWithFilter(query, category string, local bool, sinceID, untilID string, limit, offset int) ([]*model.Emoji, error)

func (*MockEmojiRepository) UpdateFields

func (m *MockEmojiRepository) UpdateFields(id string, fields map[string]any) error

func (*MockEmojiRepository) UpdateFieldsMany

func (m *MockEmojiRepository) UpdateFieldsMany(ids []string, fields map[string]any) error

type MockFlashLikeRepository

type MockFlashLikeRepository struct {
	Likes map[string]*model.FlashLike
}

MockFlashLikeRepository is a test double for repository.FlashLikeRepository.

func NewMockFlashLikeRepository

func NewMockFlashLikeRepository() *MockFlashLikeRepository

NewMockFlashLikeRepository creates an empty MockFlashLikeRepository.

func (*MockFlashLikeRepository) Create

func (*MockFlashLikeRepository) Delete

func (*MockFlashLikeRepository) Exists

func (m *MockFlashLikeRepository) Exists(userID, flashID string) (bool, error)

func (*MockFlashLikeRepository) FindByPair

func (m *MockFlashLikeRepository) FindByPair(userID, flashID string) (*model.FlashLike, error)

func (*MockFlashLikeRepository) ListByUser

func (m *MockFlashLikeRepository) ListByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.FlashLike, error)

func (*MockFlashLikeRepository) ListByUserSearch

func (m *MockFlashLikeRepository) ListByUserSearch(userID, _, sinceID, untilID string, limit, offset int) ([]*model.FlashLike, error)

ListByUserSearch ignores the search filter (the mock holds no flash title / summary to match against) and delegates to ListByUser. The SQL search path is covered by the repository-level DB test.

func (*MockFlashLikeRepository) ListLikedFlashIDs

func (m *MockFlashLikeRepository) ListLikedFlashIDs(userID string, flashIDs []string) ([]string, error)

ListLikedFlashIDs returns the subset of flashIDs liked by userID.

type MockFlashRepository

type MockFlashRepository struct {
	Flashes   map[string]*model.Flash
	CreateErr error
	UpdateErr error
	// LastUpdates は UpdateFields に最後に渡された fields map を capture
	// する。caller が slice value を model.StringArray 等で正しく wrap して
	// いるかを test 側で assert するため (#896)。
	LastUpdates map[string]any
}

MockFlashRepository is a test double for repository.FlashRepository.

func NewMockFlashRepository

func NewMockFlashRepository() *MockFlashRepository

NewMockFlashRepository creates an empty MockFlashRepository.

func (*MockFlashRepository) Create

func (m *MockFlashRepository) Create(f *model.Flash) error

func (*MockFlashRepository) Delete

func (m *MockFlashRepository) Delete(f *model.Flash) error

func (*MockFlashRepository) FindByID

func (m *MockFlashRepository) FindByID(id string) (*model.Flash, error)

func (*MockFlashRepository) IncrementCount

func (m *MockFlashRepository) IncrementCount(flashID, column string, delta int) error

func (*MockFlashRepository) ListByUser

func (m *MockFlashRepository) ListByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.Flash, error)

func (*MockFlashRepository) ListFeatured

func (m *MockFlashRepository) ListFeatured(sinceID, untilID string, limit, offset int) ([]*model.Flash, error)

func (*MockFlashRepository) ListPublicByUser

func (m *MockFlashRepository) ListPublicByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.Flash, error)

func (*MockFlashRepository) Search

func (m *MockFlashRepository) Search(query, sinceID, untilID string, limit, offset int) ([]*model.Flash, error)

func (*MockFlashRepository) UpdateFields

func (m *MockFlashRepository) UpdateFields(flashID string, fields map[string]any) error

type MockFollowRequestRepository

type MockFollowRequestRepository struct {
	Requests map[string]*model.FollowRequest
}

MockFollowRequestRepository is a test double for repository.FollowRequestRepository.

func NewMockFollowRequestRepository

func NewMockFollowRequestRepository() *MockFollowRequestRepository

func (*MockFollowRequestRepository) CountReceived

func (m *MockFollowRequestRepository) CountReceived(userID string) (int64, error)

CountReceived returns the number of pending requests addressed to userID.

func (*MockFollowRequestRepository) Create

func (*MockFollowRequestRepository) Delete

func (*MockFollowRequestRepository) DeleteAllByUser

func (m *MockFollowRequestRepository) DeleteAllByUser(userID string) error

func (*MockFollowRequestRepository) Exists

func (m *MockFollowRequestRepository) Exists(followerID, followeeID string) (bool, error)

func (*MockFollowRequestRepository) FilterPendingFromAnchor

func (m *MockFollowRequestRepository) FilterPendingFromAnchor(anchorID string, candidateIDs []string) ([]string, error)

func (*MockFollowRequestRepository) FilterPendingToAnchor

func (m *MockFollowRequestRepository) FilterPendingToAnchor(anchorID string, candidateIDs []string) ([]string, error)

func (*MockFollowRequestRepository) FindByPair

func (m *MockFollowRequestRepository) FindByPair(followerID, followeeID string) (*model.FollowRequest, error)

func (*MockFollowRequestRepository) ListReceived

func (m *MockFollowRequestRepository) ListReceived(userID string, limit int, sinceID, untilID string) ([]*model.FollowRequest, error)

func (*MockFollowRequestRepository) ListSent

func (m *MockFollowRequestRepository) ListSent(userID string, limit int, sinceID, untilID string) ([]*model.FollowRequest, error)

type MockFollowingRepository

type MockFollowingRepository struct {
	Followings map[string]*model.Following // keyed by ID
	// RemoteInboxes stores per-followee inbox lists used by
	// ListRemoteFollowerInboxes. テスト側で明示的に登録する。
	RemoteInboxes map[string][]string
	// RemoteSharedInboxes maps an inbox URL to whether it is a shared inbox
	// (#1811). 未登録の URL は Shared=false 扱い。
	RemoteSharedInboxes map[string]bool
	// RemoteInboxHosts maps an inbox URL to the host of the followers using it,
	// for ListRemoteFollowerInboxHosts. 未登録の URL は inbox URL のホスト名を使う。
	RemoteInboxHosts map[string][]string
	// Birthdays maps followeeID -> "YYYY-MM-DD" string used by
	// ListFollowingByBirthday. 未登録のユーザーは誕生日なしとして扱う。
	Birthdays map[string]string
	// LastHostListViewer is the viewer passed to the last
	// ListFollowersByHostCursor / ListFollowingByHostCursor call (nil if none).
	LastHostListViewer *model.FollowListViewer
}

MockFollowingRepository is a test double for repository.FollowingRepository.

func NewMockFollowingRepository

func NewMockFollowingRepository() *MockFollowingRepository

func (*MockFollowingRepository) CountRemoteFollowees

func (m *MockFollowingRepository) CountRemoteFollowees() (int64, error)

func (*MockFollowingRepository) CountRemoteFollowers

func (m *MockFollowingRepository) CountRemoteFollowers() (int64, error)

func (*MockFollowingRepository) Create

func (*MockFollowingRepository) Delete

func (*MockFollowingRepository) DeleteAllByUser

func (m *MockFollowingRepository) DeleteAllByUser(userID string) (int64, error)

ListRemoteFollowerInboxes returns the inbox URLs registered for the given followee. テストでは MockFollowingRepository.RemoteInboxes を直接埋めて使う。

func (*MockFollowingRepository) Exists

func (m *MockFollowingRepository) Exists(followerID, followeeID string) (bool, error)

func (*MockFollowingRepository) FilterFollowingsFromAnchor

func (m *MockFollowingRepository) FilterFollowingsFromAnchor(anchorID string, candidateIDs []string) ([]string, error)

func (*MockFollowingRepository) FilterFollowingsToAnchor

func (m *MockFollowingRepository) FilterFollowingsToAnchor(anchorID string, candidateIDs []string) ([]string, error)

func (*MockFollowingRepository) FindByPair

func (m *MockFollowingRepository) FindByPair(followerID, followeeID string) (*model.Following, error)

func (*MockFollowingRepository) FollowsAnyOnHost

func (m *MockFollowingRepository) FollowsAnyOnHost(followerID, host string) (bool, error)

FollowsAnyOnHost mirrors repository.followingRepository.FollowsAnyOnHost.

func (*MockFollowingRepository) ListFolloweeIDs

func (m *MockFollowingRepository) ListFolloweeIDs(followerID string) ([]string, error)

ListFolloweeIDs returns every followee id without pagination.

func (*MockFollowingRepository) ListFollowers

func (m *MockFollowingRepository) ListFollowers(userID string, limit, offset int) ([]*model.Following, error)

func (*MockFollowingRepository) ListFollowersBefore

func (m *MockFollowingRepository) ListFollowersBefore(userID, cursor string, limit int) ([]*model.Following, error)

func (*MockFollowingRepository) ListFollowersByHost

func (m *MockFollowingRepository) ListFollowersByHost(host string, limit, offset int) ([]*model.Following, error)

ListFollowersByHost mirrors production: federation/followers filters by followeeHost (本家 followers.ts と同じ列)。

func (*MockFollowingRepository) ListFollowersByHostCursor

func (m *MockFollowingRepository) ListFollowersByHostCursor(host, sinceID, untilID string, limit int, viewer model.FollowListViewer) ([]*model.Following, error)

ListFollowersByHostCursor records viewer in LastHostListViewer and returns the host's rows. The owner visibility filter is not emulated (the mock has no profiles); it is covered by the repository's real-DB tests.

func (*MockFollowingRepository) ListFollowersToNotify

func (m *MockFollowingRepository) ListFollowersToNotify(userID string) ([]*model.Following, error)

ListFollowersToNotify mirrors the production repo: followeeId match + notify='normal'.

func (*MockFollowingRepository) ListFollowersWithCursor

func (m *MockFollowingRepository) ListFollowersWithCursor(followeeID, sinceID, untilID string, limit, offset int) ([]*model.Following, error)

ListFollowersWithCursor mirrors the production repository: followeeId match, sinceId/untilId in the query, paginationOrder.

**本番と揃える。** 揃っていないと、カーソルを SQL に渡さない実装 (#2711) を テストが見逃す。実際、旧 mock は**ソートせず挿入順**だったので本番より軽い 症状しか再現しなかった。

func (*MockFollowingRepository) ListFollowing

func (m *MockFollowingRepository) ListFollowing(userID string, limit, offset int) ([]*model.Following, error)

func (*MockFollowingRepository) ListFollowingBefore

func (m *MockFollowingRepository) ListFollowingBefore(userID, cursor string, limit int) ([]*model.Following, error)

func (*MockFollowingRepository) ListFollowingByBirthday

func (m *MockFollowingRepository) ListFollowingByBirthday(followerID string, beginMMDD, endMMDD, limit, offset int) ([]model.FollowingBirthday, error)

func (*MockFollowingRepository) ListFollowingByHost

func (m *MockFollowingRepository) ListFollowingByHost(host string, limit, offset int) ([]*model.Following, error)

ListFollowingByHost mirrors production: federation/following filters by followerHost (本家 following.ts と同じ列)。

func (*MockFollowingRepository) ListFollowingByHostCursor

func (m *MockFollowingRepository) ListFollowingByHostCursor(host, sinceID, untilID string, limit int, viewer model.FollowListViewer) ([]*model.Following, error)

ListFollowingByHostCursor records viewer in LastHostListViewer and returns the host's rows (see ListFollowersByHostCursor).

func (*MockFollowingRepository) ListFollowingForList

func (m *MockFollowingRepository) ListFollowingForList(followerID, sinceID, untilID string, notification bool, limit int) ([]*model.Following, error)

ListFollowingForList mirrors repository.followingRepository.ListFollowingForList (cursor + notification filter for /api/following/list)。

func (*MockFollowingRepository) ListFollowingWithCursor

func (m *MockFollowingRepository) ListFollowingWithCursor(followerID, sinceID, untilID string, limit, offset int) ([]*model.Following, error)

ListFollowingWithCursor is ListFollowersWithCursor for the follower side.

func (*MockFollowingRepository) ListHomeTimelineFollowers

func (m *MockFollowingRepository) ListHomeTimelineFollowers(followeeID string, limit, offset int) ([]*model.Following, error)

ListHomeTimelineFollowers mirrors the production repository: local and non-hibernated followers only, ORDER BY id DESC, then LIMIT/OFFSET.

func (*MockFollowingRepository) ListLocalFollowerIDs

func (m *MockFollowingRepository) ListLocalFollowerIDs(followeeID string) ([]string, error)

ListLocalFollowerIDs mirrors repository.followingRepository.ListLocalFollowerIDs (followeeId 一致かつ followerHost IS NULL の followerId を全件)。 実装同様 followerId 昇順で返し、caller が順序に依存できるようにする。

func (*MockFollowingRepository) ListLocalFollowerIDsLimit

func (m *MockFollowingRepository) ListLocalFollowerIDsLimit(followeeID string, limit int) ([]string, error)

ListLocalFollowerIDsLimit mirrors repository.followingRepository.ListLocalFollowerIDsLimit.

func (*MockFollowingRepository) ListRemoteFollowerInboxHosts

func (m *MockFollowingRepository) ListRemoteFollowerInboxHosts(userID string) ([]model.RemoteInboxHost, error)

func (*MockFollowingRepository) ListRemoteFollowerInboxes

func (m *MockFollowingRepository) ListRemoteFollowerInboxes(userID string) ([]model.RemoteInbox, error)

func (*MockFollowingRepository) UpdateAllByFollower

func (m *MockFollowingRepository) UpdateAllByFollower(followerID string, fields map[string]any) error

func (*MockFollowingRepository) UpdateRelation

func (m *MockFollowingRepository) UpdateRelation(followerID, followeeID string, fields map[string]any) error

type MockGalleryRepository

type MockGalleryRepository struct {
	Posts map[string]*model.GalleryPost
	Likes map[string][]*model.GalleryLike // keyed by userID
	// LikedBy holds "<userID>:<postID>" pairs reported by ExistsLike.
	LikedBy map[string]bool
	Err     error
}

MockGalleryRepository is a test double for repository.GalleryRepository.

func NewMockGalleryRepository

func NewMockGalleryRepository() *MockGalleryRepository

NewMockGalleryRepository creates an empty MockGalleryRepository.

func (*MockGalleryRepository) ExistsLike

func (m *MockGalleryRepository) ExistsLike(userID, postID string) (bool, error)

func (*MockGalleryRepository) FindPostsByIDs

func (m *MockGalleryRepository) FindPostsByIDs(ids []string) ([]*model.GalleryPost, error)

func (*MockGalleryRepository) ListByUser

func (m *MockGalleryRepository) ListByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.GalleryPost, error)

func (*MockGalleryRepository) ListLikesByUser

func (m *MockGalleryRepository) ListLikesByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.GalleryLike, error)

type MockInstanceRepository

type MockInstanceRepository struct {
	Instances map[string]*model.Instance // keyed by host
	CreateErr error
	UpdateErr error
	// FindByHostErr injects an arbitrary error from FindByHost regardless of
	// the in-memory map state. Used to exercise non-NotFound DB error paths
	// (#915 review: Service must surface raw err for observability).
	FindByHostErr error
	// ListPeerHostsErr injects a DB error from ListPeerHosts so the
	// /api/v1/instance/peers handler の 500 経路を試験できる (#2245)。
	ListPeerHostsErr error
	// FindCalls counts FindByHost invocations so tests can assert caching
	// behaviour in callers (e.g. instance.ShouldSkipDelivery, #1407). Not
	// goroutine-safe; tests asserting on it must drive the service serially.
	FindCalls int
	// UpdateCalls counts UpdateFields invocations so tests can assert that
	// instance health bookkeeping skips redundant writes (#1429: TS-aligned
	// state-transition guard / CollapsedQueue throttling). Not goroutine-safe.
	UpdateCalls int
}

MockInstanceRepository is a test double for repository.InstanceRepository.

func NewMockInstanceRepository

func NewMockInstanceRepository() *MockInstanceRepository

NewMockInstanceRepository creates an empty MockInstanceRepository.

func (*MockInstanceRepository) Create

func (*MockInstanceRepository) FindByHost

func (m *MockInstanceRepository) FindByHost(host string) (*model.Instance, error)

func (*MockInstanceRepository) FindManyByHosts

func (m *MockInstanceRepository) FindManyByHosts(hosts []string) ([]*model.Instance, error)

func (*MockInstanceRepository) IncrementCount

func (m *MockInstanceRepository) IncrementCount(host, column string, delta int) error

func (*MockInstanceRepository) IncrementFollowersCount

func (m *MockInstanceRepository) IncrementFollowersCount(host string, delta int) error

IncrementFollowersCount adjusts followersCount on an existing instance row。 host 不在 / delta=0 は no-op (real repo と同じ semantics)。

func (*MockInstanceRepository) IncrementFollowingCount

func (m *MockInstanceRepository) IncrementFollowingCount(host string, delta int) error

IncrementFollowingCount adjusts followingCount on an existing instance row。

func (*MockInstanceRepository) List

func (*MockInstanceRepository) ListForRefresh

func (m *MockInstanceRepository) ListForRefresh(staleBefore time.Time, limit int) ([]*model.Instance, error)

ListForRefresh returns live instances whose metadata is stale (#393).

func (*MockInstanceRepository) ListPeerHosts

func (m *MockInstanceRepository) ListPeerHosts() ([]string, error)

List returns all stored instances filtered by the most common predicates. 並び順は host 昇順 (テストの安定性のため)。 ListPeerHosts mirrors the real repository: non-suspended hosts, ASC。 production の DB column default は 'none' だが Go 構造体の zero value は "" なので両方 live 扱いにする (ListForRefresh と同じ扱い)。

func (*MockInstanceRepository) RecomputeFollowCounts

func (m *MockInstanceRepository) RecomputeFollowCounts() error

RecomputeFollowCounts is a no-op stub for tests; the mock has no `following` rows to aggregate from, and tests that exercise the pie-chart endpoint can seed Instance.FollowersCount / FollowingCount directly.

func (*MockInstanceRepository) UpdateFields

func (m *MockInstanceRepository) UpdateFields(host string, fields map[string]any) error

func (*MockInstanceRepository) UpdateFieldsIf

func (m *MockInstanceRepository) UpdateFieldsIf(host string, cond model.InstanceUpdateCondition, fields map[string]any) (bool, error)

UpdateFieldsIf applies fields only while the stored instance satisfies cond (#3731). It counts as an update call.

type MockMetaRepository

type MockMetaRepository struct {
	Meta       *model.Meta
	FetchCalls int
	// LastUpdateFields is the field map handed to the most recent Update.
	// 実 repo は key をそのまま列識別子として UPDATE に載せるので、
	// 「何が渡ったか」自体が検査対象になる。
	LastUpdateFields map[string]any
	// FetchErr forces Fetch to fail. 「DB が読めない窓」を再現するために使う
	// (判定できないときに fail-open していないかを見るテスト)。
	FetchErr error
	// CheckedMeta, when set, is the row UpdateChecked hands to check instead of
	// Meta. 実 repo の「transaction の中で読んだ行」がキャッシュ (Fetch) と
	// 食い違う場面を再現する。
	CheckedMeta *model.Meta
	// UpdateCheckedCalls counts UpdateChecked calls.
	UpdateCheckedCalls int
	// contains filtered or unexported fields
}

MockMetaRepository is a test double for repository.MetaRepository.

FetchCalls tracks how many times Fetch has been invoked. Tests asserting perf invariants (例: "Create が meta を 1 度しか fetch しない") can read this counter directly.

**Fetch と Update は mutex で守る。** 競合を再現する test (承認制の同時登録、 #2580) は同じ handler を複数 goroutine から叩くので、素の counter だと -race が本題と無関係な場所で落ちる。counter の直接読み出しは呼び出し元の goroutine 内で完結する前提のまま (逐次 test で使う)。

func NewMockMetaRepository

func NewMockMetaRepository() *MockMetaRepository

func (*MockMetaRepository) EnsureInitial

func (m *MockMetaRepository) EnsureInitial(id string) error

func (*MockMetaRepository) Fetch

func (m *MockMetaRepository) Fetch() (*model.Meta, error)

func (*MockMetaRepository) Update

func (m *MockMetaRepository) Update(fields map[string]any) error

func (*MockMetaRepository) UpdateChecked

func (m *MockMetaRepository) UpdateChecked(fields map[string]any, check func(current *model.Meta) error) error

UpdateChecked mimics repository.CheckedMetaUpdater: check sees the current row (CheckedMeta, else Meta) and nothing is written when it fails.

type MockModerationLogRepository

type MockModerationLogRepository struct {
	Logs []*model.ModerationLog
	// CreateCalls counts how many times Create was invoked. Combined with
	// CreateManyCalls it lets bulk-handler tests assert that LogMany
	// (batched goroutine + single multi-row INSERT, #671) is exercised
	// instead of fanning out per-item Create calls.
	CreateCalls     int
	CreateManyCalls int
	// contains filtered or unexported fields
}

MockModerationLogRepository is a thread-safe in-memory test double for repository.ModerationLogRepository. Goroutine-safety is required because core/moderationlog.Service.Log writes via a fire-and-forget goroutine, so test assertions in the calling goroutine race with the writer.

func NewMockModerationLogRepository

func NewMockModerationLogRepository() *MockModerationLogRepository

func (*MockModerationLogRepository) CallCounts

func (m *MockModerationLogRepository) CallCounts() (create, createMany int)

CallCounts returns the (Create, CreateMany) call counts taken under the repo's lock. Use from tests that need a consistent snapshot of both.

func (*MockModerationLogRepository) Create

func (*MockModerationLogRepository) CreateMany

func (m *MockModerationLogRepository) CreateMany(logs []*model.ModerationLog) error

CreateMany appends a batch of logs in a single critical section. Mirrors repository.ModerationLogRepository.CreateMany so test doubles can verify LogMany batch behaviour (#671).

func (*MockModerationLogRepository) List

func (*MockModerationLogRepository) Snapshot

Snapshot returns a thread-safe copy of the recorded logs for assertions. Use this instead of reading the Logs field directly when log writes happen on a background goroutine.

type MockMutingRepository

type MockMutingRepository struct {
	Mutings map[string]*model.Muting
}

MockMutingRepository is a test double for repository.MutingRepository.

func NewMockMutingRepository

func NewMockMutingRepository() *MockMutingRepository

func (*MockMutingRepository) Create

func (m *MockMutingRepository) Create(rec *model.Muting) error

func (*MockMutingRepository) Delete

func (m *MockMutingRepository) Delete(rec *model.Muting) error

func (*MockMutingRepository) DeleteExpired

func (m *MockMutingRepository) DeleteExpired(now time.Time) ([]string, error)

DeleteExpired removes muting rows whose ExpiresAt has passed. Returns the muterId of every removed row (one entry per row, so duplicates are possible), matching repository.MutingRepository.

map の走査順は不定なので、返る順序は保証しない。呼び出し側は集合として扱うこと (実装も重複排除してから publish する)。

func (*MockMutingRepository) Exists

func (m *MockMutingRepository) Exists(muterID, muteeID string) (bool, error)

func (*MockMutingRepository) FindByPair

func (m *MockMutingRepository) FindByPair(muterID, muteeID string) (*model.Muting, error)

func (*MockMutingRepository) ListAllMuteeIDs

func (m *MockMutingRepository) ListAllMuteeIDs(muterID string) ([]string, error)

ListAllMuteeIDs returns every muteeId for muterID (expiry filter なし)。

func (*MockMutingRepository) ListByMutee

func (m *MockMutingRepository) ListByMutee(muteeID string) ([]*model.Muting, error)

ListByMutee returns the active (non-expired) mute rows whose muteeId matches (= who mutes this user)。id 昇順で返し、caller が順序に依存できるようにする。

func (*MockMutingRepository) ListByMuter

func (m *MockMutingRepository) ListByMuter(muterID, sinceID, untilID string, limit, offset int) ([]*model.Muting, error)

func (*MockMutingRepository) ListMuteeIDs

func (m *MockMutingRepository) ListMuteeIDs(muterID string) ([]string, error)

ListMuteeIDs returns muteeIDs for muterID where the mute is active (= ExpiresAt nil or in future). production の挙動と同じ filter logic で timeline test の user mute 経路を担保する (#874)。

type MockNoteFavoriteRepository

type MockNoteFavoriteRepository struct {
	Favorites map[string]*model.NoteFavorite // keyed by "userId:noteId"
}

MockNoteFavoriteRepository is a test double for repository.NoteFavoriteRepository.

func NewMockNoteFavoriteRepository

func NewMockNoteFavoriteRepository() *MockNoteFavoriteRepository

func (*MockNoteFavoriteRepository) Create

func (*MockNoteFavoriteRepository) Delete

func (m *MockNoteFavoriteRepository) Delete(userID, noteID string) error

func (*MockNoteFavoriteRepository) Exists

func (m *MockNoteFavoriteRepository) Exists(userID, noteID string) (bool, error)

func (*MockNoteFavoriteRepository) ListByUser

func (m *MockNoteFavoriteRepository) ListByUser(userID, untilID, sinceID string, limit int) ([]*model.NoteFavorite, error)

type MockNoteReactionRepository

type MockNoteReactionRepository struct {
	Reactions map[string]*model.NoteReaction // keyed by id
	CreateErr error                          // optional error to return on Create
	// Following は ListByUserID の visibility filter (followers note の follow
	// 判定) に使う followerID -> followeeIDs map。未設定なら follow なし扱い
	// (= 非 follower viewer)。testutil は repository を import すると repository
	// 内部テストとの循環になるため、core/note.CanSeeNote は使わず inline で
	// 可視性を再現する (条件は CanSeeNote と一致させる)。
	Following map[string][]string
}

MockNoteReactionRepository is a test double for repository.NoteReactionRepository.

func NewMockNoteReactionRepository

func NewMockNoteReactionRepository() *MockNoteReactionRepository

func (*MockNoteReactionRepository) Create

func (*MockNoteReactionRepository) Delete

func (*MockNoteReactionRepository) FindByPair

func (m *MockNoteReactionRepository) FindByPair(userID, noteID string) (*model.NoteReaction, error)

func (*MockNoteReactionRepository) FindByUserAndNoteIDs

func (m *MockNoteReactionRepository) FindByUserAndNoteIDs(userID string, noteIDs []string) (map[string]*model.NoteReaction, error)

func (*MockNoteReactionRepository) ListByNoteID

func (m *MockNoteReactionRepository) ListByNoteID(noteID, untilID, sinceID string, limit int, reactions []string) ([]*model.NoteReaction, error)

func (*MockNoteReactionRepository) ListByUserID

func (m *MockNoteReactionRepository) ListByUserID(userID, viewerID, untilID, sinceID string, limit int) ([]*model.NoteReaction, error)

ListByUserID returns reactions made by a user. paginationOrder と同じく sinceID 単独指定時のみ ASC、それ以外 DESC (ListByNoteID と同 logic)。

func (*MockNoteReactionRepository) ListReactionPairs

func (m *MockNoteReactionRepository) ListReactionPairs(noteID string, limit int) ([]string, error)

ListReactionPairs returns up to `limit` "<userId>/<reaction>" pairs for a note, oldest (smallest id) first, mirroring the production repo (#2067)。

type MockNoteRepository

type MockNoteRepository struct {
	Notes          map[string]*model.Note
	ReactionCounts map[string]map[string]int // noteID -> reaction -> count
	// ExistingOnPrimaryErr, when set, is returned by ExistingNoteIDsOnPrimary
	// so callers can exercise the fail-safe path (#2719).
	ExistingOnPrimaryErr error
	// ListRenoteOrReplyErr, when set, is returned by
	// ListRenoteOrReplyRemoteUserIDs so callers can exercise the lookup
	// failure path (#2995).
	ListRenoteOrReplyErr error
	// FindByURIErr forces FindByURI to fail with a non-not-found error, for
	// exercising the paths that must retry instead of acking (#3115).
	FindByURIErr error
	// FindErr forces FindByID (and the wrappers that delegate to it) to fail
	// with a non-not-found error, for exercising the paths that must retry
	// instead of acking (#3121).
	FindErr error
	// Following は ListByUserIDFiltered の visibility push-down (followers note
	// の follow 判定) に使う followerID -> followeeIDs map。未設定なら follow
	// なし扱い (= 非 follower viewer)。testutil は core/note を import すると
	// repository 内部テストとの循環になるため CanSeeNote は使わず inline で
	// 可視性を再現する (条件は CanSeeNote / real repo SQL と一致させる)。
	Following map[string][]string
	// UserListMembers は ListByUserList の member-filter + reply gate (#1495 /
	// #1496) を mock 側で再現するための listID -> memberships。テストは
	// noteRepo.UserListMembers[listID] = []*model.UserListMembership{...} の
	// shape で直接 seed する。空 / nil の listID は member 不在として空結果。
	UserListMembers map[string][]*model.UserListMembership
	// UpdateFieldsCalls は UpdateFields に渡された field map を順に記録する。
	//
	// **in-memory の値を見るだけでは「fields への載せ忘れ」を検出できない** —
	// 呼び出し側が持つ `*model.Note` は `Notes[id]` と同じ pointer なので、
	// `existing.X = v` だけしても mock 上は反映されて見える。実 DB では
	// `fields` に載っていない列は UPDATE 文に出ないので、**呼び出し側から見えて
	// いる値と DB の値が食い違う** (#2729)。
	//
	// 同じ理由で、**`UpdateFields` の switch に列を足すときは慎重に。** 足すと
	// 「`fields` に載せた」と「呼び出し側が in-memory を書き換えた」を
	// 区別できなくなる。実際 `case "url"` を足すと、呼び出し側の
	// `existing.URL = &u` を消す変異がどのテストにも掛からなくなる
	// (`fields["url"]` 側を消す変異はこの記録が捕まえるので落ちる)。
	UpdateFieldsCalls []map[string]any
}

MockNoteRepository is a test double for repository.NoteRepository.

func NewMockNoteRepository

func NewMockNoteRepository() *MockNoteRepository

func (*MockNoteRepository) CountLocalComments

func (m *MockNoteRepository) CountLocalComments() (int64, error)

CountLocalComments counts local notes that are replies.

func (*MockNoteRepository) CountLocalNotes

func (m *MockNoteRepository) CountLocalNotes() (int64, error)

CountLocalNotes counts notes whose author is local (UserHost nil).

func (*MockNoteRepository) CountReplyTargets

func (m *MockNoteRepository) CountReplyTargets(userID, viewerID string, limit int) ([]model.ReplyTargetCount, error)

func (*MockNoteRepository) Create

func (m *MockNoteRepository) Create(note *model.Note) error

Create inserts a note, enforcing the production partial UNIQUE index on `note.uri` (migration/000057_note_uri_unique_index).

**制約を模さないと「同じ URI を二重に取り込む」形の欠陥がテストを素通りする。** 実際 #2686 は、inbox 直送でピン留め投稿を取り込むと同じ note を二度作りに行き、 外側の Create が UNIQUE に当たって created=false になる (= 通知が落ちる) という ものだったが、素の map 書き込みでは 2 行できるだけで誰も気付けなかった。

全パッケージで壊れるテストは無いことを確認済み。

func (*MockNoteRepository) CreateWithTx

func (m *MockNoteRepository) CreateWithTx(note *model.Note, _ *gorm.DB) error

CreateWithTx mirrors Create for callers whose production insert shares a transaction with a user-row lock.

func (*MockNoteRepository) Delete

func (m *MockNoteRepository) Delete(note *model.Note) error

func (*MockNoteRepository) DeleteByUserBatch

func (m *MockNoteRepository) DeleteByUserBatch(userID string, batchSize int) (int64, error)

func (*MockNoteRepository) DeleteExpiredRemoteNotes

func (m *MockNoteRepository) DeleteExpiredRemoteNotes(_, _ int) (int64, error)

func (*MockNoteRepository) DeleteExpiredRemoteNotesAfter

func (m *MockNoteRepository) DeleteExpiredRemoteNotesAfter(_, _ int, _ string) (int64, int, string, error)

func (*MockNoteRepository) ExistingNoteIDsOnPrimary

func (m *MockNoteRepository) ExistingNoteIDsOnPrimary(ids []string) ([]string, error)

ExistingNoteIDsOnPrimary implements repository.NoteRepository (#2719).

mock は単一ストアなのでレプリカ遅延を模さない。production は primary に 固定した SELECT で、ここでは Notes に有るかどうかをそのまま返す。

func (*MockNoteRepository) FindByID

func (m *MockNoteRepository) FindByID(id string) (*model.Note, error)

func (*MockNoteRepository) FindByIDWithRelations

func (m *MockNoteRepository) FindByIDWithRelations(id string) (*model.Note, error)

FindByIDWithRelations mirrors the production hydrateNoteRelations behavior: shallow-copy the stored note and embed Renote / Reply targets from the map when their IDs are set (#425)。コピーに書き込むので、同じ note を FindByID で取り直した時に relation が連鎖的に残らない。

func (*MockNoteRepository) FindByIDWithRelationsOnPrimary

func (m *MockNoteRepository) FindByIDWithRelationsOnPrimary(id string) (*model.Note, error)

func (*MockNoteRepository) FindByIDWithUser

func (m *MockNoteRepository) FindByIDWithUser(id string) (*model.Note, error)

FindByIDWithUser returns the stored note as-is (User pointer that the caller set is preserved). Renote / Reply の embed は行わず、軽量経路 (#425) として visibility / userId 参照だけが必要な caller 用。

func (*MockNoteRepository) FindByIDWithUserOnPrimary

func (m *MockNoteRepository) FindByIDWithUserOnPrimary(id string) (*model.Note, error)

func (*MockNoteRepository) FindByURI

func (m *MockNoteRepository) FindByURI(uri string) (*model.Note, error)

func (*MockNoteRepository) FindManyByIDsWithUser

func (m *MockNoteRepository) FindManyByIDsWithUser(ids []string) ([]*model.Note, error)

func (*MockNoteRepository) FindManyByIDsWithUserOnPrimary

func (m *MockNoteRepository) FindManyByIDsWithUserOnPrimary(ids []string) ([]*model.Note, error)

func (*MockNoteRepository) FindManyLocalReferenceMetadataByIDs

func (m *MockNoteRepository) FindManyLocalReferenceMetadataByIDs(ids []string) ([]*model.Note, error)

func (*MockNoteRepository) IncrementCount

func (m *MockNoteRepository) IncrementCount(noteID, column string, delta int) error

IncrementCount mutates the in-memory note's counter column for tests.

func (*MockNoteRepository) IncrementReaction

func (m *MockNoteRepository) IncrementReaction(noteID, reaction string, delta int) error

IncrementReaction adjusts an in-memory reaction count map. テスト用に Reactions を JSON Map にデコードして加算する。

func (*MockNoteRepository) IncrementUserNotesCount

func (m *MockNoteRepository) IncrementUserNotesCount(_ string, _ int) error

func (*MockNoteRepository) ListByChannelID

func (m *MockNoteRepository) ListByChannelID(channelID, viewerID, untilID, sinceID string, limit int) ([]*model.Note, error)

ListByChannelID mirrors the real repo's visibility push-down for channels/timeline (#1440). viewerID="" は匿名 (public/home のみ)。

func (*MockNoteRepository) ListByFileID

func (m *MockNoteRepository) ListByFileID(_, _, _ string, _ int) ([]*model.Note, error)

func (*MockNoteRepository) ListByUserID

func (m *MockNoteRepository) ListByUserID(userID string, untilID, sinceID string, limit int) ([]*model.Note, error)

func (*MockNoteRepository) ListByUserIDFiltered

func (m *MockNoteRepository) ListByUserIDFiltered(userID, viewerID, untilID, sinceID string, limit int, withFiles, withReplies, withRenotes, withChannelNotes bool) ([]*model.Note, error)

ListByUserIDFiltered は ListByUserID に upstream `users/notes` 互換の filter 引数を適用した版。production GORM impl と同 logic で predicate に 詰めて listFiltered に委譲する (#1021)。bool 4 引数は repository interface の signature に整合 (= struct を介さない理由は testutil ↔ repository の import cycle 回避)。

func (*MockNoteRepository) ListByUserList

func (m *MockNoteRepository) ListByUserList(listID string, limit int, sinceID, untilID string, filter model.TimelineDBFilter) ([]*model.Note, error)

ListByUserList mirrors the real repository's SQL push-down for user-list timeline (#1452 visibility / #1496 withReplies / #1498 renote / WithFiles). Caller seeds UserListMembers[listID] = []*model.UserListMembership{...}.

旧 stub は (nil, nil) を返していて real SQL との parity drift があり、 handler-layer 以外で visibility / withReplies / withRenotes / withFiles の regression を mock 経由で検出できなかった (#1491 audit 指摘 1)。本実装で real repo と同 semantics を再現する。

適用順:

  1. listID member でない author の note は除外
  2. channel note は除外
  3. visibility push-down: public/home は常時、followers は author 本人か viewer が follow 済みのときのみ、specified は list timeline に出さない (DM 非表示, ListByUserList の real SQL も同じ)
  4. reply gate (#1496): replyId IS NULL || replyUserId==note.userId (self-thread) || replyUserId==viewerID || membership.WithReplies
  5. sinceID / untilID cursor
  6. WithFiles (= ファイル添付必須) / WithRenotes nil=true (false なら pure renote 除外) / IncludeMyRenotes・IncludeRenotedMyNotes・IncludeLocalRenotes (いずれも nil=true、false で対応する pure renote 分岐を除外) を applyTimelineFilter と同じ条件で適用
  7. paginationOrder: sinceID only → ASC, otherwise DESC

未実装 (= parity 対象外): MutedChannelIDs / muting subquery (UseMutingSubquery / MutedUserIDs)。user-list-timeline では real repo もこれらを積まない方針 なので mock も省略する。これらを使う test は専用 fake (userListNotesRepo 系) で受けること。

muting subquery 系 filter が渡された場合は panic で loud-fail させる (#1506)。 docstring の案内だけでは将来の test 著者が読まずに mock 経由で書く可能性が あり、その場合 real SQL では mute されるはずの note が mock で素通りする silent regression を引き起こす。stacktrace から専用 fake への escalation を 即座に促すために panic を選択している。

func (*MockNoteRepository) ListChildrenOf

func (m *MockNoteRepository) ListChildrenOf(noteID, viewerID, untilID, sinceID string, limit int) ([]*model.Note, error)

ListChildrenOf returns notes that reply to or quote the given noteID. upstream notes/children (children.ts:53-67) に合わせ、renote 側は本文・ファイル・ 投票のいずれかを持つ引用 renote のみ child として返す。pure renote (Text==nil かつ FileIDs 空かつ HasPoll==false) は除外する (#1554)。reply 側にはこのガードを掛けない。

func (*MockNoteRepository) ListFeatured

func (m *MockNoteRepository) ListFeatured(channelID, untilID string, limit, offset int) ([]*model.Note, error)

func (*MockNoteRepository) ListFeaturedByUser

func (m *MockNoteRepository) ListFeaturedByUser(userID, viewerID, untilID string, limit int) ([]*model.Note, error)

ListFeaturedByUser mirrors the real repository's 2-stage selection: engagement DESC で top-50 を選抜したあと、id DESC でページングする。 channel 投稿は除外する。real repo の SQL push-down と一致 (#1487 / #1491)。

func (*MockNoteRepository) ListGlobalTimeline

func (m *MockNoteRepository) ListGlobalTimeline(limit int, sinceID, untilID string, f model.TimelineDBFilter) ([]*model.Note, error)

func (*MockNoteRepository) ListHomeTimeline

func (m *MockNoteRepository) ListHomeTimeline(_ string, limit int, sinceID, untilID string, _ model.TimelineDBFilter) ([]*model.Note, error)

ListHomeTimeline / ListLocalTimeline / ListGlobalTimeline return public or home-visibility notes via the shared listFiltered helper. The mock does not reproduce the production timeline filter semantics (follows / userHost / muted channels / etc.); only the pagination cursor and sinceID ASC flip match production behaviour.

func (*MockNoteRepository) ListLocalByChannelID

func (m *MockNoteRepository) ListLocalByChannelID(channelID, viewerID, untilID, sinceID string, limit int) ([]*model.Note, error)

ListLocalByChannelID is ListByChannelID limited to local authors (`userHost IS NULL`), mirroring the real repo.

func (*MockNoteRepository) ListLocalTimeline

func (m *MockNoteRepository) ListLocalTimeline(limit int, sinceID, untilID string, _ model.TimelineDBFilter) ([]*model.Note, error)

func (*MockNoteRepository) ListMentions

func (m *MockNoteRepository) ListMentions(userID, visibility string, following bool, limit int, sinceID, untilID string, ascending bool) ([]*model.Note, error)

ListMentions accepts the `following` flag for signature parity but does not filter on it: the mock has no following graph, so the followee restriction is exercised by the real-DB repository test instead (#1554)。

func (*MockNoteRepository) ListPublicByUserID

func (m *MockNoteRepository) ListPublicByUserID(userID string, untilID, sinceID string, limit int) ([]*model.Note, error)

func (*MockNoteRepository) ListPublicNotes

func (m *MockNoteRepository) ListPublicNotes(filter model.PublicNotesFilter, limit int, sinceID, untilID string) ([]*model.Note, error)

func (*MockNoteRepository) ListPublicNotesForFeed

func (m *MockNoteRepository) ListPublicNotesForFeed(userID string, limit int) ([]*model.Note, error)

ListPublicNotesForFeed mirrors the repository query: renote を除いた public / home のノートを新しい順に返す。

func (*MockNoteRepository) ListRenoteOrReplyRemoteUserIDs

func (m *MockNoteRepository) ListRenoteOrReplyRemoteUserIDs(noteID string) ([]string, error)

ListRenoteOrReplyRemoteUserIDs returns the distinct ids of remote users who renoted or replied to noteID (#2995)。`note.userHost` が非 NULL の行だけを見る のは本物の SQL と同じ。

func (*MockNoteRepository) ListRenotesByUser

func (m *MockNoteRepository) ListRenotesByUser(userID, renoteID string) ([]*model.Note, error)

func (*MockNoteRepository) ListRenotesOf

func (m *MockNoteRepository) ListRenotesOf(noteID, viewerID, untilID, sinceID string, limit int) ([]*model.Note, error)

ListRenotesOf returns notes whose renoteId equals noteID.

func (*MockNoteRepository) ListRepliesOf

func (m *MockNoteRepository) ListRepliesOf(noteID, viewerID, untilID, sinceID string, limit int) ([]*model.Note, error)

ListRepliesOf returns notes whose replyId equals noteID.

func (*MockNoteRepository) SearchByFilter

func (m *MockNoteRepository) SearchByFilter(f model.NoteSearchFilter) ([]*model.Note, error)

SearchByFilter returns public/home notes matching the filter (lower() + LIKE + optional userId / channelId / host)。`Host == "."` はローカル限定。

func (*MockNoteRepository) SearchByTag

func (m *MockNoteRepository) SearchByTag(tagGroups [][]string, viewerID string, limit int, sinceID, untilID string, filter model.NoteSearchTagFilter) ([]*model.Note, error)

func (*MockNoteRepository) Update

func (m *MockNoteRepository) Update(note *model.Note, column string, value any) error

func (*MockNoteRepository) UpdateFields

func (m *MockNoteRepository) UpdateFields(noteID string, fields map[string]any) error

UpdateFields applies field updates to the in-memory note. テストで参照される 列だけを反映する; 拡張時はここに追記する。

type MockNoteThreadMutingRepository

type MockNoteThreadMutingRepository struct {
	Mutings map[string]*model.NoteThreadMuting // keyed by "userId:threadId"
}

MockNoteThreadMutingRepository is a test double for repository.NoteThreadMutingRepository.

func NewMockNoteThreadMutingRepository

func NewMockNoteThreadMutingRepository() *MockNoteThreadMutingRepository

func (*MockNoteThreadMutingRepository) Create

func (*MockNoteThreadMutingRepository) Delete

func (m *MockNoteThreadMutingRepository) Delete(userID, threadID string) error

func (*MockNoteThreadMutingRepository) Exists

func (m *MockNoteThreadMutingRepository) Exists(userID, threadID string) (bool, error)

func (*MockNoteThreadMutingRepository) ListMutedThreadIDs

func (m *MockNoteThreadMutingRepository) ListMutedThreadIDs(userID string) ([]string, error)

type MockNoteUnreadRepository

type MockNoteUnreadRepository struct {
	Rows []*model.NoteUnread
}

MockNoteUnreadRepository is a test double for repository.NoteUnreadRepository.

func NewMockNoteUnreadRepository

func NewMockNoteUnreadRepository() *MockNoteUnreadRepository

NewMockNoteUnreadRepository returns an empty repository.

func (*MockNoteUnreadRepository) DeleteAllByUser

func (m *MockNoteUnreadRepository) DeleteAllByUser(userID string) error

DeleteAllByUser removes every row owned by userID.

func (*MockNoteUnreadRepository) DeleteByUserNote

func (m *MockNoteUnreadRepository) DeleteByUserNote(userID, noteID string) error

DeleteByUserNote removes the row matching (userID, noteID), if any.

func (*MockNoteUnreadRepository) HasAnyMentioned

func (m *MockNoteUnreadRepository) HasAnyMentioned(userID string) (bool, error)

HasAnyMentioned returns whether any mentioned-flagged row exists for user.

func (*MockNoteUnreadRepository) HasAnySpecified

func (m *MockNoteUnreadRepository) HasAnySpecified(userID string) (bool, error)

HasAnySpecified returns whether any specified-flagged row exists for user.

func (*MockNoteUnreadRepository) Upsert

Upsert records an unread row. Flags are OR-merged on conflict to mirror the real repository's behaviour.

type MockPageLikeRepository

type MockPageLikeRepository struct {
	Likes map[string]*model.PageLike
}

MockPageLikeRepository is a test double for repository.PageLikeRepository.

func NewMockPageLikeRepository

func NewMockPageLikeRepository() *MockPageLikeRepository

NewMockPageLikeRepository creates an empty MockPageLikeRepository.

func (*MockPageLikeRepository) Create

func (*MockPageLikeRepository) Delete

func (*MockPageLikeRepository) Exists

func (m *MockPageLikeRepository) Exists(userID, pageID string) (bool, error)

func (*MockPageLikeRepository) FindByPair

func (m *MockPageLikeRepository) FindByPair(userID, pageID string) (*model.PageLike, error)

func (*MockPageLikeRepository) ListByUser

func (m *MockPageLikeRepository) ListByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.PageLike, error)

func (*MockPageLikeRepository) ListLikedPageIDs

func (m *MockPageLikeRepository) ListLikedPageIDs(userID string, pageIDs []string) ([]string, error)

ListLikedPageIDs returns the subset of pageIDs liked by userID.

type MockPageRepository

type MockPageRepository struct {
	Pages     map[string]*model.Page
	CreateErr error
	UpdateErr error
	// UpdateFieldsCalls は UpdateFields に渡された field map を順に記録する。
	// jsonb 列へ `[]byte` を渡していないか等、**値の型そのもの**を検査する用。
	UpdateFieldsCalls []map[string]any
}

MockPageRepository is a test double for repository.PageRepository.

func NewMockPageRepository

func NewMockPageRepository() *MockPageRepository

NewMockPageRepository creates an empty MockPageRepository.

func (*MockPageRepository) Create

func (m *MockPageRepository) Create(p *model.Page) error

func (*MockPageRepository) Delete

func (m *MockPageRepository) Delete(p *model.Page) error

func (*MockPageRepository) FindByID

func (m *MockPageRepository) FindByID(id string) (*model.Page, error)

func (*MockPageRepository) FindByUserAndName

func (m *MockPageRepository) FindByUserAndName(userID, name string) (*model.Page, error)

func (*MockPageRepository) FindManyByIDs

func (m *MockPageRepository) FindManyByIDs(ids []string) ([]*model.Page, error)

func (*MockPageRepository) IncrementCount

func (m *MockPageRepository) IncrementCount(pageID, column string, delta int) error

func (*MockPageRepository) ListByUser

func (m *MockPageRepository) ListByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.Page, error)

func (*MockPageRepository) ListFeatured

func (m *MockPageRepository) ListFeatured(sinceID, untilID string, limit, offset int) ([]*model.Page, error)

func (*MockPageRepository) ListPublicByUser

func (m *MockPageRepository) ListPublicByUser(userID, sinceID, untilID string, limit, offset int) ([]*model.Page, error)

func (*MockPageRepository) UpdateFields

func (m *MockPageRepository) UpdateFields(pageID string, fields map[string]any) error

type MockPasswordResetRequestRepository

type MockPasswordResetRequestRepository struct {
	Requests map[string]*model.PasswordResetRequest // keyed by ID
}

MockPasswordResetRequestRepository is a test double for repository.PasswordResetRequestRepository.

func NewMockPasswordResetRequestRepository

func NewMockPasswordResetRequestRepository() *MockPasswordResetRequestRepository

func (*MockPasswordResetRequestRepository) Create

func (*MockPasswordResetRequestRepository) Delete

func (*MockPasswordResetRequestRepository) FindByToken

type MockPollRepository

type MockPollRepository struct {
	Polls map[string]*model.Poll
	// FindErr, when non-nil, is returned by FindByNoteID. not-found ではない
	// 障害を ack していないことを試すために要る (#3116)。
	FindErr error
}

MockPollRepository is a test double for repository.PollRepository.

func NewMockPollRepository

func NewMockPollRepository() *MockPollRepository

func (*MockPollRepository) Create

func (m *MockPollRepository) Create(poll *model.Poll) error

func (*MockPollRepository) FindByNoteID

func (m *MockPollRepository) FindByNoteID(noteID string) (*model.Poll, error)

func (*MockPollRepository) IncrementVote

func (m *MockPollRepository) IncrementVote(noteID string, choice int, delta int) error

func (*MockPollRepository) ListExpiredUnnotified

func (m *MockPollRepository) ListExpiredUnnotified(now time.Time, limit int) ([]*model.Poll, error)

ListExpiredUnnotified mirrors the live repo: returns polls with expiresAt before `now` and notifiedAt == nil. ordering by expiresAt ASC for deterministic testing.

func (*MockPollRepository) ListRecommendation

func (m *MockPollRepository) ListRecommendation(viewerID string, mutedUserIDs []string, excludeChannels bool, limit, offset int) ([]string, error)

ListRecommendation mirrors the live query in-memory: local public unexpired polls not authored by / voted by the viewer, author not muted; when excludeChannels is true all channel polls are dropped; ordered by noteId DESC; limit/offset applied.

func (*MockPollRepository) MarkNotified

func (m *MockPollRepository) MarkNotified(noteID string, t time.Time) error

MarkNotified stamps notifiedAt on the in-memory poll. unknown noteID is a no-op (matches GORM's UPDATE WHERE behaviour for non-matching rows).

func (*MockPollRepository) UpdateVotes

func (m *MockPollRepository) UpdateVotes(noteID string, votes []int64) error

UpdateVotes overwrites the poll's votes array (#1779)。

type MockPollVoteRepository

type MockPollVoteRepository struct {
	Votes map[string]*model.PollVote // keyed by id
}

MockPollVoteRepository is a test double for repository.PollVoteRepository.

func NewMockPollVoteRepository

func NewMockPollVoteRepository() *MockPollVoteRepository

func (*MockPollVoteRepository) CountByUserAndNote

func (m *MockPollVoteRepository) CountByUserAndNote(userID, noteID string) (int64, error)

func (*MockPollVoteRepository) Create

func (*MockPollVoteRepository) CreateIfNotVoted

func (m *MockPollVoteRepository) CreateIfNotVoted(v *model.PollVote, single bool) (bool, error)

CreateIfNotVoted mirrors the live repo's duplicate check (not its locking).

func (*MockPollVoteRepository) FindByUserAndChoice

func (m *MockPollVoteRepository) FindByUserAndChoice(userID, noteID string, choice int) (*model.PollVote, error)

func (*MockPollVoteRepository) FindByUserAndNoteIDs

func (m *MockPollVoteRepository) FindByUserAndNoteIDs(userID string, noteIDs []string) (map[string][]int, error)

FindByUserAndNoteIDs mirrors the live repo: groups choices by noteID for the given user across the requested noteIDs. Empty noteIDs returns empty map.

func (*MockPollVoteRepository) ListByNoteID

func (m *MockPollVoteRepository) ListByNoteID(noteID string) ([]*model.PollVote, error)

type MockRegistrationTicketRepository

type MockRegistrationTicketRepository struct {
	Tickets   map[string]*model.RegistrationTicket
	CreateErr error
}

MockRegistrationTicketRepository is a test double for repository.RegistrationTicketRepository.

func NewMockRegistrationTicketRepository

func NewMockRegistrationTicketRepository() *MockRegistrationTicketRepository

NewMockRegistrationTicketRepository creates an empty mock.

func (*MockRegistrationTicketRepository) ClaimForSignup

func (m *MockRegistrationTicketRepository) ClaimForSignup(ticketID string, emailRequired bool) (bool, error)

ClaimForSignup mirrors the real conditional UPDATE in memory.

func (*MockRegistrationTicketRepository) CountByCreatorSince

func (m *MockRegistrationTicketRepository) CountByCreatorSince(creatorID, sinceID string) (int64, error)

func (*MockRegistrationTicketRepository) Create

func (*MockRegistrationTicketRepository) Delete

func (*MockRegistrationTicketRepository) FindByCode

func (*MockRegistrationTicketRepository) FindByID

func (*MockRegistrationTicketRepository) FindByIDForUpdateTx

func (m *MockRegistrationTicketRepository) FindByIDForUpdateTx(_ *gorm.DB, id string) (*model.RegistrationTicket, error)

FindByIDForUpdateTx は real repo の SELECT FOR UPDATE 相当だが、Mock は in-memory で直列実行されるためロック相当はノーオプ。tx 引数も使わない。

func (*MockRegistrationTicketRepository) List

func (m *MockRegistrationTicketRepository) List(filter string, limit, offset int, now time.Time) ([]*model.RegistrationTicket, error)

func (*MockRegistrationTicketRepository) ListByCreator

func (m *MockRegistrationTicketRepository) ListByCreator(creatorID, sinceID, untilID string, limit int) ([]*model.RegistrationTicket, error)

func (*MockRegistrationTicketRepository) ListSorted

func (m *MockRegistrationTicketRepository) ListSorted(filter, sort string, limit, offset int, now time.Time) ([]*model.RegistrationTicket, error)

ListSorted filters like List and applies the upstream sort enum (#1545).

func (*MockRegistrationTicketRepository) MarkPending

func (m *MockRegistrationTicketRepository) MarkPending(ticketID, pendingID string) error

MarkPending sets usedAt + pendingUserId (not usedById)。email 確認待ち ticket の予約 (#2083)。

func (*MockRegistrationTicketRepository) MarkUsed

func (m *MockRegistrationTicketRepository) MarkUsed(ticketID, userID string) error

func (*MockRegistrationTicketRepository) MarkUsedTx

func (m *MockRegistrationTicketRepository) MarkUsedTx(_ *gorm.DB, ticketID, userID string) error

func (*MockRegistrationTicketRepository) ReleaseClaim

func (m *MockRegistrationTicketRepository) ReleaseClaim(ticketID string) error

ReleaseClaim mirrors the real conditional UPDATE in memory.

type MockRegistryRepository

type MockRegistryRepository struct {
	Items map[string]*model.RegistryItem // keyed by "userId:key:scope"
}

MockRegistryRepository is a test double for repository.RegistryRepository.

func NewMockRegistryRepository

func NewMockRegistryRepository() *MockRegistryRepository

func (*MockRegistryRepository) Get

func (m *MockRegistryRepository) Get(userID, key string, scope []string, _ *string) (*model.RegistryItem, error)

func (*MockRegistryRepository) GetAll

func (m *MockRegistryRepository) GetAll(userID string, scope []string, _ *string) ([]*model.RegistryItem, error)

func (*MockRegistryRepository) KeysWithType

func (m *MockRegistryRepository) KeysWithType(userID string, scope []string, domain *string) (map[string]string, error)

func (*MockRegistryRepository) Remove

func (m *MockRegistryRepository) Remove(userID, key string, scope []string, _ *string) error

func (*MockRegistryRepository) ScopesWithDomain

func (m *MockRegistryRepository) ScopesWithDomain(userID string) ([]model.RegistryScopeDomain, error)

func (*MockRegistryRepository) Set

type MockRelayRepository

type MockRelayRepository struct {
	Relays map[string]*model.Relay
}

MockRelayRepository is a test double for repository.RelayRepository.

func NewMockRelayRepository

func NewMockRelayRepository() *MockRelayRepository

func (*MockRelayRepository) Create

func (m *MockRelayRepository) Create(r *model.Relay) error

func (*MockRelayRepository) Delete

func (m *MockRelayRepository) Delete(id string) error

func (*MockRelayRepository) FindByID

func (m *MockRelayRepository) FindByID(id string) (*model.Relay, error)

func (*MockRelayRepository) List

func (m *MockRelayRepository) List() ([]*model.Relay, error)

func (*MockRelayRepository) ListByStatus

func (m *MockRelayRepository) ListByStatus(status string) ([]*model.Relay, error)

func (*MockRelayRepository) UpdateStatusFrom

func (m *MockRelayRepository) UpdateStatusFrom(id, from, to string) (bool, error)

UpdateStatusFrom sets the status to `to` only when it is currently `from`.

type MockRenoteMutingRepository

type MockRenoteMutingRepository struct {
	Mutings map[string]*model.RenoteMuting
}

MockRenoteMutingRepository is a test double for repository.RenoteMutingRepository.

func NewMockRenoteMutingRepository

func NewMockRenoteMutingRepository() *MockRenoteMutingRepository

func (*MockRenoteMutingRepository) Create

func (*MockRenoteMutingRepository) Delete

func (*MockRenoteMutingRepository) Exists

func (m *MockRenoteMutingRepository) Exists(muterID, muteeID string) (bool, error)

func (*MockRenoteMutingRepository) FindByPair

func (m *MockRenoteMutingRepository) FindByPair(muterID, muteeID string) (*model.RenoteMuting, error)

func (*MockRenoteMutingRepository) ListByMuter

func (m *MockRenoteMutingRepository) ListByMuter(muterID, sinceID, untilID string, limit, offset int) ([]*model.RenoteMuting, error)

func (*MockRenoteMutingRepository) ListMuteeIDs

func (m *MockRenoteMutingRepository) ListMuteeIDs(muterID string) ([]string, error)

ListMuteeIDs returns muteeIDs of all renote-mute rows for muterID. timeline endpoint で renote-mute された user の pure renote を除外する filter 用 (#903)。renote_muting には expiresAt が無いので active filter 不要。

type MockRetentionAggregationRepository

type MockRetentionAggregationRepository struct {
	Records []*model.RetentionAggregation
}

MockRetentionAggregationRepository is a test double for repository.RetentionAggregationRepository.

func NewMockRetentionAggregationRepository

func NewMockRetentionAggregationRepository() *MockRetentionAggregationRepository

func (*MockRetentionAggregationRepository) ListRecent

type MockRoleAssignmentRepository

type MockRoleAssignmentRepository struct {
	Assignments map[string]*model.RoleAssignment // keyed by "userId:roleId"
	RoleRepo    *MockRoleRepository
	// UserRepo はテストで紐付けると ListByRole が User を Preload 風に
	// セットするので、admin/roles/users の handler テストで User を直接
	// 参照するパスが組める。
	UserRepo *MockUserRepository
	// LastListByRoleLimit は最後に ListByRole に渡された limit を保持する。
	// handler 側の limit clamping (>100 → 100) を直接 assert したいテスト用。
	LastListByRoleLimit int
}

MockRoleAssignmentRepository is a test double for repository.RoleAssignmentRepository.

func NewMockRoleAssignmentRepository

func NewMockRoleAssignmentRepository(roleRepo *MockRoleRepository) *MockRoleAssignmentRepository

func (*MockRoleAssignmentRepository) CountActiveByRole

func (m *MockRoleAssignmentRepository) CountActiveByRole(roleID string) (int, error)

func (*MockRoleAssignmentRepository) CountVisibleByRole

func (m *MockRoleAssignmentRepository) CountVisibleByRole(roleID string) (int, error)

CountVisibleByRole counts the assignments ListVisibleByRole returns.

func (*MockRoleAssignmentRepository) Create

func (*MockRoleAssignmentRepository) Delete

func (m *MockRoleAssignmentRepository) Delete(userID, roleID string) error

func (*MockRoleAssignmentRepository) DeleteExpired

func (m *MockRoleAssignmentRepository) DeleteExpired(now time.Time) (int64, error)

DeleteExpired removes assignments whose ExpiresAt has passed. Returns the number removed.

func (*MockRoleAssignmentRepository) Exists

func (m *MockRoleAssignmentRepository) Exists(userID, roleID string) (bool, error)

func (*MockRoleAssignmentRepository) FindActive

func (m *MockRoleAssignmentRepository) FindActive(userID, roleID string, at time.Time) (*model.RoleAssignment, error)

func (*MockRoleAssignmentRepository) ListByRole

func (m *MockRoleAssignmentRepository) ListByRole(roleID string, untilID, sinceID string, limit int) ([]*model.RoleAssignment, error)

func (*MockRoleAssignmentRepository) ListByUser

func (m *MockRoleAssignmentRepository) ListByUser(userID string) ([]*model.RoleAssignment, error)

func (*MockRoleAssignmentRepository) ListVisibleByRole

func (m *MockRoleAssignmentRepository) ListVisibleByRole(roleID string, untilID, sinceID string, limit int) ([]*model.RoleAssignment, error)

ListVisibleByRole mirrors the production visibleAssigneeCond: assignees known to UserRepo that are suspended or deleted local users are dropped.

type MockRoleRepository

type MockRoleRepository struct {
	Roles map[string]*model.Role
}

MockRoleRepository is a test double for repository.RoleRepository.

func NewMockRoleRepository

func NewMockRoleRepository() *MockRoleRepository

func (*MockRoleRepository) Create

func (m *MockRoleRepository) Create(role *model.Role) error

func (*MockRoleRepository) Delete

func (m *MockRoleRepository) Delete(id string) error

func (*MockRoleRepository) FindByID

func (m *MockRoleRepository) FindByID(id string) (*model.Role, error)

func (*MockRoleRepository) List

func (m *MockRoleRepository) List() ([]*model.Role, error)

func (*MockRoleRepository) ListByLastUsed

func (m *MockRoleRepository) ListByLastUsed() ([]*model.Role, error)

ListByLastUsed returns roles sorted by lastUsedAt DESC (id ASC tie-break), mirroring the production query for admin/roles/list (#2061)。

func (*MockRoleRepository) UpdateFields

func (m *MockRoleRepository) UpdateFields(id string, fields map[string]any) error

type MockSigninRepository

type MockSigninRepository struct {
	Signins []*model.Signin
	// contains filtered or unexported fields
}

MockSigninRepository is a test double for repository.SigninRepository.

func NewMockSigninRepository

func NewMockSigninRepository() *MockSigninRepository

func (*MockSigninRepository) Create

func (m *MockSigninRepository) Create(s *model.Signin) error

func (*MockSigninRepository) Len

func (m *MockSigninRepository) Len() int

Len returns the number of signin records (thread-safe).

func (*MockSigninRepository) ListByUserID

func (m *MockSigninRepository) ListByUserID(userID string, limit int, untilID, sinceID string) ([]*model.Signin, error)

type MockSystemAccountRepository

type MockSystemAccountRepository struct {
	Accounts map[string]*model.SystemAccount // keyed by type
}

MockSystemAccountRepository is a test double for repository.SystemAccountRepository.

func NewMockSystemAccountRepository

func NewMockSystemAccountRepository() *MockSystemAccountRepository

func (*MockSystemAccountRepository) Create

func (*MockSystemAccountRepository) FindByType

type MockSystemWebhookRepository

type MockSystemWebhookRepository struct {
	Webhooks  map[string]*model.SystemWebhook
	CreateErr error
	UpdateErr error
}

MockSystemWebhookRepository is a test double for repository.SystemWebhookRepository.

func NewMockSystemWebhookRepository

func NewMockSystemWebhookRepository() *MockSystemWebhookRepository

NewMockSystemWebhookRepository creates an empty mock.

func (*MockSystemWebhookRepository) Create

func (*MockSystemWebhookRepository) Delete

func (*MockSystemWebhookRepository) FindByID

func (*MockSystemWebhookRepository) List

func (*MockSystemWebhookRepository) ListActive

func (m *MockSystemWebhookRepository) ListActive() ([]*model.SystemWebhook, error)

func (*MockSystemWebhookRepository) Update

func (*MockSystemWebhookRepository) UpdateAdminFields

func (m *MockSystemWebhookRepository) UpdateAdminFields(id string, fields map[string]any) error

func (*MockSystemWebhookRepository) UpdateLatestStatus

func (m *MockSystemWebhookRepository) UpdateLatestStatus(id string, sentAt time.Time, status int) error

type MockUsedUsernameRepository

type MockUsedUsernameRepository struct {
	Usernames map[string]bool
}

MockUsedUsernameRepository is a test double for repository.UsedUsernameRepository.

func NewMockUsedUsernameRepository

func NewMockUsedUsernameRepository() *MockUsedUsernameRepository

func (*MockUsedUsernameRepository) Create

func (m *MockUsedUsernameRepository) Create(username string) error

func (*MockUsedUsernameRepository) Exists

func (m *MockUsedUsernameRepository) Exists(username string) (bool, error)

type MockUserKeypairExtraRepository

type MockUserKeypairExtraRepository struct {
	// contains filtered or unexported fields
}

MockUserKeypairExtraRepository is a test double for repository.UserKeypairExtraRepository.

`keypairs` map は concurrent backfill (= TestUser_LazyBackfill_RaceSafe のような 8 goroutine 並列で InsertIfAbsent + FindByUserID を呼ぶシナリオ) で race detector に検出されるため、全 method を mu で保護する (#1091)。 field を unexport にして外部からの直接 read を実装で塞ぎ、必ず `Get(userID)` 経由で読み出させる。

func NewMockUserKeypairExtraRepository

func NewMockUserKeypairExtraRepository() *MockUserKeypairExtraRepository

func (*MockUserKeypairExtraRepository) Delete

func (m *MockUserKeypairExtraRepository) Delete(userID string) error

func (*MockUserKeypairExtraRepository) FindByUserID

func (*MockUserKeypairExtraRepository) Get

Get は test assertion 用の helper。production interface の FindByUserID は error 返却で "not found vs DB error" を区別するが、test では存在の有無 だけ確認したいケースが多いため `(value, ok)` 形式で expose する。内部 map は unexport なので、外部からの read は必ず本 helper を通る。

func (*MockUserKeypairExtraRepository) InsertIfAbsent

InsertIfAbsent inserts only when no entry exists for the userId. Returns (inserted, nil) where inserted=true if a new row was inserted, false if a row already existed (= ON CONFLICT DO NOTHING semantic of the production repository).

func (*MockUserKeypairExtraRepository) Upsert

type MockUserKeypairRepository

type MockUserKeypairRepository struct {
	Keypairs map[string]*model.UserKeypair // keyed by userID
}

MockUserKeypairRepository is a test double for repository.UserKeypairRepository.

func NewMockUserKeypairRepository

func NewMockUserKeypairRepository() *MockUserKeypairRepository

func (*MockUserKeypairRepository) Create

func (*MockUserKeypairRepository) FindByUserID

func (m *MockUserKeypairRepository) FindByUserID(userID string) (*model.UserKeypair, error)

func (*MockUserKeypairRepository) NormalizePrivateKeysToPKCS8

func (m *MockUserKeypairRepository) NormalizePrivateKeysToPKCS8() (int, error)

NormalizePrivateKeysToPKCS8 は mock では no-op (#2378)。

type MockUserListFavoriteRepository

type MockUserListFavoriteRepository struct {
	Favorites map[string]*model.UserListFavorite // keyed by "userId:userListId"
}

MockUserListFavoriteRepository is a test double for repository.UserListFavoriteRepository.

func NewMockUserListFavoriteRepository

func NewMockUserListFavoriteRepository() *MockUserListFavoriteRepository

func (*MockUserListFavoriteRepository) CountByList

func (m *MockUserListFavoriteRepository) CountByList(listID string) (int64, error)

func (*MockUserListFavoriteRepository) Create

func (*MockUserListFavoriteRepository) Delete

func (m *MockUserListFavoriteRepository) Delete(userID, listID string) error

func (*MockUserListFavoriteRepository) Exists

func (m *MockUserListFavoriteRepository) Exists(userID, listID string) (bool, error)

func (*MockUserListFavoriteRepository) ListByUser

type MockUserListRepository

type MockUserListRepository struct {
	Lists   map[string]*model.UserList
	Members []*model.UserListMembership
}

func NewMockUserListRepository

func NewMockUserListRepository() *MockUserListRepository

func (*MockUserListRepository) AddMember

func (*MockUserListRepository) CountByUser

func (m *MockUserListRepository) CountByUser(userID string) (int64, error)

func (*MockUserListRepository) CountMembers

func (m *MockUserListRepository) CountMembers(listID string) (int64, error)

func (*MockUserListRepository) Create

func (m *MockUserListRepository) Create(list *model.UserList) error

func (*MockUserListRepository) Delete

func (m *MockUserListRepository) Delete(id string) error

func (*MockUserListRepository) FindByID

func (m *MockUserListRepository) FindByID(id string) (*model.UserList, error)

func (*MockUserListRepository) ListByUser

func (m *MockUserListRepository) ListByUser(userID string) ([]*model.UserList, error)

func (*MockUserListRepository) ListIDsAndOwnersByMember

func (m *MockUserListRepository) ListIDsAndOwnersByMember(memberID string) (map[string]string, error)

ListIDsAndOwnersByMember returns {listID: ownerID} for lists containing memberID.

func (*MockUserListRepository) ListIDsByMember

func (m *MockUserListRepository) ListIDsByMember(userID string) ([]string, error)

func (*MockUserListRepository) ListMembers

func (m *MockUserListRepository) ListMembers(listID string) ([]*model.UserListMembership, error)

func (*MockUserListRepository) ListMembersByListIDs

func (m *MockUserListRepository) ListMembersByListIDs(listIDs []string) (map[string][]string, error)

ListMembersByListIDs returns userIDs grouped by listID. Mirrors the production batch fetch (#876) but iterates the in-memory slice.

func (*MockUserListRepository) ListMembershipsByUser

func (m *MockUserListRepository) ListMembershipsByUser(userID string) ([]*model.UserListMembership, error)

ListMembershipsByUser returns every membership row for the given member user across all lists (= which lists contain this user)。id 昇順で返す。

func (*MockUserListRepository) ListMembershipsPage

func (m *MockUserListRepository) ListMembershipsPage(listID, sinceID, untilID string, limit int) ([]*model.UserListMembership, error)

ListMembershipsPage mirrors the production cursor pagination (id ASC when sinceID-only, else DESC) over the in-memory Members slice.

func (*MockUserListRepository) ListsContainingMember

func (m *MockUserListRepository) ListsContainingMember(ownerID, memberUserID string) ([]*model.UserList, error)

func (*MockUserListRepository) RemoveMember

func (m *MockUserListRepository) RemoveMember(listID, userID string) error

func (*MockUserListRepository) UpdateList

func (m *MockUserListRepository) UpdateList(id string, fields map[string]any) error

func (*MockUserListRepository) UpdateMembership

func (m *MockUserListRepository) UpdateMembership(listID, userID string, withReplies *bool) error

type MockUserMemoRepository

type MockUserMemoRepository struct {
	// keyed by "userID:targetUserID"
	Memos map[string]*model.UserMemo
}

MockUserMemoRepository is a test double for repository.UserMemoRepository.

func NewMockUserMemoRepository

func NewMockUserMemoRepository() *MockUserMemoRepository

NewMockUserMemoRepository creates an empty MockUserMemoRepository.

func (*MockUserMemoRepository) CreateOrUpdate

func (m *MockUserMemoRepository) CreateOrUpdate(memo *model.UserMemo) error

func (*MockUserMemoRepository) Delete

func (m *MockUserMemoRepository) Delete(userID, targetUserID string) error

func (*MockUserMemoRepository) FindByPair

func (m *MockUserMemoRepository) FindByPair(userID, targetUserID string) (*model.UserMemo, error)

type MockUserNotePiningRepository

type MockUserNotePiningRepository struct {
	Pinings map[string]*model.UserNotePining // keyed by ID
	// ReplaceErr forces ReplaceByUser to fail, for exercising the
	// best-effort paths that must not abort actor resolution.
	ReplaceErr error
	// CountErr forces CountByUser to fail, for exercising the paths that must
	// not silently skip the pin cap when the count is unavailable.
	CountErr error
	// FindErr forces FindByPair to fail with a non-not-found error, for
	// exercising the paths that must retry instead of acking (#3115).
	FindErr error
	// DeleteErr forces Delete to fail, for exercising the paths that must not
	// swallow the write failure after deciding to unpin (#3115).
	DeleteErr error
}

MockUserNotePiningRepository is a test double for repository.UserNotePiningRepository.

func NewMockUserNotePiningRepository

func NewMockUserNotePiningRepository() *MockUserNotePiningRepository

func (*MockUserNotePiningRepository) CountByUser

func (m *MockUserNotePiningRepository) CountByUser(userID string) (int, error)

func (*MockUserNotePiningRepository) Create

func (*MockUserNotePiningRepository) Delete

func (*MockUserNotePiningRepository) FindByPair

func (m *MockUserNotePiningRepository) FindByPair(userID, noteID string) (*model.UserNotePining, error)

func (*MockUserNotePiningRepository) ListByUser

func (m *MockUserNotePiningRepository) ListByUser(userID string) ([]*model.UserNotePining, error)

func (*MockUserNotePiningRepository) ListByUsers

func (m *MockUserNotePiningRepository) ListByUsers(userIDs []string) ([]*model.UserNotePining, error)

ListByUsers implements repository.UserNotePiningBatchReader.

func (*MockUserNotePiningRepository) ReplaceByUser

func (m *MockUserNotePiningRepository) ReplaceByUser(userID string, pins []*model.UserNotePining) error

type MockUserPendingRepository

type MockUserPendingRepository struct {
	Rows map[string]*model.UserPending // keyed by ID
}

MockUserPendingRepository is a test double for repository.UserPendingRepository.

func NewMockUserPendingRepository

func NewMockUserPendingRepository() *MockUserPendingRepository

NewMockUserPendingRepository creates an empty MockUserPendingRepository.

func (*MockUserPendingRepository) Create

func (*MockUserPendingRepository) Delete

func (m *MockUserPendingRepository) Delete(id string) error

func (*MockUserPendingRepository) DeleteOlderThan

func (m *MockUserPendingRepository) DeleteOlderThan(thresholdID string) (int64, error)

DeleteOlderThan removes rows whose id sorts before thresholdID.

**実データに合わせて件数を返す。** 常に 0 を返すと、掃除を検査するテストが 空虚になる (#3037)。

func (*MockUserPendingRepository) FindByCode

func (m *MockUserPendingRepository) FindByCode(code string) (*model.UserPending, error)

type MockUserPublickeyRepository

type MockUserPublickeyRepository struct {
	// keyed by userID
	Keys map[string]*model.UserPublickey
	// FindByKeyIDErr forces FindByKeyID to fail with a non-not-found error,
	// for exercising the paths that must retry instead of dropping (#3121).
	FindByKeyIDErr error
}

MockUserPublickeyRepository is a test double for federation.PublickeyStore.

func NewMockUserPublickeyRepository

func NewMockUserPublickeyRepository() *MockUserPublickeyRepository

NewMockUserPublickeyRepository creates an empty MockUserPublickeyRepository.

func (*MockUserPublickeyRepository) Delete

func (m *MockUserPublickeyRepository) Delete(userID string) error

Delete removes the public key for userID. interface 互換のため実装。

func (*MockUserPublickeyRepository) FindByKeyID

func (m *MockUserPublickeyRepository) FindByKeyID(keyID string) (*model.UserPublickey, error)

FindByKeyID mirrors repository.userPublickeyRepository.FindByKeyID。 LD-Signature verify は signature.creator (= keyId) で lookup するため、 userID baseの map を線形 search する (= mock なのでコスト OK)。

func (*MockUserPublickeyRepository) FindByUserID

func (m *MockUserPublickeyRepository) FindByUserID(userID string) (*model.UserPublickey, error)

func (*MockUserPublickeyRepository) Upsert

type MockUserRepository

type MockUserRepository struct {
	// CountLocalUsersErr forces CountLocalUsers to fail (fail-closed の枝用)。
	CountLocalUsersErr error
	// EmailInUseErr forces EmailVerifiedInUse to fail (fail-closed の枝用)。
	EmailInUseErr             error
	Users                     map[string]*model.User        // keyed by ID
	Tokens                    map[string]*model.User        // keyed by token
	Profiles                  map[string]*model.UserProfile // keyed by userID
	FindByUsernameLowerFn     func(username string, host *string) (*model.User, error)
	UpdatePasswordIfCurrentFn func(userID, currentHash, newHash string) (bool, error)
	RemoveBackupCodeFn        func(userID, code string) error
	// RecommendationFollowing maps viewerID -> list of followeeIDs to exclude
	// from ListUserRecommendations. Set by tests to emulate the "already
	// following" filter.
	RecommendationFollowing map[string][]string
	// UpdateProfileErr, when non-nil, is returned by UpdateProfile so tests
	// can exercise persistence-failure branches.
	UpdateProfileErr error
	// FindProfileErr, when non-nil, is returned by FindProfileByUserID so tests
	// can exercise lookup-failure branches. **行が無いケースとは別物** で、
	// 呼び出し側は ErrRecordNotFound と実エラーを区別することがある。
	FindProfileErr error
	// FindErr, when non-nil, is returned by FindByID. Same intent as
	// FindProfileErr: a DB failure must not be collapsed into not-found (#2792).
	FindErr error
	// FindByURIErr, when non-nil, is returned by FindByURI.
	//
	// **FindErr とは別にしてある。** 同じ関数が id と URI の 2 経路で利用者を
	// 引くとき、片方だけ guard する形 (#3025 が名指しした失敗形) は 1 つの
	// hook では書き分けられない。
	FindByURIErr error
	// FindByURIHook, when non-nil, decides FindByURI's error per call (#3116)。
	// 非 nil を返した回だけ失敗する。
	//
	// **1 つの経路に同じ lookup が複数あるときに要る。** inbox は入口で
	// 「凍結済み actor か」を同じ `FindByURI` で見るので、`FindByURIErr` を
	// 立てると**手前で落ちて目的の分岐に到達しない** — テストは通るが、
	// 見たかった箇所を一度も実行していない (実測)。呼び出し順で書き分ける。
	FindByURIHook func(uri string) error
	// FindManyByIDsErr, when non-nil, is returned by FindManyByIDs. 同上 —
	// 一括解決の失敗を「その利用者は居ない」に潰さないことを検査するために要る。
	FindManyByIDsErr error
	// UpdateProfileFn, when non-nil, replaces UpdateProfile entirely. Used to
	// assert on the fields a caller writes (e.g. 2FA backup codes must be
	// consumed with RemoveBackupCode, never written back as a snapshot).
	UpdateProfileFn func(userID string, fields map[string]any) error
}

MockUserRepository is a test double for repository.UserRepository.

func NewMockUserRepository

func NewMockUserRepository() *MockUserRepository

func (*MockUserRepository) CountLocalUsers

func (m *MockUserRepository) CountLocalUsers() (int64, error)

CountLocalUsers counts non-deleted local users in the mock store that no plugin manages, like the repository (#3881). The repository also leaves out the system accounts, which the mock does not know.

func (*MockUserRepository) CountLocalUsersActiveSince

func (m *MockUserRepository) CountLocalUsersActiveSince(since time.Time) (int64, error)

CountLocalUsersActiveSince counts local users with lastActiveDate >= since.

func (*MockUserRepository) CountLocalUsersForSetup

func (m *MockUserRepository) CountLocalUsersForSetup() (int64, error)

CountLocalUsersForSetup counts non-deleted local users that no plugin manages. The repository also leaves out the system accounts, which the mock does not know. CountLocalUsersErr も同じく効く。

func (*MockUserRepository) CountOnlineUsers

func (m *MockUserRepository) CountOnlineUsers() (int64, error)

func (*MockUserRepository) Create

func (m *MockUserRepository) Create(u *model.User) error

func (*MockUserRepository) CreateProfile

func (m *MockUserRepository) CreateProfile(profile *model.UserProfile) error

func (*MockUserRepository) DeleteOrphanRemoteUsers

func (m *MockUserRepository) DeleteOrphanRemoteUsers(_, _ int) (int64, error)

DeleteOrphanRemoteUsers implements repository.UserRepository (#2340). mock は関係を追跡しないので、常に 0 件削除として振る舞う。実挙動は internal/repository の統合テストで検証する。

func (*MockUserRepository) EmailVerifiedInUse

func (m *MockUserRepository) EmailVerifiedInUse(email string) (bool, error)

EmailVerifiedInUse reports whether a confirmed profile already uses email.

func (*MockUserRepository) FindByID

func (m *MockUserRepository) FindByID(id string) (*model.User, error)

func (*MockUserRepository) FindByToken

func (m *MockUserRepository) FindByToken(token string) (*model.User, error)

func (*MockUserRepository) FindByURI

func (m *MockUserRepository) FindByURI(uri string) (*model.User, error)

func (*MockUserRepository) FindByUsernameLower

func (m *MockUserRepository) FindByUsernameLower(username string, host *string) (*model.User, error)

func (*MockUserRepository) FindManyByIDs

func (m *MockUserRepository) FindManyByIDs(ids []string) ([]*model.User, error)

FindManyByIDs mirrors the production repo: missing rows are skipped silently. Order is unspecified (production does not guarantee it either).

func (*MockUserRepository) FindManyByUsernamesAndHost

func (m *MockUserRepository) FindManyByUsernamesAndHost(usernames []string, host *string) ([]*model.User, error)

FindManyByUsernamesAndHost mirrors the production repo: case-insensitive match on usernameLower, scoped to a single host (nil = local-only).

func (*MockUserRepository) FindProfileByEmail

func (m *MockUserRepository) FindProfileByEmail(email string) (*model.UserProfile, error)

func (*MockUserRepository) FindProfileByUserID

func (m *MockUserRepository) FindProfileByUserID(userID string) (*model.UserProfile, error)

func (*MockUserRepository) FindProfileByVerifyCode

func (m *MockUserRepository) FindProfileByVerifyCode(code string) (*model.UserProfile, error)

func (*MockUserRepository) FindProfilesByUserIDs

func (m *MockUserRepository) FindProfilesByUserIDs(userIDs []string) ([]*model.UserProfile, error)

FindProfilesByUserIDs mirrors the production repo. Missing profiles are skipped (matching the DB schema where profile rows are optional).

func (*MockUserRepository) HardDeleteUser

func (m *MockUserRepository) HardDeleteUser(userID string) error

func (*MockUserRepository) IncrementFollowersCount

func (m *MockUserRepository) IncrementFollowersCount(userID string, delta int) error

func (*MockUserRepository) IncrementFollowingCount

func (m *MockUserRepository) IncrementFollowingCount(userID string, delta int) error

func (*MockUserRepository) IncrementNotesCount

func (m *MockUserRepository) IncrementNotesCount(userID string, delta int) error

func (*MockUserRepository) ListLocalUserIDsActiveSince

func (m *MockUserRepository) ListLocalUserIDsActiveSince(since time.Time) ([]string, error)

ListLocalUserIDsActiveSince returns the IDs of stored local users whose LastActiveDate is at or after `since`. 削除済みユーザーは除外する (CountLocalUsersActiveSince および実装の repository 層と挙動を揃える)。

func (*MockUserRepository) ListLocalUserIDsRegisteredAfter

func (m *MockUserRepository) ListLocalUserIDsRegisteredAfter(idCursor string) ([]string, error)

ListLocalUserIDsRegisteredAfter returns the IDs of stored local users whose id is lexicographically greater than `idCursor`.

func (*MockUserRepository) ListRemoteInboxes

func (m *MockUserRepository) ListRemoteInboxes() ([]model.RemoteInbox, error)

ListRemoteInboxes returns dedup'd inbox URLs for every remote user in the mock store. sharedInbox を優先。

func (*MockUserRepository) ListUserRecommendations

func (m *MockUserRepository) ListUserRecommendations(viewerID string, activeSince time.Time, limit, offset int) ([]*model.User, error)

Followings はテスト側で MockUserRepository.Followings[viewerID] に followeeID のリストを入れておくと、ListUserRecommendations から除外される。

func (*MockUserRepository) ListUsers

func (m *MockUserRepository) ListUsers(filter model.UserListFilter) ([]*model.User, error)

func (*MockUserRepository) RemoveBackupCode

func (m *MockUserRepository) RemoveBackupCode(userID, code string) error

RemoveBackupCode mirrors the SQL `array_remove` semantics: it deletes the code from whatever is stored now, not from a caller-supplied snapshot.

func (*MockUserRepository) RevokeDeletedLocalCredentials

func (m *MockUserRepository) RevokeDeletedLocalCredentials(userID string) error

func (*MockUserRepository) SearchByUsernameAndHost

func (m *MockUserRepository) SearchByUsernameAndHost(query string, host *string, localOnly bool, limit int) ([]*model.User, error)

SearchByUsernameAndHost narrows the prefix match with a 3-state host filter (#766 / #1054 / #1064 contract):

  • localOnly=true → u.Host == nil のみ
  • localOnly=false, host=nil → host filter なし (= local + remote 両方)
  • localOnly=false, host=ptr → u.Host が *host の prefix match (case-insensitive)

upstream `lower("host") LIKE lower(?) || '%'` を string prefix で模倣する。

なお mock は production 側の SQL LIKE wildcard escape (#1054 / #1061 で `%` / `_` / `\` を literal 化する `escapeSQLLikePattern`) を**実装しない**。 wildcard escape semantics は repository 側 testcontainer test (`TestUserRepository_SearchByUsernameAndHost_LikeWildcardEscape`) で 検証する分担にしている。mock を使う上位 (service / handler) test では wildcard を含む host を渡さないこと。

func (*MockUserRepository) SearchUsers

func (m *MockUserRepository) SearchUsers(query, meID string, limit, offset int, origin string) ([]*model.User, error)

SearchUsers mirrors the production SearchUsers contract closely enough for handler/service tests: display-name partial OR username (prefix for an @handle, partial for a username-shaped query) OR description fallback, excluding suspended users and honouring the origin filter. activeThreshold / muting / updatedAt sort are NOT modelled (covered by the real-DB repository test, #1939).

func (*MockUserRepository) SetAccountCreatedAtIfNull

func (m *MockUserRepository) SetAccountCreatedAtIfNull(userID string, createdAt time.Time) (bool, error)

SetAccountCreatedAtIfNull stores createdAt only while the column is nil.

func (*MockUserRepository) UpdatePasswordIfCurrent

func (m *MockUserRepository) UpdatePasswordIfCurrent(userID, currentHash, newHash string) (bool, error)

func (*MockUserRepository) UpdateProfile

func (m *MockUserRepository) UpdateProfile(userID string, fields map[string]any) error

func (*MockUserRepository) UpdateUser

func (m *MockUserRepository) UpdateUser(userID string, fields map[string]any) error

func (*MockUserRepository) WakeFromHibernation

func (m *MockUserRepository) WakeFromHibernation(userID string) (bool, error)

WakeFromHibernation clears IsHibernated of a hibernated user. The mock keeps no following rows, so only the user flag changes.

type TestDB

type TestDB struct {
	Container testcontainers.Container
	DB        *gorm.DB
}

TestDB holds a test PostgreSQL container and GORM connection.

func SetupPostgres

func SetupPostgres(ctx context.Context) (*TestDB, error)

SetupPostgres starts a PostgreSQL container and returns a GORM connection. The migration SQL is automatically applied.

func (*TestDB) Teardown

func (t *TestDB) Teardown(ctx context.Context)

Teardown stops the container.

func (*TestDB) TruncateAll

func (t *TestDB) TruncateAll()

TruncateAll truncates all data tables for test isolation.

type TestRedis

type TestRedis struct {
	Container testcontainers.Container
	Client    *redis.Client
	Addr      string
}

TestRedis holds a test Redis container and client.

func SetupRedis

func SetupRedis(ctx context.Context) (*TestRedis, error)

SetupRedis starts a Redis container and returns a client.

func (*TestRedis) FlushAll

func (t *TestRedis) FlushAll(ctx context.Context)

FlushAll clears all Redis data.

func (*TestRedis) Host

func (t *TestRedis) Host() string

Host returns the Redis host.

func (*TestRedis) Port

func (t *TestRedis) Port() int

Port returns the Redis port.

func (*TestRedis) Teardown

func (t *TestRedis) Teardown(ctx context.Context)

Teardown stops the container.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL