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
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ csharp_style_prefer_null_check_over_type_check = true : suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true : suggestion

# primary constructors (C# 12+)
csharp_style_prefer_primary_constructors = true : suggestion
csharp_style_prefer_primary_constructors = true : warning

# collection expressions (C# 12+)
dotnet_style_prefer_collection_expression = true : suggestion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public void RecordDeliveryAttempt_UpdatesDeliveryStatus()
var attempt = new DeliveryAttempt
{
AttemptNumber = 1,
AttemptTime = DateTime.UtcNow,
AttemptTime = DateTimeOffset.UtcNow,
Outcome = DeliveryOutcome.Success,
HttpStatusCode = 200,
};
Expand All @@ -136,7 +136,7 @@ public void RecordDeliveryAttempt_NonExistingEvent_DoesNotThrow()
var attempt = new DeliveryAttempt
{
AttemptNumber = 1,
AttemptTime = DateTime.UtcNow,
AttemptTime = DateTimeOffset.UtcNow,
Outcome = DeliveryOutcome.Success,
};

Expand Down Expand Up @@ -283,7 +283,7 @@ private static SimulatorEvent CreateTestEvent(string id)
Id = id,
Subject = "/test/subject",
EventType = "Test.EventType",
EventTime = DateTime.UtcNow.ToString("o"),
EventTime = DateTimeOffset.UtcNow.ToString("o"),
DataVersion = "1.0",
Data = new { Property = "Value" },
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ private static EventHistoryRecord CreateTestRecord(string id, string topicName =
EventType = "Test.EventType",
Subject = "/test/subject",
Source = "/test/source",
EventTime = DateTime.UtcNow.ToString("o"),
EventTime = DateTimeOffset.UtcNow.ToString("o"),
InputSchema = EventSchema.EventGridSchema,
PayloadJson = "{}",
};
Expand Down
31 changes: 31 additions & 0 deletions src/AzureEventGridSimulator.Tests/Helpers/FakeTimeProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
namespace AzureEventGridSimulator.Tests.Helpers;

/// <summary>
/// A fake TimeProvider for testing time-dependent code.
/// Allows tests to control the current time for deterministic behavior.
/// </summary>
public class FakeTimeProvider(DateTimeOffset startTime) : TimeProvider
{
private DateTimeOffset _utcNow = startTime;

public override DateTimeOffset GetUtcNow()
{
return _utcNow;
}

/// <summary>
/// Sets the current time to a specific value.
/// </summary>
public void SetUtcNow(DateTimeOffset value)
{
_utcNow = value;
}

/// <summary>
/// Advances the current time by the specified duration.
/// </summary>
public void Advance(TimeSpan duration)
{
_utcNow = _utcNow.Add(duration);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ public void GivenEventGridEvent_WhenSerializedAsCloudEvent_ThenConvertedCorrectl
EventType = "Test.Event.Type",
EventTime = "2025-01-15T10:30:00Z",
Data = new { Property = "Value" },
Topic = "/test/topic",
};
eventGridEvent.SetTopic("/test/topic");

var simulatorEvent = SimulatorEvent.FromEventGridEvent(eventGridEvent);
var json = _formatter.Serialize(simulatorEvent);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ public void GivenEventGridEvent_WhenWrappedInSimulatorEvent_ThenPropertiesMapped
EventTime = "2025-01-15T10:30:00Z",
Data = new { Property = "Value" },
DataVersion = "1.0",
Topic = "/test/topic",
};
eventGridEvent.SetTopic("/test/topic");

