Skip to content

🐛 Fixed flaky unit tests caused by DNS stubs lost after sinon.restore()#27168

Open
ErisDS wants to merge 1 commit intomainfrom
fix/flaky-dns-stub-unit-tests
Open

🐛 Fixed flaky unit tests caused by DNS stubs lost after sinon.restore()#27168
ErisDS wants to merge 1 commit intomainfrom
fix/flaky-dns-stub-unit-tests

Conversation

@ErisDS
Copy link
Copy Markdown
Member

@ErisDS ErisDS commented Apr 6, 2026

Summary

  • The global disableNetwork() helper stubs dnsPromises.lookup via sinon during beforeAll to prevent real DNS lookups in tests
  • Many tests call sinon.restore() in their afterEach, which removes all sinon stubs — including the DNS one
  • Subsequent tests then perform real DNS lookups against nocked domains (e.g. external.com), which can be slow or unreliable on CI, causing intermittent 2000ms timeouts
  • This was the root cause of the flaky ExternalMediaInliner CDN storage adapter test failures seen in https://github.com/TryGhost/Ghost/actions/runs/24012086446/job/70025449313

What changed

  • test/utils/overrides.js — Re-apply disableNetwork() in the global mocha root afterEach hook, so DNS stubs are always present for the next test
  • 3 test files — Removed redundant DNS stubs that duplicated what disableNetwork() already provides (request-external.test.js, ghost-mailer.test.js, mention-discovery-service.test.js)
  • mention-sending-service.test.js — Fixed a test that was silently depending on the DNS stub being absent (so real DNS would resolve domaincontrol.com127.0.0.1). Now explicitly stubs DNS to return a private IP, making it deterministic

Test plan

  • All 42 external-media-inliner tests pass
  • All request-external, ghost-mailer, mention-discovery-service, mention-sending-service tests pass
  • Full yarn test:unit suite passes (only pre-existing Node version mismatch failure)
  • CI passes

🤖 Generated with Claude Code

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 6, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 35407bb0-1cbe-48cf-ad83-ab7d1883f836

📥 Commits

Reviewing files that changed from the base of the PR and between 7574deb and 113c166.

📒 Files selected for processing (5)
  • ghost/core/test/unit/server/lib/request-external.test.js
  • ghost/core/test/unit/server/services/mail/ghost-mailer.test.js
  • ghost/core/test/unit/server/services/mentions/mention-discovery-service.test.js
  • ghost/core/test/unit/server/services/mentions/mention-sending-service.test.js
  • ghost/core/test/utils/overrides.js
💤 Files with no reviewable changes (2)
  • ghost/core/test/unit/server/lib/request-external.test.js
  • ghost/core/test/unit/server/services/mail/ghost-mailer.test.js
✅ Files skipped from review due to trivial changes (2)
  • ghost/core/test/utils/overrides.js
  • ghost/core/test/unit/server/services/mentions/mention-discovery-service.test.js
🚧 Files skipped from review as they are similar to previous changes (1)
  • ghost/core/test/unit/server/services/mentions/mention-sending-service.test.js

Walkthrough

