|
| 1 | +#if NET |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using Microsoft.Extensions.Logging.Testing; |
| 4 | + |
| 5 | +namespace Renci.SshNet.IntegrationTests |
| 6 | +{ |
| 7 | + [TestClass] |
| 8 | + public class LoggingTest : IntegrationTestBase |
| 9 | + { |
| 10 | + private readonly SftpClient _sftpClient; |
| 11 | + |
| 12 | + public LoggingTest() |
| 13 | + { |
| 14 | + _sftpClient = new SftpClient(SshServerHostName, SshServerPort, User.UserName, User.Password); |
| 15 | + } |
| 16 | + |
| 17 | + [TestMethod] |
| 18 | + public async Task SessionLoggerFactoryTest() |
| 19 | + { |
| 20 | + // remember the original logger factory and restore it later |
| 21 | + ILoggerFactory originalTestLoggerFactory = SshNetLoggingConfiguration.LoggerFactory; |
| 22 | + |
| 23 | + try |
| 24 | + { |
| 25 | + FakeLogCollector globalLogCollector = new(); |
| 26 | + FakeLogCollector sessionLogCollector = new(); |
| 27 | + |
| 28 | + ILoggerFactory globalLoggerFactory = CreateFakeLoggerFactory(globalLogCollector); |
| 29 | + SshNetLoggingConfiguration.InitializeLogging(globalLoggerFactory); |
| 30 | + |
| 31 | + _sftpClient.ConnectionInfo.LoggerFactory = CreateFakeLoggerFactory(sessionLogCollector); |
| 32 | + |
| 33 | + await _sftpClient.ConnectAsync(CancellationToken.None).ConfigureAwait(false); |
| 34 | + |
| 35 | + // all logs should have been written to the session logger only |
| 36 | + Assert.AreEqual(0, globalLogCollector.Count); |
| 37 | + Assert.IsTrue(sessionLogCollector.Count > 0); |
| 38 | + } |
| 39 | + finally |
| 40 | + { |
| 41 | + SshNetLoggingConfiguration.InitializeLogging(originalTestLoggerFactory); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + private ILoggerFactory CreateFakeLoggerFactory(FakeLogCollector fakeLogCollector) |
| 47 | + { |
| 48 | + FakeLoggerProvider fakeLogProvider = new(fakeLogCollector); |
| 49 | + |
| 50 | + return LoggerFactory.Create(builder => |
| 51 | + { |
| 52 | + builder.AddProvider(fakeLogProvider); |
| 53 | + builder.SetMinimumLevel(LogLevel.Trace); |
| 54 | + }); |
| 55 | + } |
| 56 | + |
| 57 | + [TestCleanup] |
| 58 | + public void Cleanup() |
| 59 | + { |
| 60 | + _sftpClient.Disconnect(); |
| 61 | + _sftpClient.Dispose(); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | +#endif |
0 commit comments