Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions src/log4net.Tests/Appender/ContentEscapeTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#region Apache License
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
Expand All @@ -17,7 +17,6 @@
//
#endregion

using System.Reflection;

using log4net.Appender;

Expand Down Expand Up @@ -66,8 +65,7 @@ public void MessagesWithoutSurrogatesAreUnchanged(string message)
=> Assert.That(EscapeUnpairedSurrogates(message), Is.EqualTo(message));

private static string EscapeUnpairedSurrogates(string message)
=> (string)typeof(TelnetAppender).Assembly
.GetType("log4net.Appender.Internal.ContentEscape")!
.GetMethod("EscapeUnpairedSurrogates", BindingFlags.Static | BindingFlags.NonPublic)!
.Invoke(null, [message])!;
=> typeof(TelnetAppender).Assembly
.NonPublicType("log4net.Appender.Internal.ContentEscape")
.Invoke<string>(nameof(EscapeUnpairedSurrogates), [message]);
}
11 changes: 3 additions & 8 deletions src/log4net.Tests/Appender/EventLogAppenderTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#region Apache License
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
Expand All @@ -21,7 +21,6 @@
#if NET462_OR_GREATER

using System.Diagnostics;
using System.Reflection;

using log4net.Appender;
using log4net.Core;
Expand Down Expand Up @@ -114,9 +113,7 @@ public void MessagesWithinTheLimitAreUnchanged()
=> Assert.That(PrepareEventText("field=1\tfield=2", 100), Is.EqualTo("field=1\tfield=2"));

private static string PrepareEventText(string rendered, int maxSize)
=> (string)typeof(EventLogAppender)
.GetMethod("PrepareEventText", BindingFlags.Static | BindingFlags.NonPublic)!
.Invoke(null, [rendered, maxSize])!;
=> typeof(EventLogAppender).Invoke<string>(nameof(PrepareEventText), [rendered, maxSize]);

/// <summary>
/// The limit is a whole record budget: the source is spent from it one character for one, so a
Expand Down Expand Up @@ -152,9 +149,7 @@ public void TheLimitNeverGoesBelowZero()
Is.EqualTo(0));

private static int GetMaxMessageSize(EventLogAppender appender)
=> (int)typeof(EventLogAppender)
.GetMethod("GetMaxMessageSize", BindingFlags.Instance | BindingFlags.NonPublic)!
.Invoke(appender, [])!;
=> appender.Invoke<int>(nameof(GetMaxMessageSize));
}

#endif // NET462_OR_GREATER
13 changes: 3 additions & 10 deletions src/log4net.Tests/Appender/FileAppenderMutexNameTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#region Apache License
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
Expand All @@ -19,7 +19,6 @@

using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;

Expand Down Expand Up @@ -220,14 +219,8 @@ public void ThePlatformDecidesWhetherALongNameIsHashed()
}

private static string MutexNameForPath(string path, string suffix)
=> (string)typeof(FileAppender)
.GetMethod("MutexNameForPath", BindingFlags.NonPublic | BindingFlags.Static,
null, [typeof(string), typeof(string)], null)!
.Invoke(null, [path, suffix])!;
=> typeof(FileAppender).Invoke<string>(nameof(MutexNameForPath), [path, suffix]);

private static string MutexNameForPath(string path, string suffix, int? maxLength)
=> (string)typeof(FileAppender)
.GetMethod("MutexNameForPath", BindingFlags.NonPublic | BindingFlags.Static,
null, [typeof(string), typeof(string), typeof(int?)], null)!
.Invoke(null, [path, suffix, maxLength])!;
=> typeof(FileAppender).Invoke<string>(nameof(MutexNameForPath), [path, suffix, maxLength]);
}
34 changes: 11 additions & 23 deletions src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#region Apache License
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
Expand Down Expand Up @@ -82,9 +82,7 @@ public void EmptyMessageIsUnchanged()
[Test]
public void TheIdentityHandleBelongsToTheProcess()
{
FieldInfo field = typeof(LocalSyslogAppender)
.GetField("_handleToIdentity", BindingFlags.Static | BindingFlags.NonPublic)
?? throw new InvalidOperationException("LocalSyslogAppender._handleToIdentity is missing");
FieldInfo field = typeof(LocalSyslogAppender).NonPublicField("_handleToIdentity");

Assert.That(field.IsStatic, Is.True);
}
Expand Down Expand Up @@ -112,9 +110,7 @@ public void ActivatingTwiceReplacesTheIdentity()
}