var simulatorEvent = SimulatorEvent.FromEventGridEvent(eventGridEvent);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ private static SimulatorEvent CreateTestEventGridEvent(string id)
Id = id,
Subject = "/test/subject",
EventType = "Test.EventType",
EventTime = DateTime.UtcNow.ToString("o"),
EventTime = DateTimeOffset.UtcNow.ToString("o"),
DataVersion = "1.0",
Data = new { Property = "Value" },
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class ValidateSubscriptionCommandHandlerTests
public ValidateSubscriptionCommandHandlerTests()
{
_logger = Substitute.For<ILogger<ValidateSubscriptionCommandHandler>>();
_handler = new ValidateSubscriptionCommandHandler(_logger);
_handler = new ValidateSubscriptionCommandHandler(TimeProvider.System, _logger);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace AzureEventGridSimulator.Tests.UnitTests.EventGrid;
[Trait("Category", "unit")]
public class EventGridSchemaFormatterTests
{
private readonly EventGridSchemaFormatter _formatter = new();
private readonly EventGridSchemaFormatter _formatter = new(TimeProvider.System);

[Fact]
public void GivenEventGridEvent_WhenSerialized_ThenJsonContainsAllFields()
Expand All @@ -22,9 +22,9 @@ public void GivenEventGridEvent_WhenSerialized_ThenJsonContainsAllFields()
EventTime = "2025-01-15T10:30:00Z",
Data = new { Property = "Value" },
DataVersion = "1.0",
Topic = "/test/topic",
MetadataVersion = "1",
};
eventGridEvent.SetTopic("/test/topic");

var simulatorEvent = SimulatorEvent.FromEventGridEvent(eventGridEvent);
var json = _formatter.Serialize(simulatorEvent);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Text.Json;
using AzureEventGridSimulator.Domain.Entities;
using Shouldly;
using Xunit;
Expand Down Expand Up @@ -258,36 +259,55 @@ string metadataVersion
public void GivenEventWithNonNullTopic_WhenValidated_ThenExceptionThrown()
{
// Topic should be null/empty when publishing - it's set by the service
var eventGridEvent = new EventGridEvent
{
Id = "test-id-123",
Subject = "/test/subject",
EventType = "Test.EventType",
EventTime = "2025-01-15T10:30:00Z",
Topic = "/subscriptions/some/topic",
};

var exception = Should.Throw<InvalidOperationException>(() => eventGridEvent.Validate());
// Use JSON deserialization to simulate a publisher sending a Topic value
var json = """
{
"id": "test-id-123",
"subject": "/test/subject",
"eventType": "Test.EventType",
"eventTime": "2025-01-15T10:30:00Z",
"topic": "/subscriptions/some/topic"
}
""";
var eventGridEvent = JsonSerializer.Deserialize<EventGridEvent>(json);

var exception = Should.Throw<InvalidOperationException>(() => eventGridEvent!.Validate());
exception.Message.ShouldContain("Topic");
}

[Theory]
[InlineData(null)]
[InlineData("")]
public void GivenEventWithNullOrEmptyTopic_WhenValidated_ThenNoExceptionThrown(string topic)
[Fact]
public void GivenEventWithNullTopic_WhenValidated_ThenNoExceptionThrown()
{
// Topic defaults to null when not set
var eventGridEvent = new EventGridEvent
{
Id = "test-id-123",
Subject = "/test/subject",
EventType = "Test.EventType",
EventTime = "2025-01-15T10:30:00Z",
Topic = topic,
};

Should.NotThrow(() => eventGridEvent.Validate());
}

[Fact]
public void GivenEventWithEmptyTopic_WhenValidated_ThenNoExceptionThrown()
{
// Use JSON deserialization to set empty Topic
var json = """
{
"id": "test-id-123",
"subject": "/test/subject",
"eventType": "Test.EventType",
"eventTime": "2025-01-15T10:30:00Z",
"topic": ""
}
""";
var eventGridEvent = JsonSerializer.Deserialize<EventGridEvent>(json);

Should.NotThrow(() => eventGridEvent!.Validate());
}

[Fact]
public void GivenEventWithNullData_WhenValidated_ThenNoExceptionThrown()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,31 @@ namespace AzureEventGridSimulator.Tests.UnitTests.Filtering;
[Trait("Category", "unit")]
public class AdvancedFilterEventAcceptanceTests
{
private static readonly EventGridEvent _gridEvent = new()
private static readonly EventGridEvent _gridEvent = CreateTestEvent();

private static EventGridEvent CreateTestEvent()
{
Id = "EventId",
Data = new
var evt = new EventGridEvent
{
NumberValue = 1,
IsTrue = true,
Name = "StringValue",
DoubleValue = 0.12345d,
NumberMaxValue = ulong.MaxValue,
SubObject = new { Id = 1, Name = "Test" },
},
DataVersion = "5.0",
EventTime = DateTime.UtcNow.ToString("O"),
EventType = "this.is.a.test.event.type",
MetadataVersion = "2.3.4",
Subject = "TheEventSubject",
Topic = "THE_EVENT_TOPIC",
};
Id = "EventId",
Data = new
{
NumberValue = 1,
IsTrue = true,
Name = "StringValue",
DoubleValue = 0.12345d,
NumberMaxValue = ulong.MaxValue,
SubObject = new { Id = 1, Name = "Test" },
},
DataVersion = "5.0",
EventTime = DateTimeOffset.UtcNow.ToString("O"),
EventType = "this.is.a.test.event.type",
MetadataVersion = "2.3.4",
Subject = "TheEventSubject",
};
evt.SetTopic("THE_EVENT_TOPIC");
return evt;
}

