Skip to content

Commit acb3e35

Browse files
grvnmttlclaudewestey-m
authored
.Net: [.NET] Add TimeProvider injection to TimePlugin for deterministic testing (#14112)
Closes #14111 ## Summary - Adds a `TimeProvider` constructor parameter to `TimePlugin` (defaults to `TimeProvider.System`, so all existing callers are unaffected) - Replaces all direct `DateTimeOffset.Now` / `DateTimeOffset.UtcNow` calls with `_timeProvider.GetLocalNow()` / `_timeProvider.GetUtcNow()` - Rewrites `TimePluginTests` from 5 real-clock tests to 26 deterministic tests covering every public method, using an inline `FixedUtcTimeProvider` subclass (no new test dependencies) ## Key decisions | Decision | Reason | |---|---| | `System.TimeProvider` (not a custom `IClock`) | Standard .NET 8+ pattern; no extra abstraction needed | | Inline `FixedUtcTimeProvider` subclass in tests | Avoids adding `Microsoft.Extensions.TimeProvider.Testing` as a new dependency; 3-line subclass is clearer | | `LocalTimeZone = TimeZoneInfo.Utc` on the test provider | Makes test output identical on any machine regardless of OS timezone | | Default `TimeProvider.System` in constructor | Zero breaking change — all existing callers (`new TimePlugin()`) work unchanged | ## Test results ``` Passed! - Failed: 0, Passed: 394, Skipped: 0, Total: 394 ``` --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]> Co-authored-by: westey <[email protected]>
1 parent e15ae16 commit acb3e35

4 files changed

Lines changed: 163 additions & 64 deletions

File tree

‎dotnet/Directory.Packages.props‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@
148148
<PackageVersion Include="Microsoft.Extensions.Logging.Debug" Version="10.0.2" />
149149
<PackageVersion Include="Microsoft.Extensions.Options.DataAnnotations" Version="10.0.2" />
150150
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.2" />
151+
<PackageVersion Include="Microsoft.Bcl.TimeProvider" Version="8.0.1" />
151152
<PackageVersion Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.2.0" />
152153
<PackageVersion Include="Microsoft.Extensions.FileProviders.Physical" Version="10.0.2" />
153154
<PackageVersion Include="Microsoft.Extensions.FileProviders.Embedded" Version="10.0.2" />

‎dotnet/src/Plugins/Plugins.Core/Plugins.Core.csproj‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,8 @@
2525
<PackageReference Include="Microsoft.Extensions.Http" />
2626
</ItemGroup>
2727

28+
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
29+
<PackageReference Include="Microsoft.Bcl.TimeProvider" />
30+
</ItemGroup>
31+
2832
</Project>

‎dotnet/src/Plugins/Plugins.Core/TimePlugin.cs‎

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,17 @@ namespace Microsoft.SemanticKernel.Plugins.Core;
1414
/// </remark>
1515
public sealed class TimePlugin
1616
{
17+
private readonly TimeProvider _timeProvider;
18+
19+
/// <summary>
20+
/// Initializes a new instance of the <see cref="TimePlugin"/> class.
21+
/// </summary>
22+
/// <param name="timeProvider">The time provider to use. Defaults to <see cref="TimeProvider.System"/>.</param>
23+
public TimePlugin(TimeProvider? timeProvider = null)
24+
{
25+
this._timeProvider = timeProvider ?? TimeProvider.System;
26+
}
27+
1728
/// <summary>
1829
/// Get the current date
1930
/// </summary>
@@ -24,7 +35,7 @@ public sealed class TimePlugin
2435
[KernelFunction, Description("Get the current date")]
2536
public string Date(IFormatProvider? formatProvider = null) =>
2637
// Example: Sunday, 12 January, 2025
27-
DateTimeOffset.Now.ToString("D", formatProvider);
38+
this._timeProvider.GetLocalNow().ToString("D", formatProvider);
2839

2940
/// <summary>
3041
/// Get the current date
@@ -48,7 +59,7 @@ public string Today(IFormatProvider? formatProvider = null) =>
4859
[KernelFunction, Description("Get the current date and time in the local time zone")]
4960
public string Now(IFormatProvider? formatProvider = null) =>
5061
// Sunday, January 12, 2025 9:15 PM
51-
DateTimeOffset.Now.ToString("f", formatProvider);
62+
this._timeProvider.GetLocalNow().ToString("f", formatProvider);
5263

5364
/// <summary>
5465
/// Get the current UTC date and time
@@ -60,7 +71,7 @@ public string Now(IFormatProvider? formatProvider = null) =>
6071
[KernelFunction, Description("Get the current UTC date and time")]
6172
public string UtcNow(IFormatProvider? formatProvider = null) =>
6273
// Sunday, January 13, 2025 5:15 AM
63-
DateTimeOffset.UtcNow.ToString("f", formatProvider);
74+
this._timeProvider.GetUtcNow().ToString("f", formatProvider);
6475

6576
/// <summary>
6677
/// Get the current time
@@ -72,7 +83,7 @@ public string UtcNow(IFormatProvider? formatProvider = null) =>
7283
[KernelFunction, Description("Get the current time")]
7384
public string Time(IFormatProvider? formatProvider = null) =>
7485
// Example: 09:15:07 PM
75-
DateTimeOffset.Now.ToString("hh:mm:ss tt", formatProvider);
86+
this._timeProvider.GetLocalNow().ToString("hh:mm:ss tt", formatProvider);
7687

7788
/// <summary>
7889
/// Get the current year
@@ -84,7 +95,7 @@ public string Time(IFormatProvider? formatProvider = null) =>
8495
[KernelFunction, Description("Get the current year")]
8596
public string Year(IFormatProvider? formatProvider = null) =>
8697
// Example: 2025
87-
DateTimeOffset.Now.ToString("yyyy", formatProvider);
98+
this._timeProvider.GetLocalNow().ToString("yyyy", formatProvider);
8899

89100
/// <summary>
90101
/// Get the current month name
@@ -96,7 +107,7 @@ public string Year(IFormatProvider? formatProvider = null) =>
96107
[KernelFunction, Description("Get the current month name")]
97108
public string Month(IFormatProvider? formatProvider = null) =>
98109
// Example: January
99-
DateTimeOffset.Now.ToString("MMMM", formatProvider);
110+
this._timeProvider.GetLocalNow().ToString("MMMM", formatProvider);
100111

101112
/// <summary>
102113
/// Get the current month number
@@ -108,7 +119,7 @@ public string Month(IFormatProvider? formatProvider = null) =>
108119
[KernelFunction, Description("Get the current month number")]
109120
public string MonthNumber(IFormatProvider? formatProvider = null) =>
110121
// Example: 01
111-
DateTimeOffset.Now.ToString("MM", formatProvider);
122+
this._timeProvider.GetLocalNow().ToString("MM", formatProvider);
112123

113124
/// <summary>
114125
/// Get the current day of the month
@@ -120,7 +131,7 @@ public string MonthNumber(IFormatProvider? formatProvider = null) =>
120131
[KernelFunction, Description("Get the current day of the month")]
121132
public string Day(IFormatProvider? formatProvider = null) =>
122133
// Example: 12
123-
DateTimeOffset.Now.ToString("dd", formatProvider);
134+
this._timeProvider.GetLocalNow().ToString("dd", formatProvider);
124135

125136
/// <summary>
126137
/// Get the date a provided number of days in the past
@@ -129,7 +140,7 @@ public string Day(IFormatProvider? formatProvider = null) =>
129140
[KernelFunction]
130141
[Description("Get the date offset by a provided number of days from today")]
131142
public string DaysAgo([Description("The number of days to offset from today")] double input, IFormatProvider? formatProvider = null) =>
132-
DateTimeOffset.Now.AddDays(-input).ToString("D", formatProvider);
143+
this._timeProvider.GetLocalNow().AddDays(-input).ToString("D", formatProvider);
133144

134145
/// <summary>
135146
/// Get the current day of the week
@@ -141,7 +152,7 @@ public string DaysAgo([Description("The number of days to offset from today")] d
141152
[KernelFunction, Description("Get the current day of the week")]
142153
public string DayOfWeek(IFormatProvider? formatProvider = null) =>
143154
// Example: Sunday
144-
DateTimeOffset.Now.ToString("dddd", formatProvider);
155+
this._timeProvider.GetLocalNow().ToString("dddd", formatProvider);
145156

146157
/// <summary>
147158
/// Get the current clock hour
@@ -153,7 +164,7 @@ public string DayOfWeek(IFormatProvider? formatProvider = null) =>
153164
[KernelFunction, Description("Get the current clock hour")]
154165
public string Hour(IFormatProvider? formatProvider = null) =>
155166
// Example: 9 PM
156-
DateTimeOffset.Now.ToString("h tt", formatProvider);
167+
this._timeProvider.GetLocalNow().ToString("h tt", formatProvider);
157168

158169
/// <summary>
159170
/// Get the current clock 24-hour number
@@ -165,7 +176,7 @@ public string Hour(IFormatProvider? formatProvider = null) =>
165176
[KernelFunction, Description("Get the current clock 24-hour number")]
166177
public string HourNumber(IFormatProvider? formatProvider = null) =>
167178
// Example: 21
168-
DateTimeOffset.Now.ToString("HH", formatProvider);
179+
this._timeProvider.GetLocalNow().ToString("HH", formatProvider);
169180

170181
/// <summary>
171182
/// Get the date of the previous day matching the supplied day name
@@ -181,7 +192,7 @@ public string DateMatchingLastDayName(
181192
[Description("The day name to match")] DayOfWeek input,
182193
IFormatProvider? formatProvider = null)
183194
{
184-
DateTimeOffset dateTime = DateTimeOffset.Now;
195+
DateTimeOffset dateTime = this._timeProvider.GetLocalNow();
185196

186197
// Walk backwards from the previous day for up to a week to find the matching day
187198
for (int i = 1; i <= 7; ++i)
@@ -206,7 +217,7 @@ public string DateMatchingLastDayName(
206217
[KernelFunction, Description("Get the minutes on the current hour")]
207218
public string Minute(IFormatProvider? formatProvider = null) =>
208219
// Example: 15
209-
DateTimeOffset.Now.ToString("mm", formatProvider);
220+
this._timeProvider.GetLocalNow().ToString("mm", formatProvider);
210221

211222
/// <summary>
212223
/// Get the seconds on the current minute
@@ -218,7 +229,7 @@ public string Minute(IFormatProvider? formatProvider = null) =>
218229
[KernelFunction, Description("Get the seconds on the current minute")]
219230
public string Second(IFormatProvider? formatProvider = null) =>
220231
// Example: 07
221-
DateTimeOffset.Now.ToString("ss", formatProvider);
232+
this._timeProvider.GetLocalNow().ToString("ss", formatProvider);
222233

223234
/// <summary>
224235
/// Get the local time zone offset from UTC
@@ -230,7 +241,7 @@ public string Second(IFormatProvider? formatProvider = null) =>
230241
[KernelFunction, Description("Get the local time zone offset from UTC")]
231242
public string TimeZoneOffset(IFormatProvider? formatProvider = null) =>
232243
// Example: -08:00
233-
DateTimeOffset.Now.ToString("%K", formatProvider);
244+
this._timeProvider.GetLocalNow().ToString("%K", formatProvider);
234245

235246
/// <summary>
236247
/// Get the local time zone name
@@ -246,5 +257,5 @@ public string TimeZoneOffset(IFormatProvider? formatProvider = null) =>
246257
public string TimeZoneName() =>
247258
// Example: PST
248259
// Note: this is the "current" timezone and it can change over the year, e.g. from PST to PDT
249-
TimeZoneInfo.Local.DisplayName;
260+
this._timeProvider.LocalTimeZone.DisplayName;
250261
}

‎dotnet/src/Plugins/Plugins.UnitTests/Core/TimePluginTests.cs‎

Lines changed: 130 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -11,44 +11,157 @@
1111

1212
namespace SemanticKernel.Plugins.UnitTests.Core;
1313

14-
// TODO: allow clock injection and test all functions
1514
public class TimePluginTests
1615
{
16+
// Sunday, 15 June 2025 21:15:07 UTC — local timezone pinned to UTC so tests are machine-independent
17+
private static readonly DateTimeOffset s_fixedTime = new(2025, 6, 15, 21, 15, 7, TimeSpan.Zero);
18+
19+
private static TimePlugin CreatePlugin() => new(new FixedUtcTimeProvider(s_fixedTime));
20+
21+
/// <summary>Minimal TimeProvider that returns a fixed UTC instant with UTC as local timezone.</summary>
22+
private sealed class FixedUtcTimeProvider(DateTimeOffset fixedUtc) : TimeProvider
23+
{
24+
public override DateTimeOffset GetUtcNow() => fixedUtc.ToUniversalTime();
25+
public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc;
26+
}
27+
1728
[Fact]
1829
public void ItCanBeInstantiated()
1930
{
20-
// Act - Assert no exception occurs
2131
var _ = new TimePlugin();
2232
}
2333

2434
[Fact]
2535
public void ItCanBeImported()
2636
{
27-
// Act - Assert no exception occurs e.g. due to reflection
2837
Assert.NotNull(KernelPluginFactory.CreateFromType<TimePlugin>("time"));
2938
}
3039

3140
[Fact]
32-
public void DaysAgo()
41+
public void Date()
42+
{
43+
// InvariantCulture "D" format: dddd, dd MMMM yyyy
44+
Assert.Equal("Sunday, 15 June 2025", CreatePlugin().Date(CultureInfo.InvariantCulture));
45+
}
46+
47+
[Fact]
48+
public void Today()
3349
{
34-
double interval = 2;
35-
DateTime expected = DateTime.Now.AddDays(-interval);
36-
var plugin = new TimePlugin();
37-
string result = plugin.DaysAgo(interval, CultureInfo.CurrentCulture);
38-
DateTime returned = DateTime.Parse(result, CultureInfo.CurrentCulture);
39-
Assert.Equal(expected.Day, returned.Day);
40-
Assert.Equal(expected.Month, returned.Month);
41-
Assert.Equal(expected.Year, returned.Year);
50+
Assert.Equal("Sunday, 15 June 2025", CreatePlugin().Today(CultureInfo.InvariantCulture));
51+
}
52+
53+
[Fact]
54+
public void Now()
55+
{
56+
// InvariantCulture "f" format: dddd, dd MMMM yyyy HH:mm
57+
Assert.Equal("Sunday, 15 June 2025 21:15", CreatePlugin().Now(CultureInfo.InvariantCulture));
58+
}
59+
60+
[Fact]
61+
public void UtcNow()
62+
{
63+
Assert.Equal("Sunday, 15 June 2025 21:15", CreatePlugin().UtcNow(CultureInfo.InvariantCulture));
64+
}
65+
66+
[Fact]
67+
public void Time()
68+
{
69+
Assert.Equal("09:15:07 PM", CreatePlugin().Time(CultureInfo.InvariantCulture));
70+
}
71+
72+
[Fact]
73+
public void Year()
74+
{
75+
Assert.Equal("2025", CreatePlugin().Year(CultureInfo.InvariantCulture));
76+
}
77+
78+
[Fact]
79+
public void Month()
80+
{
81+
Assert.Equal("June", CreatePlugin().Month(CultureInfo.InvariantCulture));
82+
}
83+
84+
[Fact]
85+
public void MonthNumber()
86+
{
87+
Assert.Equal("06", CreatePlugin().MonthNumber(CultureInfo.InvariantCulture));
4288
}
4389

4490
[Fact]
4591
public void Day()
4692
{
47-
string expected = DateTime.Now.ToString("dd", CultureInfo.CurrentCulture);
48-
var plugin = new TimePlugin();
49-
string result = plugin.Day(CultureInfo.CurrentCulture);
50-
Assert.Equal(expected, result);
51-
Assert.True(int.TryParse(result, out _));
93+
Assert.Equal("15", CreatePlugin().Day(CultureInfo.InvariantCulture));
94+
}
95+
96+
[Fact]
97+
public void DayOfWeek()
98+
{
99+
Assert.Equal("Sunday", CreatePlugin().DayOfWeek(CultureInfo.InvariantCulture));
100+
}
101+
102+
[Fact]
103+
public void Hour()
104+
{
105+
Assert.Equal("9 PM", CreatePlugin().Hour(CultureInfo.InvariantCulture));
106+
}
107+
108+
[Fact]
109+
public void HourNumber()
110+
{
111+
Assert.Equal("21", CreatePlugin().HourNumber(CultureInfo.InvariantCulture));
112+
}
113+
114+
[Fact]
115+
public void Minute()
116+
{
117+
Assert.Equal("15", CreatePlugin().Minute(CultureInfo.InvariantCulture));
118+
}
119+
120+
[Fact]
121+
public void Second()
122+
{
123+
Assert.Equal("07", CreatePlugin().Second(CultureInfo.InvariantCulture));
124+
}
125+
126+
[Fact]
127+
public void TimeZoneOffset()
128+
{
129+
Assert.Equal("+00:00", CreatePlugin().TimeZoneOffset(CultureInfo.InvariantCulture));
130+
}
131+
132+
[Fact]
133+
public void TimeZoneName()
134+
{
135+
// FixedUtcTimeProvider pins LocalTimeZone to TimeZoneInfo.Utc
136+
Assert.Equal(TimeZoneInfo.Utc.DisplayName, CreatePlugin().TimeZoneName());
137+
}
138+
139+
[Fact]
140+
public void DaysAgo()
141+
{
142+
// 2 days before 2025-06-15 is 2025-06-13 (Friday)
143+
Assert.Equal("Friday, 13 June 2025", CreatePlugin().DaysAgo(2, CultureInfo.InvariantCulture));
144+
}
145+
146+
[Theory]
147+
[MemberData(nameof(DayOfWeekCases))]
148+
public void DateMatchingLastDayName(DayOfWeek dayName, string expectedDate)
149+
{
150+
// Fixed time is Sunday 2025-06-15; walk back to find each day
151+
Assert.Equal(expectedDate, CreatePlugin().DateMatchingLastDayName(dayName, CultureInfo.InvariantCulture));
152+
}
153+
154+
public static IEnumerable<object[]> DayOfWeekCases()
155+
{
156+
// From Sunday 2025-06-15, the previous occurrence of each day (never same day).
157+
// InvariantCulture "D" format: dddd, dd MMMM yyyy
158+
yield return [System.DayOfWeek.Saturday, "Saturday, 14 June 2025"];
159+
yield return [System.DayOfWeek.Friday, "Friday, 13 June 2025"];
160+
yield return [System.DayOfWeek.Thursday, "Thursday, 12 June 2025"];
161+
yield return [System.DayOfWeek.Wednesday, "Wednesday, 11 June 2025"];
162+
yield return [System.DayOfWeek.Tuesday, "Tuesday, 10 June 2025"];
163+
yield return [System.DayOfWeek.Monday, "Monday, 09 June 2025"];
164+
yield return [System.DayOfWeek.Sunday, "Sunday, 08 June 2025"];
52165
}
53166

54167
[Fact]
@@ -60,34 +173,4 @@ public async Task LastMatchingDayBadInputAsync()
60173

61174
AssertExtensions.AssertIsArgumentOutOfRange(ex, "input", "not a day name");
62175
}
63-
64-
[Theory]
65-
[MemberData(nameof(DayOfWeekEnumerator))]
66-
public void LastMatchingDay(DayOfWeek dayName)
67-
{
68-
int steps = 0;
69-
DateTime date = DateTime.Now.Date.AddDays(-1);
70-
while (date.DayOfWeek != dayName && steps <= 7)
71-
{
72-
date = date.AddDays(-1);
73-
steps++;
74-
}
75-
bool found = date.DayOfWeek == dayName;
76-
Assert.True(found);
77-
78-
var plugin = new TimePlugin();
79-
string result = plugin.DateMatchingLastDayName(dayName, CultureInfo.CurrentCulture);
80-
DateTime returned = DateTime.Parse(result, CultureInfo.CurrentCulture);
81-
Assert.Equal(date.Day, returned.Day);
82-
Assert.Equal(date.Month, returned.Month);
83-
Assert.Equal(date.Year, returned.Year);
84-
}
85-
86-
public static IEnumerable<object[]> DayOfWeekEnumerator()
87-
{
88-
foreach (var day in Enum.GetValues<DayOfWeek>())
89-
{
90-
yield return new object[] { day };
91-
}
92-
}
93176
}

0 commit comments

Comments
 (0)