private static IntPtr CurrentIdentityHandle()
=> (IntPtr)typeof(LocalSyslogAppender)
.GetField("_handleToIdentity", BindingFlags.Static | BindingFlags.NonPublic)!
.GetValue(null)!;
=> typeof(LocalSyslogAppender).GetFieldValue<IntPtr>("_handleToIdentity");

/// <summary>
/// A newline ends the record for a daemon that writes the message through to a line oriented
Expand Down Expand Up @@ -173,9 +169,8 @@ public void MessagesWithoutPercentSignsAreUnchanged()
public void TheSyslogDeclarationPassesNoVariadicArgument()
{
MethodInfo syslog = typeof(LocalSyslogAppender).Assembly
.GetType("log4net.Util.NativeMethods")!
.GetMethod("syslog", BindingFlags.Static | BindingFlags.NonPublic)
?? throw new InvalidOperationException("NativeMethods.syslog no longer exists - update this test along with it.");
.NonPublicType("log4net.Util.NativeMethods")
.NonPublicMethod("syslog");

Assert.That(syslog.GetParameters().Select(parameter => parameter.ParameterType),
Is.EqualTo(new[] { typeof(int), typeof(string) }));
Expand Down Expand Up @@ -206,23 +201,16 @@ public void ContentThatLooksLikeAFormatStringIsLogged()
}

private static string EscapePercent(string message)
=> (string)typeof(LocalSyslogAppender)
.GetMethod("EscapePercent", BindingFlags.Static | BindingFlags.NonPublic)!
.Invoke(null, [message])!;
=> typeof(LocalSyslogAppender).Invoke<string>(nameof(EscapePercent), [message]);

private static string EscapeNewLines(string message)
=> (string)typeof(LocalSyslogAppender)
.GetMethod("EscapeNewLines", BindingFlags.Static | BindingFlags.NonPublic)!
.Invoke(null, [message])!;
=> typeof(LocalSyslogAppender).Invoke<string>(nameof(EscapeNewLines), [message]);

private static string[] SplitLines(string message)
=> (string[])typeof(LocalSyslogAppender)
.GetMethod("SplitLines", BindingFlags.Static | BindingFlags.NonPublic)!
.Invoke(null, [message])!;
=> typeof(LocalSyslogAppender).Invoke<string[]>(nameof(SplitLines), [message]);

private static string EscapeNulCharacters(string message)
=> (string)typeof(LocalSyslogAppender).Assembly
.GetType("log4net.Appender.Internal.ContentEscape")!
.GetMethod("EscapeNulCharacters", BindingFlags.Static | BindingFlags.NonPublic)!
.Invoke(null, [message])!;
=> typeof(LocalSyslogAppender).Assembly
.NonPublicType("log4net.Appender.Internal.ContentEscape")
.Invoke<string>(nameof(EscapeNulCharacters), [message]);
}
38 changes: 12 additions & 26 deletions src/log4net.Tests/Appender/LockingStreamTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#region Apache License
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
Expand All @@ -19,7 +19,6 @@

using System;
using System.IO;
using System.Reflection;
using System.Text;

using log4net.Appender;
Expand Down Expand Up @@ -73,14 +72,14 @@ public void AnUnmatchedReleaseDoesNotBreakTheNextAcquisition()
object stream = NewLockingStream(model);

// What the footer, close and open paths used to do.
Assert.That(Invoke<bool>(stream, "AcquireLock"), Is.False, "the model was set up to refuse");
Invoke(stream, "ReleaseLock");
Assert.That(stream.Invoke<bool>("AcquireLock"), Is.False, "the model was set up to refuse");
stream.Invoke("ReleaseLock");

model.CanAcquire = true;

Assert.That(Invoke<bool>(stream, "AcquireLock"), Is.True,
Assert.That(stream.Invoke<bool>("AcquireLock"), Is.True,
"the counter went negative, so the stream could never be locked again");
Invoke(stream, "ReleaseLock");
stream.Invoke("ReleaseLock");
Assert.That(model.ReleaseCount, Is.EqualTo(1), "the model lock must be released exactly once");
}

Expand All @@ -91,12 +90,12 @@ public void NestedAcquisitionsReleaseTheModelOnce()
SwitchableLock model = new() { CanAcquire = true };
object stream = NewLockingStream(model);

