title: Reset cached Title objects between tests

Why:

- Title has several in-memory caches for Titles constructed via
  newFromText() and for the canonical mainpage instance that
  isMainPage() compares against.
- These caches are not reset between tests, which can cause cryptic
  integration test failures. It's not safe to persist either of these
  caches across tests, as neither the internal state of Title objects nor
  the identity of the canonical mainpage is valid across tests.

What:

- Clear the cached main page instance in Title::clearCaches().
- Call Title::clearCaches() from MediaWikiIntegrationTestCase::resetNonServiceCaches().

Bug: T395214
Depends-On: Ic35b45015ff5a53f6e728b69b59cc57efe0b390b
Change-Id: Ie6cac7e1282f794277dfc8ff3673f12e9969818c
(cherry picked from commit 3f7905bc9ff9006831f8573b7fe948dc7243107e)
This commit is contained in:
Máté Szabó 2025-05-26 17:02:47 +02:00 committed by Reedy
parent 81ef984c90
commit 7d44a728b6
2 changed files with 14 additions and 4 deletions

View file

@ -82,6 +82,12 @@ class Title implements Stringable, LinkTarget, PageIdentity {
/** @var MapCacheLRU|null */
private static $titleCache = null;
/**
* Cached instance of the main page title, to speed up isMainPage() checks.
* @var Title|null
*/
private static ?Title $cachedMainPage = null;
/**
* Title::newFromText maintains a cache to avoid expensive re-normalization of
* commonly used titles. On a batch operation this can become a memory leak
@ -1383,10 +1389,8 @@ class Title implements Stringable, LinkTarget, PageIdentity {
* @return bool
*/
public function isMainPage() {
/** @var Title|null */
static $cachedMainPage;
$cachedMainPage ??= self::newMainPage();
return $this->equals( $cachedMainPage );
self::$cachedMainPage ??= self::newMainPage();
return $this->equals( self::$cachedMainPage );
}
/**
@ -2693,6 +2697,9 @@ class Title implements Stringable, LinkTarget, PageIdentity {
$linkCache = MediaWikiServices::getInstance()->getLinkCache();
$linkCache->clear();
// Reset cached main page instance (T395214).
self::$cachedMainPage = null;
$titleCache = self::getTitleCache();
$titleCache->clear();
}

View file

@ -541,6 +541,9 @@ abstract class MediaWikiIntegrationTestCase extends PHPUnit\Framework\TestCase {
MediaWiki\Session\SessionManager::resetCache();
TestUserRegistry::clear();
// Invalidate any Title objects cached by newFromText() or isMainPage() (T395214).
Title::clearCaches();
}
/**