Skip to content

test: Strengthen assertions and isolate external HTTP calls - #985

Draft
marandaneto wants to merge 1 commit into
mainfrom
test-audit
Draft

marandaneto wants to merge 1 commit into
mainfrom
test-audit

Conversation

@marandaneto

Copy link
Copy Markdown
Member

💡 Motivation and Context

Several tests could pass without exercising the behavior they claimed to protect. Some also depended on external HTTP services, scheduler timing, or assertions raised inside worker callbacks that catch exceptions.

This test-only change replaces those HTTP calls with controlled responses and strengthens checks for retry counts, event payloads, exception propagation, truncation, copy isolation, and lifecycle behavior. Consumer tests now wait for delivery and stop their workers. LangChain error tests still exercise the real callback lifecycle through a mocked HTTP transport.

These are the validated repairs from a partial test audit. This PR does not claim that every repository test has been reviewed. No production code or public API changes are included.

💚 How did you test it?

  • Root suite with external socket connections blocked: 4,143 passed, 16 skipped. The same guarded baseline had 4,137 passed and 6 failures involving external HTTP dependencies.
  • Runtime branch coverage, excluding tests: combined coverage changed from 88.18059% to 88.18510%. Covered lines increased from 14,622 to 14,623 of 16,234. Covered branches stayed at 4,910 of 5,916. The main benefit is stronger assertions rather than broader execution coverage.
  • OpenFeature: 68 passed. Django middleware and exception integration: 7 passed. Compliance adapter: 23 passed.
  • Ruff lint and formatting, mypy baseline filtering, the public API checker tests, and import with warnings treated as errors passed.
  • Changing the tracing default flush interval to 50 seconds in memory passed the old defaults test and failed the repaired test.
  • Autoreview against origin/main reported no actionable findings for 107b3fb.

Validation used Python 3.13.13. Live credential-dependent tests, MCP v2, and the full Python-version matrix were not run.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Pi used read-only subagents for test inventories and review, then applied and validated focused test repairs in a dedicated worktree. Tools included Git, pytest, coverage.py, Ruff, mypy, and the autoreview helper. The audit remains incomplete, and unresolved review scope was not treated as approved. Local audit notes are kept outside the PR. No shared session link is available.

@marandaneto marandaneto self-assigned this Sep 26, 2026
@marandaneto

Copy link
Copy Markdown
Member Author

Test coverage comparison