Assert.That(Invoke<bool>(stream, "AcquireLock"), Is.True);
Assert.That(Invoke<bool>(stream, "AcquireLock"), Is.True);
Invoke(stream, "ReleaseLock");
Assert.That(stream.Invoke<bool>("AcquireLock"), Is.True);
Assert.That(stream.Invoke<bool>("AcquireLock"), Is.True);
stream.Invoke("ReleaseLock");
Assert.That(model.ReleaseCount, Is.EqualTo(0), "still held by the outer acquisition");

Invoke(stream, "ReleaseLock");
stream.Invoke("ReleaseLock");
Assert.That(model.ReleaseCount, Is.EqualTo(1));
}

Expand Down Expand Up @@ -126,24 +125,11 @@ public void RunWithBestEffortLockRunsTheWorkButReleasesOnlyWhatItTook()


private static void SetStream(FileAppender appender, object stream)
=> typeof(FileAppender).GetField("_stream", BindingFlags.Instance | BindingFlags.NonPublic)!
.SetValue(appender, stream);
=> appender.SetFieldValue("_stream", stream);

private static void RunWithBestEffortLock(FileAppender appender, Action action)
=> typeof(FileAppender).GetMethod("RunWithBestEffortLock", BindingFlags.Instance | BindingFlags.NonPublic)!
.Invoke(appender, [action]);
=> appender.Invoke(nameof(RunWithBestEffortLock), [action]);

private static object NewLockingStream(FileAppender.LockingModelBase model)
{
Type type = typeof(FileAppender).GetNestedType("LockingStream", BindingFlags.NonPublic)
?? throw new InvalidOperationException("FileAppender.LockingStream is gone");
return Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
null, [model], null)
?? throw new InvalidOperationException("could not construct a LockingStream");
}

private static void Invoke(object target, string method) => Invoke<object?>(target, method);

private static T Invoke<T>(object target, string method)
=> (T)target.GetType().GetMethod(method)!.Invoke(target, null)!;
=> typeof(FileAppender).NonPublicNestedType("LockingStream").Construct<object>([model]);
}
19 changes: 8 additions & 11 deletions src/log4net.Tests/Appender/UdpAppenderTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#region Apache License
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
Expand All @@ -19,7 +19,6 @@

using System;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net.Appender;
using log4net.Tests.Appender.Internal;
Expand All @@ -36,10 +35,8 @@ public sealed class UdpAppenderTest
private const string Marker = "...[truncated]";

/// <summary>Calls the internal encoder the way <c>Append</c> does.</summary>
private static byte[] Encode(UdpAppender appender, string message)
=> (byte[])typeof(UdpAppender)
.GetMethod("GetDatagramBytes", BindingFlags.Instance | BindingFlags.NonPublic)!
.Invoke(appender, [message])!;
private static byte[] GetDatagramBytes(UdpAppender appender, string message)
=> appender.Invoke<byte[]>(nameof(GetDatagramBytes), [message]);

/// <summary>The maximum UDP payload of an IPv4 packet, measured as the first size the socket rejects minus one.</summary>
[Test]
Expand All @@ -59,7 +56,7 @@ public void AMessageThatFitsIsEncodedUnchanged()
{
UdpAppender appender = new() { Encoding = Encoding.UTF8 };

Assert.That(Encode(appender, "hello"), Is.EqualTo(Encoding.UTF8.GetBytes("hello")));
Assert.That(GetDatagramBytes(appender, "hello"), Is.EqualTo(Encoding.UTF8.GetBytes("hello")));
}

/// <summary>An event of exactly the limit still fits, so nothing is cut and nothing reported.</summary>
Expand All @@ -70,7 +67,7 @@ public void AMessageOfExactlyTheLimitIsEncodedUnchanged()
RecordingErrorHandler errorHandler = new();
appender.ErrorHandler = errorHandler;

byte[] datagram = Encode(appender, new string('a', 512));
byte[] datagram = GetDatagramBytes(appender, new string('a', 512));

Assert.That(datagram, Is.EqualTo(Encoding.ASCII.GetBytes(new string('a', 512))));
Assert.That(errorHandler.Messages, Is.Empty);
Expand All @@ -86,7 +83,7 @@ public void AnOversizeMessageIsTruncatedInsteadOfLost()
RecordingErrorHandler errorHandler = new();
appender.ErrorHandler = errorHandler;

byte[] datagram = Encode(appender, new string('a', 1000));
byte[] datagram = GetDatagramBytes(appender, new string('a', 1000));

