cs-codex-dist-tests/Logging/TestLog.cs

76 lines
2.1 KiB
C#
Raw Normal View History

2023-04-12 11:53:55 +00:00
using NUnit.Framework;
using Utils;
namespace Logging
{
public class TestLog
{
private readonly NumberSource subfileNumberSource = new NumberSource(0);
private readonly LogFile file;
private readonly DateTime now;
2023-04-12 14:06:04 +00:00
private readonly LogConfig config;
2023-04-12 11:53:55 +00:00
2023-04-12 14:06:04 +00:00
public TestLog(LogConfig config)
2023-04-12 11:53:55 +00:00
{
2023-04-12 14:06:04 +00:00
this.config = config;
2023-04-12 11:53:55 +00:00
now = DateTime.UtcNow;
var name = GetTestName();
2023-04-12 14:06:04 +00:00
file = new LogFile(config, now, name);
2023-04-12 11:53:55 +00:00
Log($"Begin: {name}");
}
public void Log(string message)
{
file.Write(message);
}
public void Error(string message)
{
Log($"[ERROR] {message}");
}
public void EndTest()
{
var result = TestContext.CurrentContext.Result;
Log($"Finished: {GetTestName()} = {result.Outcome.Status}");
if (!string.IsNullOrEmpty(result.Message))
{
Log(result.Message);
Log($"{result.StackTrace}");
}
if (result.Outcome.Status == NUnit.Framework.Interfaces.TestStatus.Failed)
{
RenameLogFile();
}
}
private void RenameLogFile()
{
file.ConcatToFilename("_FAILED");
}
public LogFile CreateSubfile(string ext = "log")
{
2023-04-12 14:06:04 +00:00
return new LogFile(config, now, $"{GetTestName()}_{subfileNumberSource.GetNextNumber().ToString().PadLeft(6, '0')}", ext);
2023-04-12 11:53:55 +00:00
}
private static string GetTestName()
{
var test = TestContext.CurrentContext.Test;
var className = test.ClassName!.Substring(test.ClassName.LastIndexOf('.') + 1);
var args = FormatArguments(test);
return $"{className}.{test.MethodName}{args}";
}
private static string FormatArguments(TestContext.TestAdapter test)
{
if (test.Arguments == null || !test.Arguments.Any()) return "";
return $"[{string.Join(',', test.Arguments)}]";
}
}
}