Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 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
75 changes: 75 additions & 0 deletions ExtractorUtils.Test/unit/CallbackUtilTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#nullable enable
using System;
using System.Threading;
using System.Threading.Tasks;
using Cognite.Extractor.Utils;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;

namespace ExtractorUtils.Test.Unit
{
/// <summary>
/// Test double for CogniteDestination that doesn't require CogniteSdk.Client
/// </summary>
internal class TestCogniteDestination : CogniteDestination
{
public TestCogniteDestination()
: base(null!, new NullLogger<CogniteDestination>(), new CogniteConfig { Project = "test-project" })
{
}
}

public class CallbackUtilTest
{
private static CogniteDestination GetCogniteDestination()
{
return new TestCogniteDestination();
}

[Fact]
public async Task TryCallWithMissingConfiguration_ReturnsFalseAndLogsWarning()
{
// Arrange
var destination = GetCogniteDestination();
var mockLogger = new Mock<ILogger>();
var config = new FunctionCallConfig(); // No ExternalId or Id
var wrapper = new FunctionCallWrapper<string>(destination, config, mockLogger.Object);

// Act
var result = await wrapper.TryCall("test-argument", CancellationToken.None);

// Assert
Assert.False(result);
mockLogger.Verify(
x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString()!.Contains("Missing function configuration")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
}

[Theory]
[InlineData("test-function-id", null)]
[InlineData(null, 12345L)]
[InlineData("test-function-id", 12345L)]
public async Task TryCallWithValidConfiguration_ReturnsTrue(string? externalId, long? id)
{
// Arrange
var destination = GetCogniteDestination();
var config = new FunctionCallConfig { ExternalId = externalId, Id = id };
var wrapper = new FunctionCallWrapper<string>(destination, config, null);

// Act
// Note: The stub destination always returns true for function calls.
// If the underlying function's behavior changes, this test will need to be updated.
var result = await wrapper.TryCall("test-argument", CancellationToken.None);

// Assert
Assert.True(result);
}
}
}
108 changes: 107 additions & 1 deletion ExtractorUtils.Test/unit/LoggingTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using Xunit;
using Cognite.Extractor.Logging;
using Cognite.Extractor.Utils;
using Serilog;

namespace ExtractorUtils.Test.Unit
{
Expand Down Expand Up @@ -129,5 +128,112 @@ public static void TestLogLevel()
logger.LogTrace("This is a trace message with {SideEffect}", sideEffect);
Assert.Equal(4, sideEffect.logCount); // should not be evaluated
}

private static ServiceCollection ConfigureLoggerService(string logType, string level = null)
{
var services = new ServiceCollection();
var loggerConfig = new LoggerConfig();

switch (logType)
{
case "console":
loggerConfig.Console = new ConsoleConfig { Level = level ?? "information" };
break;
case "file":
loggerConfig.File = new FileConfig { Level = level ?? "warning", Path = "test.log" };
break;
case "trace-listener":
loggerConfig.TraceListener = new TraceListenerConfig { Level = level ?? "error" };
break;
}

services.AddSingleton(loggerConfig);
services.AddLogger();
return services;
}

[Theory]
[InlineData("console")]
[InlineData("file")]
[InlineData("trace-listener")]
public void TestLogger_WithDifferentLogTypes(string logType)
{
var services = ConfigureLoggerService(logType);

using (var provider = services.BuildServiceProvider())
{
var logger = provider.GetRequiredService<ILogger<LoggingTest>>();

Assert.NotNull(logger);
logger.LogWarning("Test log message");
} // provider is disposed here, which flushes async logs

// Assert and cleanup test.log file if created by file logger
if (logType == "file")
{
// Wait a bit for async logging to complete
System.Threading.Thread.Sleep(100);
// The file logger uses rolling interval, so we need to find files matching the pattern
var logFiles = Directory.GetFiles(".", "test*.log");
Assert.NotEmpty(logFiles);
foreach (var logFile in logFiles)
{
File.Delete(logFile);
}
}
}

[Theory]
[InlineData("console", "debug")]
[InlineData("console", "information")]
[InlineData("file", "warning")]
[InlineData("trace-listener", "error")]
public void TestLogger_WithTypeAndLevel(string configType, string level)
{
var services = ConfigureLoggerService(configType, level);

using (var provider = services.BuildServiceProvider())
{
var logger = provider.GetRequiredService<ILogger<LoggingTest>>();
Assert.NotNull(logger);

// Verify the logger respects the configured level using side effects
// Note: trace-listener alone falls back to default logger, so we only verify console and file
if (configType != "trace-listener")
{
var sideEffect = new LogSideEffect();
logger.LogDebug("Debug: {SideEffect}", sideEffect);
logger.LogInformation("Info: {SideEffect}", sideEffect);
logger.LogWarning("Warning: {SideEffect}", sideEffect);
logger.LogError("Error: {SideEffect}", sideEffect);

// Verify only messages at or above the configured level were evaluated
int expectedCount = level switch
{
"debug" => 4, // debug, info, warning, error
"information" => 3, // info, warning, error
"warning" => 2, // warning, error
"error" => 1, // error only
_ => 0
};
Assert.Equal(expectedCount, sideEffect.logCount);
}
else
{
// For trace-listener, just verify it doesn't throw
logger.LogError("Test log message");
}
} // provider is disposed here

// Cleanup file if created by file logger
if (configType == "file")
{
var logFile = "test.log";
if (File.Exists(logFile))
{
File.Delete(logFile);
}
}
}
}
}
Loading