@@ -301,3 +301,63 @@ func TestMetadataContextIsolation(t *testing.T) {
301301 assert .Equal (t , "value2" , value2 )
302302 })
303303}
304+
305+ func TestContextHasMetadata (t * testing.T ) {
306+ t .Run ("returns true when context has metadata" , func (t * testing.T ) {
307+ ctx := WithMetadataContext (context .Background ())
308+ assert .True (t , ContextHasMetadata (ctx ))
309+ })
310+
311+ t .Run ("returns false for context without metadata" , func (t * testing.T ) {
312+ ctx := context .Background ()
313+ assert .False (t , ContextHasMetadata (ctx ))
314+ })
315+
316+ t .Run ("returns true after setting metadata values" , func (t * testing.T ) {
317+ ctx := WithMetadataContext (context .Background ())
318+ ContextMetadataSet (ctx , "key1" , "value1" )
319+ ContextMetadataSet (ctx , "key2" , "value2" )
320+
321+ assert .True (t , ContextHasMetadata (ctx ))
322+ })
323+
324+ t .Run ("returns true for empty metadata context" , func (t * testing.T ) {
325+ ctx := WithMetadataContext (context .Background ())
326+ // No values set, but metadata context exists
327+ assert .True (t , ContextHasMetadata (ctx ))
328+ })
329+
330+ t .Run ("child context inherits metadata from parent" , func (t * testing.T ) {
331+ parentCtx := WithMetadataContext (context .Background ())
332+ ContextMetadataSet (parentCtx , "key" , "value" )
333+
334+ type testContextKey string
335+ childCtx := context .WithValue (parentCtx , testContextKey ("other-key" ), "other-value" )
336+
337+ assert .True (t , ContextHasMetadata (parentCtx ))
338+ assert .True (t , ContextHasMetadata (childCtx ))
339+ })
340+
341+ t .Run ("returns false for wrong type in context" , func (t * testing.T ) {
342+ ctx := context .WithValue (context .Background (), metadataCtxKey , "wrong type" )
343+ assert .False (t , ContextHasMetadata (ctx ))
344+ })
345+
346+ t .Run ("returns true for cancelled context with metadata" , func (t * testing.T ) {
347+ ctx , cancel := context .WithCancel (context .Background ())
348+ ctx = WithMetadataContext (ctx )
349+ cancel ()
350+
351+ assert .True (t , ContextHasMetadata (ctx ))
352+ })
353+
354+ t .Run ("multiple contexts with metadata are independent" , func (t * testing.T ) {
355+ ctx1 := WithMetadataContext (context .Background ())
356+ ctx2 := WithMetadataContext (context .Background ())
357+ ctx3 := context .Background ()
358+
359+ assert .True (t , ContextHasMetadata (ctx1 ))
360+ assert .True (t , ContextHasMetadata (ctx2 ))
361+ assert .False (t , ContextHasMetadata (ctx3 ))
362+ })
363+ }
0 commit comments