From 61bc139e51b81055a06f0270bf23b8f9c42644cf Mon Sep 17 00:00:00 2001 From: Gennady Pundikov Date: Fri, 15 Nov 2024 12:44:02 +0300 Subject: [PATCH] Refactor logging --- src/ApiCodeGenerator.Abstraction/ILogger.cs | 6 ++-- src/ApiCodeGenerator.Core/GenerationTask.cs | 36 ++++++++++--------- src/ApiCodeGenerator.Core/LogCodes.cs | 14 ++++++++ .../NswagDocument/PreprocessorHelper.cs | 16 +++++++-- .../Console/ConsoleLogAdapter.cs | 6 ++-- .../Task/MSBuildLogger.cs | 12 +++---- .../AsyncApiContentGeneratorTests.cs | 36 +++++++++---------- .../Infrastructure/FakeTextPreprocessor.cs | 2 +- .../GeneratorTests.cs | 32 ++++++++--------- .../PreprocessorHelperTests.cs | 7 ++-- .../ContentGeneratorFactoryTests.cs | 2 +- .../Infrastructure/FakeTextPreprocessor.cs | 2 +- 12 files changed, 101 insertions(+), 70 deletions(-) create mode 100644 src/ApiCodeGenerator.Core/LogCodes.cs diff --git a/src/ApiCodeGenerator.Abstraction/ILogger.cs b/src/ApiCodeGenerator.Abstraction/ILogger.cs index 714fb9a..5f8968f 100644 --- a/src/ApiCodeGenerator.Abstraction/ILogger.cs +++ b/src/ApiCodeGenerator.Abstraction/ILogger.cs @@ -6,10 +6,10 @@ namespace ApiCodeGenerator.Abstraction { public interface ILogger { - void LogError(string? sourceFile, string message, params object[] messageArgs); + void LogError(string? code, string? sourceFile, string message, params object[] messageArgs); - void LogMessage(string message, params object[] messageArgs); + void LogMessage(string? code, string? sourceFile, string message, params object[] messageArgs); - void LogWarning(string? sourceFile, string message, params object[] messageArgs); + void LogWarning(string? code, string? sourceFile, string message, params object[] messageArgs); } } diff --git a/src/ApiCodeGenerator.Core/GenerationTask.cs b/src/ApiCodeGenerator.Core/GenerationTask.cs index b848016..3d2d54f 100644 --- a/src/ApiCodeGenerator.Core/GenerationTask.cs +++ b/src/ApiCodeGenerator.Core/GenerationTask.cs @@ -4,14 +4,13 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; -using System.Reflection; -using System.Text; using System.Threading.Tasks; using ApiCodeGenerator.Abstraction; using ApiCodeGenerator.Core.NswagDocument; using ApiCodeGenerator.Core.NswagDocument.Converters; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using static ApiCodeGenerator.Core.LogCodes; namespace ApiCodeGenerator.Core { @@ -69,31 +68,31 @@ internal GenerationTask( /// Генерирует код и сохраняет его в указанный файл. /// /// Путь к файлу настроек генератора. - /// Путь к файлу документа OpenApi. + /// Путь к файлу документа Api. /// Путь к фалу с результатами генерации. /// Перечень пар ключ=значение разделенныз запятой. /// Файл базовых настроек. /// True если процесс генерации успешно завершен. public async Task ExecuteAsync(string nswagFilePath, - string openApiFilePath, + string apiDocumentPath, string outFilePath, string? variables = null, string? baseNswagFilePath = null) { if (!_fileProvider.Exists(nswagFilePath)) { - Log?.LogError(null, "File '{0}' not found.", nswagFilePath); + Log?.LogError(FileNotFound, nswagFilePath, message: "File '{0}' not found.", messageArgs: nswagFilePath); return false; } // System.Diagnostics.Debugger.Launch(); var vars = ParseVariables(variables); - vars["InputJson"] = openApiFilePath; + vars["InputJson"] = apiDocumentPath; vars["OutFile"] = outFilePath; var roVariables = new ReadOnlyDictionary(vars); - Log?.LogMessage("Values of nswag variables"); - Log?.LogMessage(string.Join(Environment.NewLine, vars.Select(_ => $"\t[{_.Key}] = {_.Value}"))); + LogMessage("Values of nswag variables"); + LogMessage(string.Join(Environment.NewLine, vars.Select(_ => $"\t[{_.Key}] = {_.Value}"))); JObject? baseNswagDocument = LoadBaseNswag(baseNswagFilePath); var nswagDocument = _documentFactory.LoadNswagDocument(nswagFilePath, roVariables, baseNswagDocument); @@ -101,13 +100,13 @@ public async Task ExecuteAsync(string nswagFilePath, var generatorSettings = nswagDocument.CodeGenerators.FirstOrDefault(); if (generatorSettings.Key is null) { - Log?.LogWarning(nswagFilePath, "Nswag not contains codeGenerator definition. Skip generation."); + Log?.LogWarning(NotDefineGenerator, nswagFilePath, "Nswag not contains codeGenerator definition. Skip generation."); return true; } if (!_extensions.CodeGenerators.TryGetValue(generatorSettings.Key, out var contentGeneratorFactory)) { - Log?.LogError(nswagFilePath, $"Unable find generator {generatorSettings.Key}. Check package references."); + Log?.LogError(GenNotFound, nswagFilePath, $"Unable find generator {generatorSettings.Key}. Check package references."); return false; } @@ -117,31 +116,31 @@ public async Task ExecuteAsync(string nswagFilePath, { if (context.DocumentReader is null) { - Log?.LogWarning(nswagFilePath, "Source not set. Skip generation."); + Log?.LogWarning(NotSetInput, nswagFilePath, "Source not set. Skip generation."); return true; } try { - Log?.LogMessage($"Use settings: {generatorSettings.Key}"); + LogMessage($"Use settings: {generatorSettings.Key}"); var contentGenerator = await contentGeneratorFactory.Invoke(context); - Log?.LogMessage("Generate content for file '{0}'", outFilePath); + LogMessage("Generate content for file '{0}'", outFilePath); var code = contentGenerator.Generate(); try { - Log?.LogMessage("Write file '{0}'", outFilePath); + LogMessage("Write file '{0}'", outFilePath); await _fileProvider.WriteAllTextAsync(outFilePath, code); } catch (Exception ex) { - Log?.LogError("Unable write file. Error:", ex.Message); + Log?.LogError(WriteFileErr, outFilePath, "Unable write file. Error: {0}", ex.Message); } } catch (InvalidOperationException ex) { - Log?.LogError(nswagFilePath, ex.Message); + Log?.LogError(GenerationErr, nswagFilePath, ex.Message); return false; } @@ -149,6 +148,9 @@ public async Task ExecuteAsync(string nswagFilePath, } return false; + + void LogMessage(string message, params object[] messageArgs) + => Log?.LogMessage(null, nswagFilePath, message, messageArgs); } private async Task CreateGenerationContext( @@ -175,7 +177,7 @@ public async Task ExecuteAsync(string nswagFilePath, if (result is not null && !string.IsNullOrEmpty(result.Error)) { - Log?.LogError(result.FilePath ?? nswagFilePath, result.Error!); + Log?.LogError(DocumentOpenErr, result.FilePath ?? nswagFilePath, result.Error!); return null; } diff --git a/src/ApiCodeGenerator.Core/LogCodes.cs b/src/ApiCodeGenerator.Core/LogCodes.cs new file mode 100644 index 0000000..e74db0c --- /dev/null +++ b/src/ApiCodeGenerator.Core/LogCodes.cs @@ -0,0 +1,14 @@ +namespace ApiCodeGenerator.Core; + +internal static class LogCodes +{ + public const string FileNotFound = "ACG0001"; + public const string GenNotFound = "ACG0002"; + public const string DocumentOpenErr = "ACG0003"; + public const string WriteFileErr = "ACG0004"; + public const string GenerationErr = "ACG0005"; + + public const string NotDefineGenerator = "ACG1001"; + public const string NotSetInput = "ACG1002"; + public const string PreprocSkiped = "ACG1003"; +} diff --git a/src/ApiCodeGenerator.Core/NswagDocument/PreprocessorHelper.cs b/src/ApiCodeGenerator.Core/NswagDocument/PreprocessorHelper.cs index c2feb42..ad4766a 100644 --- a/src/ApiCodeGenerator.Core/NswagDocument/PreprocessorHelper.cs +++ b/src/ApiCodeGenerator.Core/NswagDocument/PreprocessorHelper.cs @@ -51,14 +51,26 @@ public static Preprocessors GetPreprocessors(IExtensions? extensions, IDictionar { var tuple = CreatePreprocessor(processor, method); if (tuple is null) - log?.LogWarning(null, "Method '{0}' skiped, because his signature not like Func.", method.ToString()); + { + log?.LogWarning( + LogCodes.PreprocSkiped, + null, + message: "Method '{0}' skiped, because his signature not like Func.", + messageArgs: [method.ToString()]); + } else + { yield return tuple.Value; + } } } else { - log?.LogWarning(null, "Preprocessor '{0}' skiped, because method 'Process' not found.", name!); + log?.LogWarning( + LogCodes.PreprocSkiped, + null, + message: "Preprocessor '{0}' skiped, because method 'Process' not found.", + messageArgs: [name!]); } } diff --git a/src/ApiCodeGenerator.MSBuild/Console/ConsoleLogAdapter.cs b/src/ApiCodeGenerator.MSBuild/Console/ConsoleLogAdapter.cs index 5923bb5..3675bc1 100644 --- a/src/ApiCodeGenerator.MSBuild/Console/ConsoleLogAdapter.cs +++ b/src/ApiCodeGenerator.MSBuild/Console/ConsoleLogAdapter.cs @@ -9,13 +9,13 @@ namespace ApiCodeGenerator.MSBuild { internal class ConsoleLogAdapter : ILogger { - public void LogError(string? sourceFile, string message, params object[] messageArgs) + public void LogError(string? code, string? sourceFile, string message, params object[] messageArgs) => Console.Error.WriteLine($"{sourceFile}: {string.Format(message, messageArgs)}"); - public void LogMessage(string message, params object[] messageArgs) + public void LogMessage(string? code, string? sourceFile, string message, params object[] messageArgs) => Console.WriteLine($"INFO: {string.Format(message, messageArgs)}"); - public void LogWarning(string? sourceFile, string message, params object[] messageArgs) + public void LogWarning(string? code, string? sourceFile, string message, params object[] messageArgs) => Console.WriteLine($"WARNING {sourceFile}: {string.Format(message, messageArgs)}"); } } diff --git a/src/ApiCodeGenerator.MSBuild/Task/MSBuildLogger.cs b/src/ApiCodeGenerator.MSBuild/Task/MSBuildLogger.cs index e52d618..59c1404 100644 --- a/src/ApiCodeGenerator.MSBuild/Task/MSBuildLogger.cs +++ b/src/ApiCodeGenerator.MSBuild/Task/MSBuildLogger.cs @@ -12,12 +12,12 @@ public MSBuildLogger(TaskLoggingHelper log) _log = log; } - public void LogError(string? sourceFile, string message, params object[] messageArgs) - => _log.LogError(null, null, null, sourceFile, 0, 0, 0, 0, message, messageArgs); + public void LogError(string? errorCode, string? sourceFile, string message, params object[] messageArgs) + => _log.LogError(null, errorCode, null, sourceFile, 0, 0, 0, 0, message, messageArgs); - public void LogMessage(string message, params object[] messageArgs) - => _log.LogMessage(message, messageArgs); + public void LogMessage(string? code, string? sourceFile, string message, params object[] messageArgs) + => _log.LogMessage(null, code, null, sourceFile, 0, 0, 0, 0, Microsoft.Build.Framework.MessageImportance.Normal, message, messageArgs); - public void LogWarning(string? sourceFile, string message, params object[] messageArgs) - => _log.LogWarning(null, null, null, sourceFile, 0, 0, 0, 0, message, messageArgs); + public void LogWarning(string? warningCode, string? sourceFile, string message, params object[] messageArgs) + => _log.LogWarning(null, warningCode, null, sourceFile, 0, 0, 0, 0, message, messageArgs); } diff --git a/test/ApiCodeGenerator.AsyncApi.Tests/AsyncApiContentGeneratorTests.cs b/test/ApiCodeGenerator.AsyncApi.Tests/AsyncApiContentGeneratorTests.cs index 58ef864..38b4d27 100644 --- a/test/ApiCodeGenerator.AsyncApi.Tests/AsyncApiContentGeneratorTests.cs +++ b/test/ApiCodeGenerator.AsyncApi.Tests/AsyncApiContentGeneratorTests.cs @@ -134,7 +134,7 @@ public async Task LoadApiDocument_WithTextPreprocess_Log() Assert.That(apiDocument?.Components?.Schemas, Does.ContainKey(schemaName)); var sch = apiDocument?.Components?.Schemas[schemaName].ToJson(Newtonsoft.Json.Formatting.None); Assert.That(sch, Is.EqualTo("{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"processed\":{}}")); - logger.Verify(l => l.LogWarning(filePath, It.IsAny())); + logger.Verify(l => l.LogWarning(It.IsAny(), filePath, It.IsAny())); } [Test] @@ -181,17 +181,17 @@ private void ValidateDocument(AsyncApiDocument document) .And.ContainKey(channelPrefix + "action.{streetlightId}.dim")); Assert.NotNull(document.Components); - Assert.That(document.Components.Messages, + Assert.That(document.Components?.Messages, Is.Not.Null .And.ContainKey("lightMeasured") .And.ContainKey("turnOnOff") .And.ContainKey("dimLight")); - Assert.That(document.Components.Parameters, + Assert.That(document.Components?.Parameters, Is.Not.Null .And.ContainKey("streetlightId")); - Assert.That(document.Components.Schemas, + Assert.That(document.Components?.Schemas, Is.Not.Null .And.ContainKey("lightMeasuredPayload") .And.ContainKey("turnOnOffPayload") @@ -204,32 +204,32 @@ private void ValidateDocument(AsyncApiDocument document) .And.ContainKey("mtls-connections")); // Resolve $ref in channel defintion - var actualChannel = document.Channels[channelPrefix + "event.{streetlightId}.lighting.measured"]; + var actualChannel = document.Channels?[channelPrefix + "event.{streetlightId}.lighting.measured"]; Assert.That(actualChannel, Is.Not.Null .And.Property("Publish").Not.Null .And.Property("Subscribe").Null); - Assert.That(actualChannel.Parameters, + Assert.That(actualChannel?.Parameters, Is.Not.Null .And.ContainKey("streetlightId")); - Assert.That(actualChannel.Parameters["streetlightId"], + Assert.That(actualChannel?.Parameters["streetlightId"], Is.Not.Null .And.Property("ReferencePath").EqualTo("#/components/parameters/streetlightId") - .And.Property("Reference").EqualTo(document.Components.Parameters["streetlightId"])); - Assert.That(actualChannel.Publish?.Message, + .And.Property("Reference").EqualTo(document.Components?.Parameters["streetlightId"])); + Assert.That(actualChannel?.Publish?.Message, Is.Not.Null .And.Property("ReferencePath").EqualTo("#/components/messages/lightMeasured") - .And.Property("Reference").EqualTo(document.Components.Messages["lightMeasured"])); + .And.Property("Reference").EqualTo(document.Components?.Messages["lightMeasured"])); // Resolve $ref in message definition - var actualMessage = document.Components.Messages["turnOnOff"]; + var actualMessage = document.Components?.Messages["turnOnOff"]; Assert.That(actualMessage, Is.Not.Null); - Assert.That(actualMessage.Payload, + Assert.That(actualMessage?.Payload, Is.Not.Null - .And.Property("Reference").EqualTo(document.Components.Schemas["turnOnOffPayload"])); + .And.Property("Reference").EqualTo(document.Components?.Schemas["turnOnOffPayload"])); // Resolve $ref in schema definition - Assert.That(document.Components.Schemas["turnOnOffPayload"]?.ActualProperties, + Assert.That(document.Components?.Schemas["turnOnOffPayload"]?.ActualProperties, Is.Not.Null .And.ContainKey("command")); @@ -243,12 +243,12 @@ private void ValidateDocument(AsyncApiDocument document) // Resolve $ref in servers Assert.That(document.Servers["mtls-connections"], Is.Not.Null - .And.Property("Reference").EqualTo(document.Components.Servers["mtls-connections"])); + .And.Property("Reference").EqualTo(document.Components?.Servers["mtls-connections"])); // Resolve $ref in server variables Assert.Multiple(() => { - var variables = document.Components.Servers["mtls-connections"].Variables; + var variables = document.Components?.Servers["mtls-connections"].Variables; Assert.That(variables, Is.Not.Null .And.ContainKey("someRefVariable") @@ -256,11 +256,11 @@ private void ValidateDocument(AsyncApiDocument document) Assert.That(variables!["someRefVariable"], Is.Not.Null - .And.Property("Reference").EqualTo(document.Components.ServerVariables["someRefVariable"])); + .And.Property("Reference").EqualTo(document.Components?.ServerVariables["someRefVariable"])); }); //Read server variables - Assert.That(document.Components.ServerVariables["someRefVariable"], + Assert.That(document.Components?.ServerVariables["someRefVariable"], new PredicateConstraint(a => a.Description == "Some ref variable" && a.Enum?.FirstOrDefault() == "def" diff --git a/test/ApiCodeGenerator.AsyncApi.Tests/Infrastructure/FakeTextPreprocessor.cs b/test/ApiCodeGenerator.AsyncApi.Tests/Infrastructure/FakeTextPreprocessor.cs index 05ba3e6..061874e 100644 --- a/test/ApiCodeGenerator.AsyncApi.Tests/Infrastructure/FakeTextPreprocessor.cs +++ b/test/ApiCodeGenerator.AsyncApi.Tests/Infrastructure/FakeTextPreprocessor.cs @@ -37,7 +37,7 @@ public string Process(string data, string? fileName) public string Process(string data, string? fileName, ILogger? logger) { - logger?.LogWarning(fileName, "test"); + logger?.LogWarning(null, fileName, "test"); return Process(data, fileName); } } diff --git a/test/ApiCodeGenerator.Core.Tests/GeneratorTests.cs b/test/ApiCodeGenerator.Core.Tests/GeneratorTests.cs index 71febb9..8c387ec 100644 --- a/test/ApiCodeGenerator.Core.Tests/GeneratorTests.cs +++ b/test/ApiCodeGenerator.Core.Tests/GeneratorTests.cs @@ -47,12 +47,12 @@ public async Task NswagFileNotFound() // Act var res = await task.ExecuteAsync( nswagFilePath: nswagFilePath, - openApiFilePath: NOT_SET, + apiDocumentPath: NOT_SET, outFilePath: NOT_SET); // Assert Assert.False(res); - loggerMock.Verify(l => l.LogError(null, "File '{0}' not found.", nswagFilePath)); + loggerMock.Verify(l => l.LogError(LogCodes.FileNotFound, It.IsAny(), "File '{0}' not found.", nswagFilePath)); } // разбор переменных @@ -73,13 +73,13 @@ public async Task ParseVariables() //Act _ = await task.ExecuteAsync( nswagFilePath: "exists.nswag", - openApiFilePath: NOT_SET, + apiDocumentPath: NOT_SET, outFilePath: OutFilePath, variables: "TestVar=TestValue,TestVar2 = TestValue2, TestVar_3 =TestValue3"); //Assert Assert.NotNull(variables); - loggerMock.Verify(be => be.LogError(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); + loggerMock.Verify(be => be.LogError(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); Assert.That(variables, Does.ContainKey("TestVar").WithValue("TestValue") .And.ContainKey("TestVar2").WithValue("TestValue2") @@ -108,12 +108,12 @@ public async Task SourceJsonNotSet(string nswagFileName) //Act var result = await task.ExecuteAsync( nswagFilePath: nswagFileName, - openApiFilePath: NOT_SET, + apiDocumentPath: NOT_SET, outFilePath: NOT_SET); //Assert Assert.True(result); - loggerMock.Verify(l => l.LogWarning(nswagFileName, expectedError, It.IsAny()), Times.Once()); + loggerMock.Verify(l => l.LogWarning(It.IsAny(), nswagFileName, expectedError, It.IsAny()), Times.Once()); } // обработка ошибки загрузки документа Api @@ -137,12 +137,12 @@ public async Task ApiDocumentLoadError() //Act var result = await task.ExecuteAsync( nswagFilePath: @"exists.nswag", - openApiFilePath: OpenApiFilePath, + apiDocumentPath: OpenApiFilePath, outFilePath: NOT_SET); //Assert Assert.False(result); - loggerMock.Verify(l => l.LogError(It.IsAny(), expectedError, new string[0]), Times.Once()); + loggerMock.Verify(l => l.LogError(It.IsAny(), It.IsAny(), expectedError, new string[0]), Times.Once()); } // проверка загрузки генератора содержимого и его последующего вызова. @@ -165,7 +165,7 @@ public async Task RunCodeGeneration() // Act var result = await task.ExecuteAsync( nswagFilePath: @"csharp.nswag", - openApiFilePath: NOT_SET, + apiDocumentPath: NOT_SET, outFilePath: OutFilePath); // Assert @@ -196,7 +196,7 @@ public async Task RunCSharpCodeGenerationFromJsonSchema() // Act var result = await task.ExecuteAsync( nswagFilePath: @"csharp.nswag", - openApiFilePath: NOT_SET, + apiDocumentPath: NOT_SET, outFilePath: OutFilePath); // Assert @@ -224,11 +224,11 @@ public async Task RunCustomCodeGenerator() // Act var result = await task.ExecuteAsync( nswagFilePath: @"csharp.nswag", - openApiFilePath: NOT_SET, + apiDocumentPath: NOT_SET, outFilePath: OutFilePath); // Assert - loggerMock.Verify(be => be.LogError(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + loggerMock.Verify(be => be.LogError(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); Assert.True(result); var expectedCode = FakeCodeGenerator.FileContent; _fileProviderMock.Verify(fp => fp.WriteAllTextAsync(It.Is(v => v == OutFilePath), expectedCode), Times.Once); @@ -260,12 +260,12 @@ public async Task UseVariablesInSettings() // Act var result = await task.ExecuteAsync( nswagFilePath: @"csharp.nswag", - openApiFilePath: NOT_SET, + apiDocumentPath: NOT_SET, outFilePath: OutFilePath, variables: $"var={expectedClassName}"); // Assert - loggerMock.Verify(be => be.LogError(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + loggerMock.Verify(be => be.LogError(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); Assert.True(result); Assert.NotNull(codeGen); Assert.IsInstanceOf(codeGen); @@ -306,11 +306,11 @@ public async Task UseAdditionalVariablesInSettings() // Act var result = await task.ExecuteAsync( nswagFilePath: @"csharp.nswag", - openApiFilePath: NOT_SET, + apiDocumentPath: NOT_SET, outFilePath: OutFilePath); // Assert - loggerMock.Verify(be => be.LogError(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + loggerMock.Verify(be => be.LogError(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); Assert.True(result); Assert.NotNull(codeGen); Assert.IsInstanceOf(codeGen); diff --git a/test/ApiCodeGenerator.Core.Tests/PreprocessorHelperTests.cs b/test/ApiCodeGenerator.Core.Tests/PreprocessorHelperTests.cs index f10a054..f1824ed 100644 --- a/test/ApiCodeGenerator.Core.Tests/PreprocessorHelperTests.cs +++ b/test/ApiCodeGenerator.Core.Tests/PreprocessorHelperTests.cs @@ -95,7 +95,8 @@ public void GetPreprocessors_Throw_NotFound() }; var ex = Assert.Throws(() => PreprocessorHelper.GetPreprocessors(extensions, ppDeclartaions, null)); - Assert.AreEqual("Preprocessor with name 'pp' not registred.", ex.Message); + Assert.NotNull(ex); + Assert.AreEqual("Preprocessor with name 'pp' not registred.", ex!.Message); } [TestCase(typeof(PreprocessorInvalidCtor))] @@ -113,7 +114,8 @@ public void GetPreprocessors_Throw_CtorInvalid(Type procType) }; var ex = Assert.Throws(() => PreprocessorHelper.GetPreprocessors(extensions, ppDeclartaions, null)); - Assert.AreEqual("Constructor with one or zero parameters not found for preprocessor 'pp'", ex.Message); + Assert.NotNull(ex); + Assert.AreEqual("Constructor with one or zero parameters not found for preprocessor 'pp'", ex!.Message); } [Test] @@ -135,6 +137,7 @@ public void GetPreprocessors_LogWarning_SkipProcessMethod() Assert.AreEqual(0, processors.Count); loggerMock.Verify(l => l.LogWarning( + It.IsAny(), It.IsAny(), "Method '{0}' skiped, because his signature not like Func.", new object[] { "System.String Process()" })); diff --git a/test/ApiCodeGenerator.OpenApi.Tests/ContentGeneratorFactoryTests.cs b/test/ApiCodeGenerator.OpenApi.Tests/ContentGeneratorFactoryTests.cs index 2e9ce91..a2e8dc0 100644 --- a/test/ApiCodeGenerator.OpenApi.Tests/ContentGeneratorFactoryTests.cs +++ b/test/ApiCodeGenerator.OpenApi.Tests/ContentGeneratorFactoryTests.cs @@ -124,7 +124,7 @@ public async Task LoadOpenApiDocument_WithTextPreprocess_Log() Assert.That(openApiDocument?.Definitions, Does.ContainKey(schemaName)); var sch = openApiDocument?.Definitions[schemaName].ToJson(Newtonsoft.Json.Formatting.None); Assert.That(sch, Is.EqualTo("{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"additionalProperties\":false,\"processed\":{}}")); - logger.Verify(l => l.LogWarning(filePath, It.IsAny())); + logger.Verify(l => l.LogWarning(It.IsAny(), filePath, It.IsAny(), It.IsAny())); } [Test] diff --git a/test/ApiCodeGenerator.OpenApi.Tests/Infrastructure/FakeTextPreprocessor.cs b/test/ApiCodeGenerator.OpenApi.Tests/Infrastructure/FakeTextPreprocessor.cs index 7feedc3..38a8310 100644 --- a/test/ApiCodeGenerator.OpenApi.Tests/Infrastructure/FakeTextPreprocessor.cs +++ b/test/ApiCodeGenerator.OpenApi.Tests/Infrastructure/FakeTextPreprocessor.cs @@ -26,7 +26,7 @@ public string Process(string data, string? fileName) public string Process(string data, string? fileName, ILogger? logger) { - logger?.LogWarning(fileName, "test"); + logger?.LogWarning(null, fileName, "test"); return Process(data, fileName); } }