@@ -138,6 +138,93 @@ public void ResetsFeatureFlagCallTracking()
138138 }
139139 }
140140
141+ public class TheBeforeSendCallback
142+ {
143+ [ Fact ]
144+ public void CanModifyEventBeforeItIsQueued ( )
145+ {
146+ var config = new PostHogConfig
147+ {
148+ ApiKey = "test-api-key" ,
149+ BeforeSend = evt =>
150+ {
151+ evt . Properties . Remove ( "secret" ) ;
152+ evt . Properties [ "before_send" ] = true ;
153+ return evt ;
154+ } ,
155+ } ;
156+ var sdk = CreateSdk ( config ) ;
157+ var evt = new PostHogEvent (
158+ "before-send-event" ,
159+ "distinct-id" ,
160+ new Dictionary < string , object >
161+ {
162+ [ "$lib" ] = "posthog-unity" ,
163+ [ "$lib_version" ] = "1.0.0" ,
164+ [ "$session_id" ] = "session-id" ,
165+ [ "source" ] = "super" ,
166+ [ "secret" ] = "remove" ,
167+ }
168+ ) ;
169+
170+ var processed = RunBeforeSend ( sdk , evt ) ;
171+
172+ Assert . NotNull ( processed ) ;
173+ Assert . True ( ( bool ) processed . Properties [ "before_send" ] ) ;
174+ Assert . False ( processed . Properties . ContainsKey ( "secret" ) ) ;
175+ }
176+
177+ [ Theory ]
178+ [ MemberData ( nameof ( DropCallbacks ) ) ]
179+ public void CanDropEventBeforeItIsQueued ( Func < PostHogEvent , PostHogEvent > beforeSend )
180+ {
181+ var config = new PostHogConfig { ApiKey = "test-api-key" , BeforeSend = beforeSend } ;
182+ var sdk = CreateSdk ( config ) ;
183+
184+ var processed = RunBeforeSend ( sdk , new PostHogEvent ( "drop-me" , "distinct-id" ) ) ;
185+
186+ Assert . Null ( processed ) ;
187+ }
188+
189+ public static IEnumerable < object [ ] > DropCallbacks ( )
190+ {
191+ yield return new object [ ] { ( Func < PostHogEvent , PostHogEvent > ) ( _ => null ) } ;
192+ yield return new object [ ]
193+ {
194+ ( Func < PostHogEvent , PostHogEvent > ) (
195+ _ => throw new InvalidOperationException ( "beforeSend failed" )
196+ ) ,
197+ } ;
198+ }
199+
200+ static PostHogSDK CreateSdk ( PostHogConfig config )
201+ {
202+ var sdk = ( PostHogSDK ) RuntimeHelpers . GetUninitializedObject ( typeof ( PostHogSDK ) ) ;
203+ SetField ( sdk , "_config" , config ) ;
204+ return sdk ;
205+ }
206+
207+ static PostHogEvent RunBeforeSend ( PostHogSDK sdk , PostHogEvent evt )
208+ {
209+ var method = typeof ( PostHogSDK ) . GetMethod (
210+ "RunBeforeSend" ,
211+ BindingFlags . Instance | BindingFlags . NonPublic
212+ ) ;
213+ Assert . NotNull ( method ) ;
214+ return ( PostHogEvent ) method . Invoke ( sdk , new object [ ] { evt } ) ;
215+ }
216+
217+ static void SetField ( PostHogSDK sdk , string name , object value )
218+ {
219+ var field = typeof ( PostHogSDK ) . GetField (
220+ name ,
221+ BindingFlags . Instance | BindingFlags . NonPublic
222+ ) ;
223+ Assert . NotNull ( field ) ;
224+ field . SetValue ( sdk , value ) ;
225+ }
226+ }
227+
141228 [ Collection ( "UnityGlobals" ) ]
142229 public class ThePublicApiMethods
143230 {
0 commit comments