@@ -654,4 +654,48 @@ def test_build_event_payload_device_id_fallback(self):
654654 self .assertEqual (payload ["device_id" ], "anon-1" )
655655
656656 payload2 = _build_event_payload ("e" , {}, {"id" : "raw-id" }, "" , "x" )
657- self .assertEqual (payload2 ["device_id" ], "raw-id" )
657+ self .assertEqual (payload2 ["device_id" ], "raw-id" )
658+
659+ class TestExperimentEventContext (unittest .TestCase ):
660+ """Experiment-viewed ingestor events must carry the exposure-time user
661+ context (the attributes used for bucketing/leaf routing), matching the JS
662+ plugin's use of userContext. The instance fallback only covers the sync
663+ client's legacy two-argument invocation."""
664+
665+ def _make_plugin_and_events (self ):
666+ from growthbook .plugins .growthbook_tracking import GrowthBookTrackingPlugin
667+
668+ plugin = GrowthBookTrackingPlugin (ingestor_host = "https://test.growthbook.io" )
669+ events = []
670+ plugin ._add_event_to_batch = events .append
671+ return plugin , events
672+
673+ def _result_stub (self ):
674+ return MagicMock (
675+ variationId = 1 , inExperiment = True , hashUsed = True ,
676+ hashAttribute = "id" , hashValue = "u1" , key = "1" ,
677+ )
678+
679+ def test_event_uses_exposure_time_user_context (self ):
680+ plugin , events = self ._make_plugin_and_events ()
681+ user_context = MagicMock (
682+ attributes = {"id" : "u1" , "country" : "US" }, url = "https://app.example.com"
683+ )
684+ plugin ._track_experiment_viewed (
685+ Experiment (key = "exp" , variations = [0 , 1 ]), self ._result_stub (), user_context
686+ )
687+ self .assertEqual (len (events ), 1 )
688+ self .assertEqual (events [0 ]["context_json" ], {"country" : "US" })
689+ self .assertEqual (events [0 ]["device_id" ], "u1" )
690+ self .assertEqual (events [0 ]["url" ], "https://app.example.com" )
691+
692+ def test_event_falls_back_to_instance_attributes (self ):
693+ plugin , events = self ._make_plugin_and_events ()
694+ plugin ._gb_instance = MagicMock (
695+ _attributes = {"id" : "u2" }, _url = "https://legacy.example.com"
696+ )
697+ plugin ._track_experiment_viewed (
698+ Experiment (key = "exp" , variations = [0 , 1 ]), self ._result_stub (), None
699+ )
700+ self .assertEqual (events [0 ]["device_id" ], "u2" )
701+ self .assertEqual (events [0 ]["url" ], "https://legacy.example.com" )
0 commit comments