Removed test-level DNS stubs from several unit tests: request-external, ghost-mailer, and mention-discovery-service no longer import or stub Node DNS. The mention-sending-service test now stubs dnsPromises.lookup inside a specific test to return 127.0.0.1. The global test overrides (ghost/core/test/utils/overrides.js) now re-invoke mockManager.disableNetwork() in mochaHooks.afterEach to restore network/DNS blocking after per-test cleanup. No public API or exported declarations were changed.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main fix: resolving flaky unit tests caused by DNS stubs being removed after sinon.restore().
Description check ✅ Passed The description comprehensively explains the root cause, the changes made across multiple files, and test validation results, all directly related to the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/flaky-dns-stub-unit-tests

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@ghost/core/test/utils/overrides.js`:
- Around line 106-115: The afterEach hook currently calls originalAfterEach()
and then mockManager.disableNetwork(), but if originalAfterEach() throws the
disableNetwork call is skipped; update the logic in the afterEach override
(where originalAfterEach is invoked) to call originalAfterEach() inside a
try/finally and move mockManager.disableNetwork() into the finally block so
disableNetwork always runs even when originalAfterEach throws.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d2876cbd-cfed-4d8a-a0eb-1411bdb282e4

📥 Commits

Reviewing files that changed from the base of the PR and between 0f7df8e and 7574deb.

📒 Files selected for processing (5)
  • ghost/core/test/unit/server/lib/request-external.test.js
  • ghost/core/test/unit/server/services/mail/ghost-mailer.test.js
  • ghost/core/test/unit/server/services/mentions/mention-discovery-service.test.js
  • ghost/core/test/unit/server/services/mentions/mention-sending-service.test.js
  • ghost/core/test/utils/overrides.js
💤 Files with no reviewable changes (2)
  • ghost/core/test/unit/server/lib/request-external.test.js
  • ghost/core/test/unit/server/services/mail/ghost-mailer.test.js

Comment on lines 106 to +115
if (originalAfterEach) {
await originalAfterEach();
}

// Re-apply network disabling after each test. Individual test afterEach hooks
// often call sinon.restore() which removes the DNS stubs set up by
// disableNetwork() in beforeAll. Without re-applying, subsequent tests make
// real DNS lookups on nocked domains which can be slow on CI, causing flaky
// timeouts (e.g. ExternalMediaInliner CDN storage adapter tests).
mockManager.disableNetwork();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Harden re-stubbing with finally to avoid fallback to real DNS on hook failures.

If originalAfterEach() throws, mockManager.disableNetwork() is skipped, which can reintroduce cross-test DNS flakiness.

Proposed fix
-    if (originalAfterEach) {
-        await originalAfterEach();
-    }
-
-    // Re-apply network disabling after each test. Individual test afterEach hooks
-    // often call sinon.restore() which removes the DNS stubs set up by
-    // disableNetwork() in beforeAll. Without re-applying, subsequent tests make
-    // real DNS lookups on nocked domains which can be slow on CI, causing flaky
-    // timeouts (e.g. ExternalMediaInliner CDN storage adapter tests).
-    mockManager.disableNetwork();
+    try {
+        if (originalAfterEach) {
+            await originalAfterEach();
+        }
+    } finally {
+        // Re-apply network disabling after each test. Individual test afterEach hooks
+        // often call sinon.restore() which removes the DNS stubs set up by
+        // disableNetwork() in beforeAll. Without re-applying, subsequent tests make
+        // real DNS lookups on nocked domains which can be slow on CI, causing flaky
+        // timeouts (e.g. ExternalMediaInliner CDN storage adapter tests).
+        mockManager.disableNetwork();
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (originalAfterEach) {
await originalAfterEach();
}
// Re-apply network disabling after each test. Individual test afterEach hooks
// often call sinon.restore() which removes the DNS stubs set up by
// disableNetwork() in beforeAll. Without re-applying, subsequent tests make
// real DNS lookups on nocked domains which can be slow on CI, causing flaky
// timeouts (e.g. ExternalMediaInliner CDN storage adapter tests).
mockManager.disableNetwork();
try {
if (originalAfterEach) {
await originalAfterEach();
}
} finally {
// Re-apply network disabling after each test. Individual test afterEach hooks
// often call sinon.restore() which removes the DNS stubs set up by
// disableNetwork() in beforeAll. Without re-applying, subsequent tests make
// real DNS lookups on nocked domains which can be slow on CI, causing flaky
// timeouts (e.g. ExternalMediaInliner CDN storage adapter tests).
mockManager.disableNetwork();
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ghost/core/test/utils/overrides.js` around lines 106 - 115, The afterEach
hook currently calls originalAfterEach() and then mockManager.disableNetwork(),
but if originalAfterEach() throws the disableNetwork call is skipped; update the
logic in the afterEach override (where originalAfterEach is invoked) to call
originalAfterEach() inside a try/finally and move mockManager.disableNetwork()
into the finally block so disableNetwork always runs even when originalAfterEach
throws.

ref https://github.com/TryGhost/Ghost/actions/runs/24012086446/job/70025449313

The global disableNetwork() helper stubs dnsPromises.lookup via sinon
during beforeAll to prevent real DNS lookups in tests. However, many
tests call sinon.restore() in their afterEach, which nukes all sinon
stubs — including the DNS one. Subsequent tests then perform real DNS
lookups against nocked domains (e.g. external.com), which can be slow
or unreliable on CI, causing intermittent 2000ms timeouts.

This was the root cause of the flaky ExternalMediaInliner CDN storage
adapter test failures.

The fix re-applies disableNetwork() in the global mocha root afterEach
hook, which runs after every test's own afterEach. This ensures DNS
stubs are always restored after sinon.restore() removes them. Three
tests that were redundantly re-stubbing DNS with the same fake values
are cleaned up, and one test that was silently depending on the stub
being absent (to get a real private-IP DNS result) is updated to
explicitly stub the behavior it needs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@ErisDS ErisDS force-pushed the fix/flaky-dns-stub-unit-tests branch from 7574deb to 113c166 Compare April 6, 2026 12:26
@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Apr 6, 2026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant