Skip to content

A platform for community discussion. Free, open, simple.

DEV: Plug memory leaks in the QUnit test page (#44799)

Jarek Radoszf5f3df17df69
diff --git a/frontend/discourse/app/lib/category-tag-search.js b/frontend/discourse/app/lib/category-tag-search.js
index 27ac07c21bd..70ed863772d 100644
--- a/frontend/discourse/app/lib/category-tag-search.js
+++ b/frontend/discourse/app/lib/category-tag-search.js
@@ -13,6 +13,12 @@ let cache = {};
let cacheTime;
let oldSearch;
+export function resetCategoryTagSearchCache() {
+ cache = {};
+ cacheTime = null;
+ oldSearch = null;
+}
+
function updateCache(term, results) {
cache[term] = results;
cacheTime = new Date();
diff --git a/frontend/discourse/app/models/category.js b/frontend/discourse/app/models/category.js
index 7a4124e3c11..c614983d398 100644
--- a/frontend/discourse/app/models/category.js
+++ b/frontend/discourse/app/models/category.js
@@ -1002,4 +1002,5 @@ const categoryMultiCache = new MultiCache(async (ids) => {
export function resetCategoryCache() {
categoryMultiCache.reset();
+ _uncategorized = undefined;
}
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index f0881f5df1a..b43e692a04b 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -45,6 +45,7 @@ import { resetDragAdoptionForTesting } from "discourse/lib/-internals/drag-and-d
import { resetAdminPluginConfigNav } from "discourse/lib/admin-plugin-config-nav";
import { clearPluginHeaderActionComponents } from "discourse/lib/admin-plugin-header-actions";
import { resetAdditionalReportModes } from "discourse/lib/admin-report-additional-modes";
+import { resetCategoryTagSearchCache } from "discourse/lib/category-tag-search";
import { rollbackAllPrepends } from "discourse/lib/class-prepend";
import { _clearRegisteredActions } from "discourse/lib/composer/actions-registry";
import { clearPopupMenuOptions } from "discourse/lib/composer/custom-popup-menu-options";
@@ -90,6 +91,7 @@ import {
setTestPresence,
} from "discourse/lib/user-presence";
import { resetUserSearchCache } from "discourse/lib/user-search";
+import { destroyUserStatuses } from "discourse/lib/user-status-on-autocomplete";
import { resetComposerCustomizations } from "discourse/models/composer";
import { clearAuthMethods } from "discourse/models/login-method";
import { clearNavItems } from "discourse/models/nav-item";
@@ -236,6 +238,8 @@ export function testCleanup(container, app) {
resetInlineOneboxCache();
resetCustomPostMessageCallbacks();
resetUserSearchCache();
+ resetCategoryTagSearchCache();
+ destroyUserStatuses();
resetHighestReadCache();
resetCardClickListenerSelector();
resetComposerCustomizations();
diff --git a/frontend/discourse/tests/setup-tests.js b/frontend/discourse/tests/setup-tests.js
index 81f50b0ae8f..e9f36396021 100644
--- a/frontend/discourse/tests/setup-tests.js
+++ b/frontend/discourse/tests/setup-tests.js
@@ -5,6 +5,7 @@ import "./loader-shims.js";
import "discourse/static/markdown-it";
/* eslint-enable simple-import-sort/imports */
+import { ASYNC_OBSERVERS, SYNC_OBSERVERS } from "@ember/-internals/metal";
import { getOwner } from "@ember/owner";
import { run } from "@ember/runloop";
import {
@@ -16,6 +17,8 @@ import {
} from "@ember/test-helpers";
import $ from "jquery";
import "message-bus-client";
+// Captures `setTimeout` when evaluated, so it must load before a test can fake timers
+import "pikaday";
import * as FakerModule from "@faker-js/faker";
import QUnit from "qunit";
import sinon from "sinon";
@@ -26,6 +29,7 @@ import { setLoadedFaker } from "discourse/lib/load-faker";
import PreloadStore from "discourse/lib/preload-store";
import { loadSprites } from "discourse/lib/svg-sprite-loader";
import { resetSettings as resetThemeSettings } from "discourse/lib/theme-settings-store";
+import { WebauthnAbortHandler } from "discourse/lib/webauthn";
import { resetCategoryCache } from "discourse/models/category";
import Session from "discourse/models/session";
import User from "discourse/models/user";
@@ -246,6 +250,13 @@ export default async function setupTests(config) {
// depend on the test browser's pointer.
noteKeyboardEvidence();
+ const headlessTestem =
+ window.Testem && navigator.userAgent.includes("HeadlessChrome");
+ const preexistingObserved = new Set([
+ ...ASYNC_OBSERVERS.keys(),
+ ...SYNC_OBSERVERS.keys(),
+ ]);
+
let app;
QUnit.testStart(async function (ctx) {
let settings = resetSettings();
@@ -326,6 +337,16 @@ export default async function setupTests(config) {
QUnit.testDone(function () {
testCleanup(getOwner(app), app);
+ // A pending ceremony never settles in headless Chrome, so it would retain the app
+ WebauthnAbortHandler.controller?.abort();
+
+ // Test modules can keep fakes after the test; their unformatted error stacks,
+ // call history and pending timers would retain the test's owner
+ for (const fake of sinon.getFakes()) {
+ delete fake.stackTraceError;
+ }
+ sinon.resetHistory();
+ sinon.clock?.reset();
sinon.restore();
// Destroy the previous Application so its entire dependency graph
@@ -335,6 +356,16 @@ export default async function setupTests(config) {
app.destroy();
});
+ // Ember keeps observed objects in global maps until they're destroyed,
+ // which models never are
+ for (const map of [ASYNC_OBSERVERS, SYNC_OBSERVERS]) {
+ for (const observed of map.keys()) {
+ if (!preexistingObserved.has(observed)) {
+ map.delete(observed);
+ }
+ }
+ }
+
// The inspector shim's global list would otherwise pin the destroyed app's registry.
globalThis.emberInspectorApps = globalThis.emberInspectorApps?.filter(
(entry) => entry.app !== app
@@ -360,6 +391,11 @@ export default async function setupTests(config) {
window.MessageBus.unsubscribe("*");
localStorage.clear();
+ if (headlessTestem) {
+ // Chrome keeps logged objects alive for DevTools even when it's closed
+ // eslint-disable-next-line no-console
+ console.clear();
+ }
enableLoadMoreObserver();
enableVirtualization();
@@ -392,7 +428,12 @@ export default async function setupTests(config) {
// forces 0 as duration for all jquery animations
$.fx.off = true;
- setupToolbar();
+ if (headlessTestem) {
+ // Nobody sees this report, and it keeps every passed test's DOM to unhide later
+ QUnit.config.reporters.html = false;
+ } else {
+ setupToolbar();
+ }
reportMemoryUsageAfterTests();
patchFailedAssertion();
diff --git a/frontend/discourse/tests/unit/lib/load-script-test.js b/frontend/discourse/tests/unit/lib/load-script-test.js
index ff3d68b6888..25cd8526c66 100644
--- a/frontend/discourse/tests/unit/lib/load-script-test.js
+++ b/frontend/discourse/tests/unit/lib/load-script-test.js
@@ -5,40 +5,27 @@ import loadScript from "discourse/lib/load-script";
module("Unit | Utility | load-script", function (hooks) {
setupTest(hooks);
+ let mockScriptBehavior;
+
hooks.beforeEach(function () {
- this.originalCreateElement = document.createElement.bind(document);
- this.appendedScripts = [];
- this.mockScriptBehavior = null;
+ mockScriptBehavior = null;
- const testContext = this;
- document.createElement = function (tagName) {
- const element = testContext.originalCreateElement(tagName);
- if (tagName.toLowerCase() === "script") {
- testContext.appendedScripts.push(element);
- const originalAppendChild = document.head.appendChild.bind(
- document.head
- );
- document.head.appendChild = function (child) {
- if (child === element && testContext.mockScriptBehavior) {
- setTimeout(() => {
- testContext.mockScriptBehavior(element);
- }, 0);
- return child;
- }
- return originalAppendChild(child);
- };
+ const originalAppendChild = document.head.appendChild.bind(document.head);
+ document.head.appendChild = function (child) {
+ if (child.tagName === "SCRIPT" && mockScriptBehavior) {
+ setTimeout(() => mockScriptBehavior(child), 0);
+ return child;
}
- return element;
+ return originalAppendChild(child);
};
});
hooks.afterEach(function () {
- document.createElement = this.originalCreateElement;
- this.appendedScripts.forEach((script) => script.remove?.());
+ delete document.head.appendChild;
});
test("loadScript rejects when script fails to load", async function (assert) {
- this.mockScriptBehavior = (script) => {
+ mockScriptBehavior = (script) => {
script.onerror?.();
};
@@ -57,7 +44,7 @@ module("Unit | Utility | load-script", function (hooks) {
const uniqueUrl = "/test-scripts/retry-test-" + Date.now() + ".js";
let callCount = 0;
- this.mockScriptBehavior = (script) => {
+ mockScriptBehavior = (script) => {
callCount++;
if (callCount === 1) {
script.onerror?.();