@@ -209,6 +209,92 @@ func (s *ClientTest) getClientWithMockedHttpTransport(transport httpmock.RoundTr
209209 )
210210}
211211
212+ func (s * ClientTest ) TestShutdownShouldReturnErrorWhenAlreadyShutdown () {
213+ // Given
214+ c := s .getClient ()
215+ err := c .StartSendingEvents (s .ctx , 1 * time .Microsecond )
216+ s .Require ().NoError (err )
217+ err = c .Shutdown (s .ctx )
218+ s .Require ().NoError (err )
219+
220+ // When
221+ err = c .Shutdown (s .ctx )
222+
223+ // Then
224+ s .Require ().ErrorContains (err , "already shutdown" )
225+ }
226+
227+ func (s * ClientTest ) TestShutdownShouldSucceedAfterStart () {
228+ // Given
229+ c := s .getClient ()
230+ err := c .StartSendingEvents (s .ctx , 1 * time .Microsecond )
231+ s .Require ().NoError (err )
232+
233+ // When
234+ err = c .Shutdown (s .ctx )
235+
236+ // Then
237+ s .Require ().NoError (err )
238+ }
239+
240+ func (s * ClientTest ) TestShutdownShouldFlushPendingEvents () {
241+ // Given
242+ var sentRequestBody []byte
243+ wg := & sync.WaitGroup {}
244+ wg .Add (1 )
245+ c := s .getClientWithMockedHttpTransport (func (req * http.Request ) (* http.Response , error ) {
246+ defer wg .Done ()
247+ body , err := io .ReadAll (req .Body )
248+ if err != nil {
249+ return nil , err
250+ }
251+ sentRequestBody = body
252+ return & http.Response {
253+ StatusCode : http .StatusMultiStatus ,
254+ Body : io .NopCloser (strings .NewReader ("{}" )),
255+ }, nil
256+ })
257+ err := c .StartSendingEvents (s .ctx , 1 * time .Hour ) // Long period to prevent automatic Flush
258+ s .Require ().NoError (err )
259+
260+ // When
261+ c .Trace ("input" , "output" )
262+ err = c .Shutdown (s .ctx )
263+ s .Require ().NoError (err )
264+ wg .Wait ()
265+
266+ // Then
267+ type requestBody struct {
268+ Batch []struct {
269+ Body struct {
270+ Input string `json:"input"`
271+ Output string `json:"output"`
272+ }
273+ } `json:"batch"`
274+ }
275+ bodyObj := requestBody {}
276+ err = json .Unmarshal (sentRequestBody , & bodyObj )
277+ s .Require ().NoError (err )
278+ s .Require ().Len (bodyObj .Batch , 1 )
279+ s .Require ().Equal ("input" , bodyObj .Batch [0 ].Body .Input )
280+ s .Require ().Equal ("output" , bodyObj .Batch [0 ].Body .Output )
281+ }
282+
283+ func (s * ClientTest ) TestStartSendingEventsShouldReturnErrorAfterShutdown () {
284+ // Given
285+ c := s .getClient ()
286+ err := c .StartSendingEvents (s .ctx , 1 * time .Microsecond )
287+ s .Require ().NoError (err )
288+ err = c .Shutdown (s .ctx )
289+ s .Require ().NoError (err )
290+
291+ // When
292+ err = c .StartSendingEvents (s .ctx , 1 * time .Microsecond )
293+
294+ // Then
295+ s .Require ().ErrorContains (err , "already shutdown" )
296+ }
297+
212298func TestLangfuseClient (t * testing.T ) {
213299 suite .Run (t , new (ClientTest ))
214300}
0 commit comments