Measured on Python 3.13.13 with the same branch-coverage command before and after. Coverage includes runtime code under posthog/ and excludes posthog/test/*. External socket connections were blocked, with loopback allowed.

Metric Before After Change
Line coverage 90.07022% 90.07638% +0.00616 percentage points
Covered lines 14,622 / 16,234 14,623 / 16,234 +1
Branch coverage 82.99527% 82.99527% Unchanged
Covered branches 4,910 / 5,916 4,910 / 5,916 Unchanged
Combined coverage 88.18059% 88.18510% +0.00451 percentage points
Tests passed 4,137 4,143 +6
Tests failed 6 0 -6
Tests skipped 16 16 Unchanged

The six baseline failures involved external HTTP dependencies under the network guard. The repaired tests use controlled transport responses instead.

The main improvement is stronger assertions and test isolation, not broader execution coverage. As one check, changing the tracing default flush interval to 50 seconds in memory passed the old defaults test but failed the repaired test.

These numbers cover the root suite only. Separate validation passed for OpenFeature (68 tests), Django middleware and exception capture (7 tests), and the compliance adapter (23 tests). The comprehensive semantic audit remains incomplete. Live credential-dependent tests, MCP v2, and the full Python-version matrix were not run.

@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-26T15:30:39.173191+00:00
Duration: 258928ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 511ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 506ms
Required Headers.Has Authorization Bearer Header ✅ 507ms
Required Headers.Has Content Type Json ✅ 517ms
Required Headers.Has Posthog Sdk Info Format ✅ 505ms
Required Headers.Has Posthog Attempt Header ✅ 506ms
Required Headers.Has Posthog Request Id ✅ 505ms
Required Headers.Has Posthog Request Timestamp ✅ 505ms
Required Headers.Has User Agent ✅ 506ms
Body Format.Body Has Created At And Batch ✅ 505ms
Body Format.No Api Key In Body ✅ 506ms
Body Format.No Sent At In Body ✅ 505ms
Event Format.Event Has Required Root Fields ✅ 506ms
Event Format.Event Uuid Is Valid ✅ 505ms
Event Format.Event Timestamp Is Rfc3339 ✅ 506ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 509ms
Event Format.Distinct Id Is String ✅ 505ms
Event Format.Distinct Id At Root Not Properties ✅ 506ms
Event Format.Custom Properties Preserved ✅ 506ms
Event Format.Set Properties Preserved ✅ 505ms
Event Format.Set Once Properties Preserved ✅ 506ms
Event Format.Groups Properties Preserved ✅ 505ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 506ms
Event Format.Event Has Required Root Fields Batch ✅ 520ms
Event Format.Event Uuid Is Valid Batch ✅ 507ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 508ms
Event Format.Distinct Id Is String Batch ✅ 508ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 507ms
Event Format.Custom Properties Preserved Batch ✅ 508ms
Event Format.Set Properties Preserved Batch ✅ 507ms
Event Format.Set Once Properties Preserved Batch ✅ 507ms
Event Format.Groups Properties Preserved Batch ✅ 508ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 508ms
Batch Behavior.Multiple Events In Single Batch ✅ 510ms
Batch Behavior.Batch Envelope Smoke ✅ 509ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 504ms
Batch Behavior.Flush At Triggers Batch ✅ 1007ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 505ms
Deduplication.Generates Unique Uuids ✅ 510ms
Deduplication.Different Events Same Content Different Uuids ✅ 507ms
Deduplication.Preserves Uuid On Retry ✅ 6512ms
Deduplication.Preserves Timestamp On Retry ✅ 6512ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6517ms
Deduplication.No Duplicate Events In Batch ✅ 511ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 505ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13520ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6508ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3011ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6512ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 506ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 508ms
Response Format Validation.Success No Retry After When All Ok ✅ 507ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1508ms
Response Format Validation.Success No Retry After When Drop Only ✅ 508ms
Response Format Validation.Response Echoes Request Id ✅ 505ms
Retry Behavior.Retries On 408 ✅ 6512ms
Retry Behavior.Retries On 500 ✅ 6513ms
Retry Behavior.Retries On 503 ✅ 8514ms
Retry Behavior.Retries On 504 ✅ 6512ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3511ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11515ms
Retry Behavior.Does Not Retry On 400 ✅ 2510ms
Retry Behavior.Does Not Retry On 401 ✅ 2507ms
Retry Behavior.Does Not Retry On 402 ✅ 2508ms
Retry Behavior.Does Not Retry On 413 ✅ 2508ms
Retry Behavior.Does Not Retry On 415 ✅ 2506ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2506ms
Retry Behavior.Implements Backoff ✅ 22513ms
Retry Behavior.Max Retries Respected ✅ 22527ms
Partial Batch Handling.Handles 200 Full Success ✅ 2509ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3511ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3511ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3510ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6513ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6510ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6515ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6513ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6512ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6515ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8513ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3511ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3513ms
Compression.Sends Gzip Content Encoding ✅ 507ms
Compression.No Content Encoding When Disabled ✅ 505ms
Compression.Compressed Body Is Decompressible ✅ 506ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2506ms
Event Options.Cookieless Mode Override ✅ 506ms
Event Options.Disable Skew Correction Override ✅ 505ms
Event Options.Process Person Profile Override ✅ 506ms
Event Options.Product Tour Id Override ✅ 506ms
Event Options.Unset Options Omitted ✅ 505ms
Event Options.Options Override In Batch ✅ 508ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 506ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 505ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 506ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 505ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 505ms
Identity.Capture Ai Event Has Uuid ✅ 506ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 505ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 506ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 6ms
Request Payload.Flags Request Uses V2 Query Param ✅ 6ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 6ms
Request Payload.Flags Request Omits Authorization Header ✅ 6ms
Request Payload.Token In Flags Body Matches Init ✅ 6ms
Request Payload.Groups Round Trip ✅ 5ms
Request Payload.Groups Default To Empty Object ✅ 6ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 6ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 6ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 5ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 505ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 8ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 6ms
Retry Behavior.Retries Flags On 502 ✅ 307ms
Retry Behavior.Retries Flags On 504 ✅ 308ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 507ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 41ms
Versioned Boolean Matching.Matching Version 1 ✅ 42ms
Versioned Boolean Matching.Matching Version 2 ✅ 41ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 21ms

@greptile-apps

greptile-apps Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Retrigger

[Low risk] Test improvements and assertion strengthening across test files.

The PR appears safe to merge, with non-blocking gaps in tests intended to protect timing and registry coverage.

Reviews (1) · Last reviewed commit: "test: Strengthen assertions and isolate ..."

delivered.clear()
event = _track_event("python event %d" % i)
q.put(event)
self.assertTrue(delivered.wait(5))

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.

P2 Flush timing goes unchecked
This test waits up to five seconds for each event but never checks that delivery waited for the configured 0.3-second interval. It would still pass if partial batches flushed immediately, so it cannot catch an early-flush regression. Use a controlled clock or check that no request occurs before the interval.

Knowledge Base Used: Event capture and delivery

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/test/test_consumer.py
Line: 259

Comment:
**Flush timing goes unchecked**
This test waits up to five seconds for each event but never checks that delivery waited for the configured 0.3-second interval. It would still pass if partial batches flushed immediately, so it cannot catch an early-flush regression. Use a controlled clock or check that no request occurs before the interval.

**Knowledge Base Used:** [Event capture and delivery](https://app.greptile.com/posthog-org-19734/-/custom-context/knowledge-base/posthog/posthog-python/-/docs/event-capture-and-delivery.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +61 to +62
for resource_name in resource_types:
wrapper_type = wrappers[resource_name]

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.

P2 New wrappers can go untested
The test now iterates over the separate resource_types map rather than the wrapper registry used by production code. If a wrapper is added without a matching test-resource entry, this test silently skips it. Iterate over wrappers.items() and use resource_types to check each original type, or assert that the maps have the same keys.

Knowledge Base Used: AI provider integrations

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/test/ai/openai/test_resource_wrapping.py
Line: 61-62

Comment:
**New wrappers can go untested**
The test now iterates over the separate `resource_types` map rather than the wrapper registry used by production code. If a wrapper is added without a matching test-resource entry, this test silently skips it. Iterate over `wrappers.items()` and use `resource_types` to check each original type, or assert that the maps have the same keys.

**Knowledge Base Used:** [AI provider integrations](https://app.greptile.com/posthog-org-19734/-/custom-context/knowledge-base/posthog/posthog-python/-/docs/ai-provider-integrations.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +27 to +33
obj = SimpleNamespace(
path="posthog.version.VERSION", annotation=None, value='"7.19.1"'
)
assert (
check_public_api._attribute_details(obj)
== "posthog.version.VERSION = <version>"
)

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.

P2 Placeholder coverage no longer scales
The hardcoded VERSION case replaces a loop over every entry in ATTRIBUTE_VALUE_PLACEHOLDERS. A future placeholder could stop working without this test noticing. Keep the per-entry check and add the non-placeholder case separately.

Prompt To Fix With AI
This is a comment left during a code review.
Path: .github/scripts/test_check_public_api.py
Line: 27-33

Comment:
**Placeholder coverage no longer scales**
The hardcoded `VERSION` case replaces a loop over every entry in `ATTRIBUTE_VALUE_PLACEHOLDERS`. A future placeholder could stop working without this test noticing. Keep the per-entry check and add the non-placeholder case separately.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

This branch has not been deployed

No deployments
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