[Theory]
[ClassData(typeof(PositiveFilterTestCaseContainer))]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public void GivenValidAegSasToken_WhenValidated_ThenReturnsTrue()
var token = GenerateValidSasToken(
ValidTopicKey,
"http://localhost",
DateTime.UtcNow.AddMinutes(5)
DateTimeOffset.UtcNow.AddMinutes(5)
);
var headers = new HeaderDictionary { { Constants.AegSasTokenHeader, token } };

Expand All @@ -29,7 +29,7 @@ public void GivenExpiredAegSasToken_WhenValidated_ThenReturnsFalse()
var token = GenerateValidSasToken(
ValidTopicKey,
"http://localhost",
DateTime.UtcNow.AddMinutes(-5)
DateTimeOffset.UtcNow.AddMinutes(-5)
);
var headers = new HeaderDictionary { { Constants.AegSasTokenHeader, token } };

Expand All @@ -44,7 +44,7 @@ public void GivenAegSasTokenWithWrongSignature_WhenValidated_ThenReturnsFalse()
var token = GenerateValidSasToken(
"WrongKey123456789012345=",
"http://localhost",
DateTime.UtcNow.AddMinutes(5)
DateTimeOffset.UtcNow.AddMinutes(5)
);
var headers = new HeaderDictionary { { Constants.AegSasTokenHeader, token } };

Expand All @@ -59,7 +59,7 @@ public void GivenInvalidAegSasToken_WhenValidated_ThenLogsError()
var token = GenerateValidSasToken(
"WrongKey123456789012345=",
"http://localhost",
DateTime.UtcNow.AddMinutes(5)
DateTimeOffset.UtcNow.AddMinutes(5)
);
var headers = new HeaderDictionary { { Constants.AegSasTokenHeader, token } };

Expand All @@ -82,7 +82,7 @@ public void GivenAegSasTokenWithDifferentCase_WhenValidated_ThenHeaderIsFoundCas
var token = GenerateValidSasToken(
ValidTopicKey,
"http://localhost",
DateTime.UtcNow.AddMinutes(5)
DateTimeOffset.UtcNow.AddMinutes(5)
);
var headers = new HeaderDictionary { { "AEG-SAS-TOKEN", token } };

