-
Notifications
You must be signed in to change notification settings - Fork 0
feat(v2): validate server identify and alias delivery #65
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dustinbyrne
wants to merge
3
commits into
main
Choose a base branch
from
feat/identify-alias-blackbox
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| pypi/posthog-sdk-test-harness: minor | ||
| --- | ||
|
|
||
| Add opt-in v2 server identify and alias delivery assertions and distinguish JSON booleans from numbers in event-property comparisons. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,230 @@ | ||
| """Public identify/alias bindings over the existing controlled HTTP host.""" | ||
|
|
||
| import json | ||
| from types import SimpleNamespace | ||
|
|
||
| import pytest | ||
|
|
||
| from posthog_test_harness.v2.contracts import BoundaryError, Contracts, json_equal | ||
| from posthog_test_harness.v2.gherkin import load_cases | ||
| from posthog_test_harness.v2.report import strict_exit_code | ||
| from posthog_test_harness.v2.runner import STEPS, run | ||
| from tests.v2_analytics_wire_host import AnalyticsWireHost | ||
| from tests.v2_flush_host import serve | ||
|
|
||
| FEATURES = ["acceptance/public/identify.feature", "acceptance/public/alias.feature"] | ||
| SERVER_CASE_IDS = { | ||
| "acceptance:server:identify:scalar-values", | ||
| "acceptance:server:identify:nested-values", | ||
| "acceptance:server:alias:signup", | ||
| "acceptance:server:alias:second-person", | ||
| } | ||
| ARGUMENTS = { | ||
| "identify": {"distinct_id": "user-123", "set": {"active": False, "score": 0, "note": None}}, | ||
| "alias": {"distinct_id": "anon-123", "alias": "user-123"}, | ||
| } | ||
| EVENT_NAMES = {"identify": "$identify", "alias": "$create_alias"} | ||
|
|
||
|
|
||
| class IdentifyAliasHost(AnalyticsWireHost): | ||
| """Translate the two public operations; reuse admission, flush and transport.""" | ||
|
|
||
| def __init__(self, contracts, **options): | ||
| super().__init__(contracts, **options) | ||
| self.routes.extend(r for r in ("/identify", "/alias") if r != options.get("missing_route")) | ||
|
|
||
| async def invoke(self, fixture, call): | ||
| route, args = call["route"], call["args"] | ||
| if route not in ("/identify", "/alias"): | ||
| return await super().invoke(fixture, call) | ||
| if fixture.defect == "operation_throw": | ||
| raise RuntimeError("Controlled operation failure") | ||
| identity = args["distinct_id"] | ||
| if route == "/identify": | ||
| properties = {"$set": args["set"]} | ||
| else: | ||
| properties = {"alias": args["alias"]} | ||
| if fixture.defect == "reversed_alias": | ||
| identity, properties["alias"] = properties["alias"], identity | ||
| await fixture.engine.capture( | ||
| {"event": EVENT_NAMES[route[1:]], "distinct_id": identity, "properties": properties} | ||
| ) | ||
|
|
||
|
|
||
| def public_feature(operation): | ||
| args = ARGUMENTS[operation] | ||
| property_assertion = ( | ||
| '"$set" should equal JSON ' + json.dumps(args["set"]) | ||
| if operation == "identify" | ||
| else '"alias" should equal "user-123"' | ||
| ) | ||
| return f'''@public @black_box @sdk:server | ||
| Feature: Public {operation} regression | ||
| @case:regression:{operation} | ||
| Scenario: Deliver the public operation | ||
| Given an isolated SDK with empty persistent storage | ||
| And the SDK is initialized with token "test-token" and flush threshold 20 | ||
| When {operation} is called with JSON arguments: | ||
| """application/json | ||
| {json.dumps(args)} | ||
| """ | ||
| And pending captures are flushed | ||
| Then exactly 1 capture request should have been received | ||
| And the first request should contain exactly 1 parsed events | ||
| And the first received event field "event" should equal "{EVENT_NAMES[operation]}" | ||
| And the first received event field "distinct_id" should equal "{args['distinct_id']}" | ||
| And the first received event property {property_assertion} | ||
| ''' | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def regression_source(tmp_path): | ||
| for operation in ARGUMENTS: | ||
| (tmp_path / f"{operation}.feature").write_text(public_feature(operation)) | ||
| return tmp_path | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("operation", ARGUMENTS) | ||
| async def test_public_operation_delivers_exact_event(regression_source, operation): | ||
| contracts = Contracts() | ||
| async with serve(contracts, host_type=IdentifyAliasHost) as (host, url): | ||
| report, diagnostics = await run(contracts, regression_source, [f"{operation}.feature"], url, host.profile["id"]) | ||
| assert strict_exit_code(contracts, report) == 0, report | ||
| assert report["results"][0]["result"]["status"] == "passed" | ||
| assert [call["route"] for call in host.inputs] == ["/setup", f"/{operation}", "/flush"] | ||
| assert json_equal(host.inputs[1]["args"], ARGUMENTS[operation]) | ||
| assert len(host.closed) == 1 | ||
| assert len(diagnostics["cases"][0]["ingestion"]) == 1 | ||
|
|
||
|
|
||
| COMMON_DEFECTS = [ | ||
| ("wrong_event", "event_field"), | ||
| ("omit_event:event", "event_field"), | ||
| ("numeric_identity", "event_field"), | ||
| ("omit_event:distinct_id", "event_field"), | ||
| ("no_delivery", "request_count"), | ||
| ("empty_batch", "batch_count"), | ||
| ("append_duplicate_uuid", "batch_count"), | ||
| ("duplicate_request", "request_count"), | ||
| ("operation_throw", "unexpected_throw"), | ||
| ] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "operation,defect,code", | ||
| [(op, defect, code) for op in ARGUMENTS for defect, code in COMMON_DEFECTS] | ||
| + [ | ||
| ("identify", "missing_property:$set", "event_property"), | ||
| ("identify", 'property_value:0:$set:{"active":0,"score":0,"note":null}', "event_property"), | ||
| ("identify", 'property_value:0:$set:{"active":false,"score":false,"note":null}', "event_property"), | ||
| ("identify", 'property_value:0:$set:{"active":false,"score":0}', "event_property"), | ||
| ("identify", 'property_value:0:$set:{"active":false,"score":0,"note":false}', "event_property"), | ||
| ("alias", "missing_property:alias", "event_property"), | ||
| ("alias", 'property_value:0:alias:"wrong"', "event_property"), | ||
| ("alias", "reversed_alias", "event_field"), | ||
| ], | ||
| ) | ||
| async def test_public_operation_rejects_wire_defects(regression_source, operation, defect, code): | ||
| contracts = Contracts() | ||
| async with serve(contracts, host_type=IdentifyAliasHost, defect=defect) as (host, url): | ||
| report, _ = await run(contracts, regression_source, [f"{operation}.feature"], url, host.profile["id"]) | ||
| result = report["results"][0]["result"] | ||
| assert result["status"] == "failed_assertion", report | ||
| assert result["failure"]["code"] == code | ||
| assert result["failure"]["failed_step"]["source"]["path"] == f"{operation}.feature" | ||
| assert len(result["failure"]["call_ids"]) == (2 if defect == "operation_throw" else 3) | ||
| if defect == "operation_throw": | ||
| assert [call["route"] for call in host.inputs] == ["/setup", f"/{operation}"] | ||
| outcome = report["calls"][-1]["completion"]["outcome"] | ||
| assert outcome["kind"] == "thrown" | ||
| assert outcome["error"]["message"] == "Controlled operation failure" | ||
| assert len(host.closed) == 1 | ||
| assert strict_exit_code(contracts, report) == 1 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("operation", ARGUMENTS) | ||
| async def test_missing_public_operation_is_not_silently_excluded(regression_source, operation): | ||
| contracts = Contracts() | ||
| async with serve(contracts, host_type=IdentifyAliasHost, missing_route=f"/{operation}") as (host, url): | ||
| report, _ = await run(contracts, regression_source, [f"{operation}.feature"], url, host.profile["id"]) | ||
| result = report["results"][0]["result"] | ||
| assert result["status"] == "unsupported_binding", report | ||
| assert result["failure"]["code"] == "missing_operation" | ||
| assert not result["executed"] and not host.fixtures and not host.inputs | ||
| assert strict_exit_code(contracts, report) == 1 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("operation", ARGUMENTS) | ||
| async def test_server_cases_do_not_run_on_client_profile(regression_source, operation): | ||
| contracts = Contracts() | ||
| async with serve(contracts, host_type=IdentifyAliasHost, runtime="browser") as (host, url): | ||
| report, _ = await run(contracts, regression_source, [f"{operation}.feature"], url, host.profile["id"]) | ||
| assert report["results"][0]["result"]["status"] == "not_applicable", report | ||
| assert not host.inputs and not host.fixtures | ||
| assert strict_exit_code(contracts, report) == 1 # An entirely inapplicable scope cannot pass. | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "properties,expected,passes", | ||
| [ | ||
| ({"value": False}, False, True), | ||
| ({"value": 0}, 0, True), | ||
| ({"value": None}, None, True), | ||
| ({"value": True}, 1, False), | ||
| ({"value": 1}, True, False), | ||
| ({"value": 0}, False, False), | ||
| ({"value": False}, 0, False), | ||
| ({}, None, False), | ||
| (None, None, False), | ||
| ([], None, False), | ||
| ({"value": {"nested": [0, None]}}, {"nested": [False, None]}, False), | ||
| ({"value": {"nested": [False]}}, {"nested": [False, None]}, False), | ||
| ], | ||
| ) | ||
| async def test_received_property_json_preserves_types_and_presence(properties, expected, passes): | ||
| observed = [SimpleNamespace(parsed_events=[{"properties": properties}])] | ||
| ctx = SimpleNamespace(server=SimpleNamespace(state=SimpleNamespace(get_requests=lambda: observed))) | ||
| step = SimpleNamespace( | ||
| text='the first received event property "value" should equal JSON ' + json.dumps(expected), | ||
| argument={}, | ||
| source={"path": "property.feature", "line": 1}, | ||
| ) | ||
| handler, args = STEPS.bind(step) | ||
| if passes: | ||
| await handler(ctx, step, *args) | ||
| else: | ||
| with pytest.raises(BoundaryError) as error: | ||
| await handler(ctx, step, *args) | ||
| assert error.value.code == "event_property" | ||
|
|
||
|
|
||
| async def test_server_delivery_needs_no_storage_control(regression_source): | ||
| feature = regression_source / "identify.feature" | ||
| feature.write_text( | ||
| feature.read_text().replace("an isolated SDK with empty persistent storage", "an isolated SDK instance") | ||
| ) | ||
| contracts = Contracts() | ||
| async with serve(contracts, host_type=IdentifyAliasHost, missing_capability="storage.empty.v1") as (host, url): | ||
| report, _ = await run(contracts, regression_source, ["identify.feature"], url, host.profile["id"]) | ||
| assert strict_exit_code(contracts, report) == 0, report | ||
| assert [call["route"] for call in host.inputs] == ["/setup", "/identify", "/flush"] | ||
|
|
||
|
|
||
| async def test_companion_identify_alias_features_through_public_http(specs): | ||
| cases, _ = load_cases(specs, FEATURES) | ||
| selected = [case for case in cases if case.id in SERVER_CASE_IDS] | ||
| assert {case.id for case in selected} == SERVER_CASE_IDS | ||
| assert len(cases) == 8 # Existing client and validation cases remain in their acceptance files. | ||
| assert all(case.migration is None and "@sdk:server" in case.tags for case in selected) | ||
| contracts = Contracts() | ||
| async with serve(contracts, host_type=IdentifyAliasHost) as (host, url): | ||
| report, _ = await run(contracts, specs, FEATURES, url, host.profile["id"], case_ids=sorted(SERVER_CASE_IDS)) | ||
| assert strict_exit_code(contracts, report) == 0, report | ||
| assert [row["result"]["status"] for row in report["results"] if row["case_id"] in SERVER_CASE_IDS] == ["passed"] * 4 | ||
| assert [row["result"]["status"] for row in report["results"] if row["case_id"] not in SERVER_CASE_IDS] == [ | ||
| "not_selected" | ||
| ] * 4 | ||
| assert len(host.closed) == 4 | ||
| assert [call["route"] for call in host.inputs] == [ | ||
| route for case in selected for route in ("/setup", "/alias" if "alias" in case.id else "/identify", "/flush") | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This async test calls
Path.read_text()andPath.write_text()directly, blocking the event loop. This violates the repository directive to flag synchronous file I/O in async Python. Move the feature rewrite into a synchronous fixture or helper, or offload the file operations to a thread. This repository requirement must be satisfied before merging.Context Used: Be direct and concise: state the issue, its impact, and the fix, with no preamble or praise. Do not comment on alphabetical sorting, trailing commas, or formatting. Linters catch these. Judge code by four simplicity rules: it passes all the tests, ex... (source)
Prompt To Fix With AI