Assert.That(datagram, Has.Length.EqualTo(512));
Assert.That(Encoding.ASCII.GetString(datagram), Does.EndWith(Marker));
Expand All @@ -100,7 +97,7 @@ public void TruncationDoesNotSplitAMultiByteCharacter()
UdpAppender appender = new() { Encoding = Encoding.UTF8, MaxDatagramSize = 513 };
appender.ErrorHandler = new RecordingErrorHandler();

string decoded = Encoding.UTF8.GetString(Encode(appender, new string('\u00e4', 1000)));
string decoded = Encoding.UTF8.GetString(GetDatagramBytes(appender, new string('\u00e4', 1000)));

// 513 bytes hold the 14 byte marker and 249 of the two byte characters.
Assert.That(decoded, Is.EqualTo(new string('\u00e4', 249) + Marker));
Expand All @@ -113,7 +110,7 @@ public void TruncationDoesNotSplitASurrogatePair()
UdpAppender appender = new() { Encoding = Encoding.UTF8, MaxDatagramSize = 515 };
appender.ErrorHandler = new RecordingErrorHandler();

string decoded = Encoding.UTF8.GetString(Encode(appender, string.Concat(Enumerable.Repeat("\U0001f600", 1000))));
string decoded = Encoding.UTF8.GetString(GetDatagramBytes(appender, string.Concat(Enumerable.Repeat("\U0001f600", 1000))));

Assert.That(decoded, Does.EndWith(Marker));
Assert.That(decoded, !Contains.Substring("\ufffd").Using(StringComparison.Ordinal));
Expand Down
7 changes: 2 additions & 5 deletions src/log4net.Tests/Config/XmlConfiguratorTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#region Apache License
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
Expand All @@ -20,7 +20,6 @@
#if NET8_0_OR_GREATER
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using log4net.Config;
using log4net.Repository;
Expand Down Expand Up @@ -49,9 +48,7 @@ public void ConfigureWithUnkownConfigFile()
List<LogLog> configurationMessages = [];

using LogLog.LogReceivedAdapter _ = new(configurationMessages);
typeof(XmlConfigurator)
.GetMethod("InternalConfigure", BindingFlags.NonPublic | BindingFlags.Static, [typeof(ILoggerRepository), getConfigSection.GetType()])!
.Invoke(null, [repository, getConfigSection]);
typeof(XmlConfigurator).Invoke("InternalConfigure", [repository, getConfigSection]);

Assert.That(configurationMessages, Has.Count.EqualTo(1));
Assert.That(configurationMessages[0].Message, Contains.Substring(SystemInfo.EntryAssemblyLocation + ".config"));
Expand Down
5 changes: 1 addition & 4 deletions src/log4net.Tests/Core/LevelMappingTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@

using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using log4net.Core;
using log4net.Util;
using NUnit.Framework;
Expand Down Expand Up @@ -77,9 +76,7 @@ public void SortEntriesTest()
List<MappingEntry> withoutDuplicates = unsorted.GroupBy(entry => entry.Level!.Value)
.Select(group => group.Last()).ToList();

List<LevelMappingEntry> sorted = (List<LevelMappingEntry>)typeof(LevelMapping)
.GetMethod("SortEntries", BindingFlags.NonPublic | BindingFlags.Instance)!
.Invoke(mapping, [])!;
List<LevelMappingEntry> sorted = mapping.Invoke<List<LevelMappingEntry>>("SortEntries");

Assert.That(sorted, Is.EquivalentTo(withoutDuplicates));
Assert.That(sorted, Is.Not.EqualTo(withoutDuplicates).AsCollection);
Expand Down
6 changes: 2 additions & 4 deletions src/log4net.Tests/Core/LoggingEventTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#region Apache License
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
Expand All @@ -19,7 +19,6 @@

using System;
using System.Globalization;
using System.Reflection;
#if NET462_OR_GREATER
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
Expand Down Expand Up @@ -135,8 +134,7 @@ public void ReviseThreadNameTest()

static string ReviseThreadName(string? name)
{
return (string)typeof(LoggingEvent).GetMethod(nameof(ReviseThreadName),
BindingFlags.Static | BindingFlags.NonPublic)!.Invoke(null, [name])!;
return typeof(LoggingEvent).Invoke<string>(nameof(ReviseThreadName), [name]);
}

static void AssertIsCurrentThreadId(string name)
Expand Down
Loading
Loading