Expand All @@ -94,7 +94,7 @@ public void GivenAegSasTokenWithDifferentCase_WhenValidated_ThenHeaderIsFoundCas
[Fact]
public void GivenTokenExpiringExactlyNow_WhenValidated_ThenReturnsFalse()
{
var token = GenerateValidSasToken(ValidTopicKey, "http://localhost", DateTime.UtcNow);
var token = GenerateValidSasToken(ValidTopicKey, "http://localhost", DateTimeOffset.UtcNow);
var headers = new HeaderDictionary { { Constants.AegSasTokenHeader, token } };

var result = Validator.IsValid(headers, ValidTopicKey);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public void GivenValidAuthorizationHeader_WhenValidated_ThenReturnsTrue()
var token = GenerateValidSasToken(
ValidTopicKey,
"http://localhost",
DateTime.UtcNow.AddMinutes(5)
DateTimeOffset.UtcNow.AddMinutes(5)
);
var headers = new HeaderDictionary
{
Expand All @@ -33,7 +33,7 @@ public void GivenExpiredAuthorizationHeader_WhenValidated_ThenReturnsFalse()
var token = GenerateValidSasToken(
ValidTopicKey,
"http://localhost",
DateTime.UtcNow.AddMinutes(-5)
DateTimeOffset.UtcNow.AddMinutes(-5)
);
var headers = new HeaderDictionary
{
Expand All @@ -51,7 +51,7 @@ public void GivenAuthorizationHeaderWithWrongSignature_WhenValidated_ThenReturns
var token = GenerateValidSasToken(
"WrongKey123456789012345=",
"http://localhost",
DateTime.UtcNow.AddMinutes(5)
DateTimeOffset.UtcNow.AddMinutes(5)
);
var headers = new HeaderDictionary
{
Expand All @@ -69,7 +69,7 @@ public void GivenInvalidAuthorizationHeader_WhenValidated_ThenLogsError()
var token = GenerateValidSasToken(
"WrongKey123456789012345=",
"http://localhost",
DateTime.UtcNow.AddMinutes(5)
DateTimeOffset.UtcNow.AddMinutes(5)
);
var headers = new HeaderDictionary
{
Expand Down Expand Up @@ -108,7 +108,7 @@ public void GivenAuthorizationHeaderWithDifferentCase_WhenValidated_ThenHeaderIs
var token = GenerateValidSasToken(
ValidTopicKey,
"http://localhost",
DateTime.UtcNow.AddMinutes(5)
DateTimeOffset.UtcNow.AddMinutes(5)
);
var headers = new HeaderDictionary
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,16 @@ public abstract class SasKeyValidatorTestBase
protected SasKeyValidatorTestBase()
{
Logger = Substitute.For<ILogger<SasKeyValidator>>();
Validator = new SasKeyValidator(Logger);
Validator = new SasKeyValidator(TimeProvider.System, Logger);
}

protected static string GenerateValidSasToken(string key, string resource, DateTime expiry)
protected static string GenerateValidSasToken(
string key,
string resource,
DateTimeOffset expiry
)
{
var decodedExpiration = expiry.ToString("o");
var decodedExpiration = expiry.UtcDateTime.ToString("o");
Copy link

Copilot AI Dec 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using expiry.ToString("o") directly instead of converting to UtcDateTime first. Since expiry is already a DateTimeOffset, the ToString("o") format specifier will produce the ISO 8601 format with timezone information. The intermediate conversion to UtcDateTime is unnecessary.

Suggested change
var decodedExpiration = expiry.UtcDateTime.ToString("o");
var decodedExpiration = expiry.ToString("o");

Copilot uses AI. Check for mistakes.

var encodedResource = HttpUtility.UrlEncode(resource);
var encodedExpiration = HttpUtility.UrlEncode(decodedExpiration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ private static PendingDelivery CreatePendingDelivery(
Id = eventId ?? Guid.NewGuid().ToString(),
Subject = "test/subject",
EventType = "Test.EventType",
EventTime = DateTime.UtcNow.ToString("o"),
EventTime = DateTimeOffset.UtcNow.ToString("o"),
DataVersion = "1.0",
Data = new { test = "data" },
}
Expand Down Expand Up @@ -130,7 +130,7 @@ public async Task GivenDelivery_WhenWriting_ThenFileContainsCorrectJson()
new DeliveryAttempt
{
AttemptNumber = 5,
AttemptTime = DateTime.UtcNow,
AttemptTime = DateTimeOffset.UtcNow,
Outcome = DeliveryOutcome.HttpError,
HttpStatusCode = 503,
ErrorMessage = "Service Unavailable",
Expand Down
Loading
Loading