@@ -299,4 +299,64 @@ public void ClearOutputResetFlag_GivenMultipleCalls_WhenCalled_ThenAllowsRepeate
299299 // Then
300300 Assert . Equal ( $ "First message{ Environment . NewLine } Second message{ Environment . NewLine } ", _testWriter . ToString ( ) ) ;
301301 }
302+
303+ [ Fact ]
304+ public void HasLambdaReInterceptedConsole_GivenConsoleOutThrowsException_WhenCalled_ThenReturnsTrue ( )
305+ {
306+ // Given
307+ Environment . SetEnvironmentVariable ( "AWS_LAMBDA_FUNCTION_NAME" , "test-function" ) ;
308+
309+ // Create a mock TextWriter that throws when accessing its type
310+ var mockWriter = new ThrowingTextWriter ( ) ;
311+ Console . SetOut ( mockWriter ) ;
312+
313+ var wrapper = new ConsoleWrapper ( ) ;
314+
315+ // When - This will trigger HasLambdaReInterceptedConsole which should catch the exception
316+ var exception = Record . Exception ( ( ) => wrapper . WriteLine ( "test message" ) ) ;
317+
318+ // Then - Should not throw, the catch block should handle it
319+ Assert . Null ( exception ) ;
320+ }
321+
322+ [ Fact ]
323+ public void OverrideLambdaLogger_GivenConsoleOpenStandardOutputThrows_WhenCalled_ThenDoesNotThrow ( )
324+ {
325+ // Given
326+ Environment . SetEnvironmentVariable ( "AWS_LAMBDA_FUNCTION_NAME" , "test-function" ) ;
327+
328+ // Create a scenario where Console.OpenStandardOutput might fail
329+ // We'll simulate this by creating conditions that trigger the catch block
330+ var wrapper = new ConsoleWrapper ( ) ;
331+
332+ // When - Multiple calls to trigger the override logic and potential failures
333+ var exception = Record . Exception ( ( ) =>
334+ {
335+ for ( int i = 0 ; i < 5 ; i ++ )
336+ {
337+ wrapper . WriteLine ( $ "test message { i } ") ;
338+ }
339+ } ) ;
340+
341+ // Then - Should not throw even if StreamWriter creation fails
342+ Assert . Null ( exception ) ;
343+ }
344+
345+ // Helper class to simulate exceptions in Console.Out.GetType()
346+ private class ThrowingTextWriter : TextWriter
347+ {
348+ public override System . Text . Encoding Encoding => System . Text . Encoding . UTF8 ;
349+
350+ public override void Write ( char value )
351+ {
352+ // Simulate the scenario where accessing type information fails
353+ // by throwing when any operation is performed
354+ throw new InvalidOperationException ( "Simulated exception during console operation" ) ;
355+ }
356+
357+ public override void WriteLine ( string value )
358+ {
359+ throw new InvalidOperationException ( "Simulated exception during console operation" ) ;
360+ }
361+ }
302362}
0 commit comments