Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unit tests for the Microsoft.Agents.Hosting.AspNetCore namespace #68

Merged
merged 4 commits into from
Jan 27, 2025
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
15 changes: 11 additions & 4 deletions src/Microsoft.Agents.SDK.sln
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Agents.Storage.Tr
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Agents.Storage.Tests", "tests\Microsoft.Agents.Storage.Tests\Microsoft.Agents.Storage.Tests.csproj", "{23065AEC-4875-4CDC-A7E5-EE389C201534}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Agents.BotBuilder.Tests", "tests\Microsoft.Agents.BotBuilder.Tests\Microsoft.Agents.BotBuilder.Tests.csproj", "{401F5548-D6EF-4497-B786-D2A6BA8CBF76}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Agents.BotBuilder.Tests", "tests\Microsoft.Agents.BotBuilder.Tests\Microsoft.Agents.BotBuilder.Tests.csproj", "{401F5548-D6EF-4497-B786-D2A6BA8CBF76}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Agents.State.Tests", "tests\Microsoft.Agents.State.Tests\Microsoft.Agents.State.Tests.csproj", "{71813B2D-D6A8-4388-9541-9B1287C93F19}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Agents.State.Tests", "tests\Microsoft.Agents.State.Tests\Microsoft.Agents.State.Tests.csproj", "{71813B2D-D6A8-4388-9541-9B1287C93F19}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Agents.State", "libraries\Core\Microsoft.Agents.State\Microsoft.Agents.State.csproj", "{6A27C156-842F-409C-86B7-D9CC0A38F02F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Agents.State", "libraries\Core\Microsoft.Agents.State\Microsoft.Agents.State.csproj", "{6A27C156-842F-409C-86B7-D9CC0A38F02F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EvalClient", "samples\EvalClient\EvalClient.csproj", "{A839D635-0382-4E4C-8052-1F18B71434EE}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EvalClient", "samples\EvalClient\EvalClient.csproj", "{A839D635-0382-4E4C-8052-1F18B71434EE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.Agents.Hosting.AspNetCore.Tests", "tests\Microsoft.Agents.Hosting.AspNetCore\Microsoft.Agents.Hosting.AspNetCore.Tests.csproj", "{7D1A1CE5-6D9B-4D31-AC77-C3B1787F575D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InMeetingNotificationsBot", "samples\Teams\Meetings-Notification\InMeetingNotificationsBot.csproj", "{06E490F7-F0BB-E3C4-54FE-5210627292A1}"
EndProject
Expand Down Expand Up @@ -314,6 +316,10 @@ Global
{A839D635-0382-4E4C-8052-1F18B71434EE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A839D635-0382-4E4C-8052-1F18B71434EE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A839D635-0382-4E4C-8052-1F18B71434EE}.Release|Any CPU.Build.0 = Release|Any CPU
{7D1A1CE5-6D9B-4D31-AC77-C3B1787F575D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7D1A1CE5-6D9B-4D31-AC77-C3B1787F575D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7D1A1CE5-6D9B-4D31-AC77-C3B1787F575D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7D1A1CE5-6D9B-4D31-AC77-C3B1787F575D}.Release|Any CPU.Build.0 = Release|Any CPU
{06E490F7-F0BB-E3C4-54FE-5210627292A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{06E490F7-F0BB-E3C4-54FE-5210627292A1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{06E490F7-F0BB-E3C4-54FE-5210627292A1}.Release|Any CPU.ActiveCfg = Release|Any CPU
Expand Down Expand Up @@ -378,6 +384,7 @@ Global
{71813B2D-D6A8-4388-9541-9B1287C93F19} = {AD743B78-D61F-4FBF-B620-FA83CE599A50}
{6A27C156-842F-409C-86B7-D9CC0A38F02F} = {7A18F0C9-F8AF-4168-B954-6563BB2C1A90}
{A839D635-0382-4E4C-8052-1F18B71434EE} = {674A812C-7287-4883-97F9-697D83750648}
{7D1A1CE5-6D9B-4D31-AC77-C3B1787F575D} = {AD743B78-D61F-4FBF-B620-FA83CE599A50}
{06E490F7-F0BB-E3C4-54FE-5210627292A1} = {183D0E91-B84E-46D7-B653-6D85B4CCF804}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
Expand Down
6 changes: 6 additions & 0 deletions src/libraries/Hosting/AspNetCore/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Microsoft.Agents.Hosting.AspNetCore.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue
/// </summary>
public class HostedActivityService : BackgroundService
{
private readonly ILogger<HostedTaskService> _logger;
private readonly ILogger<HostedActivityService> _logger;
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
private readonly ConcurrentDictionary<ActivityWithClaims, Task> _activitiesProcessing = new ConcurrentDictionary<ActivityWithClaims, Task>();
private IActivityTaskQueue _activityQueue;
Expand All @@ -42,7 +42,7 @@ public class HostedActivityService : BackgroundService
/// <param name="activityTaskQueue"><see cref="ActivityTaskQueue"/>Queue of activities to be processed. This class
/// contains a semaphore which the BackgroundService waits on to be notified of activities to be processed.</param>
/// <param name="logger">Logger to use for logging BackgroundService processing and exception information.</param>
public HostedActivityService(IConfiguration config, IBot bot, IChannelAdapter adapter, IActivityTaskQueue activityTaskQueue, ILogger<HostedTaskService> logger)
public HostedActivityService(IConfiguration config, IBot bot, IChannelAdapter adapter, IActivityTaskQueue activityTaskQueue, ILogger<HostedActivityService> logger)
{
ArgumentNullException.ThrowIfNull(config);
ArgumentNullException.ThrowIfNull(bot);
Expand All @@ -53,7 +53,7 @@ public HostedActivityService(IConfiguration config, IBot bot, IChannelAdapter ad
_activityQueue = activityTaskQueue;
_bot = bot;
_adapter = adapter;
_logger = logger ?? NullLogger<HostedTaskService>.Instance;
_logger = logger ?? NullLogger<HostedActivityService>.Instance;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue
{
Expand Down Expand Up @@ -40,7 +41,7 @@ public HostedTaskService(IConfiguration config, IBackgroundTaskQueue taskQueue,

_shutdownTimeoutSeconds = config.GetValue<int>("ShutdownTimeoutSeconds");
_taskQueue = taskQueue;
_logger = logger;
_logger = logger ?? NullLogger<HostedTaskService>.Instance;;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Agents.Core.Models;
using Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Agents.Hosting.AspNetCore.Tests.BackgroundActivityService
{
public class ActivityTaskQueueTests
{
[Fact]
public async Task WaitForActivityAsync_ShouldResolveQueuedActivity()
{
var queue = new ActivityTaskQueue();
var claims = new ClaimsIdentity();
var activity = new Activity();

queue.QueueBackgroundActivity(claims, activity);
var waited = await queue.WaitForActivityAsync(CancellationToken.None);

Assert.Equal(claims, waited.ClaimsIdentity);
Assert.Equal(activity, waited.Activity);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Agents.BotBuilder;
using Microsoft.Agents.BotBuilder.Testing;
using Microsoft.Agents.Core.Interfaces;
using Microsoft.Agents.Core.Models;
using Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Agents.Hosting.AspNetCore.Tests.BackgroundActivityService
{
public class HostedActivityServiceTests
{
[Fact]
public void Constructor_ShouldThrowWithNullConfig()
{
var bot = new ActivityHandler();
var adapter = new TestAdapter();
var queue = new ActivityTaskQueue();
var logger = new Mock<ILogger<HostedActivityService>>();

Assert.Throws<ArgumentNullException>(() => new HostedActivityService(null, bot, adapter, queue, logger.Object));
}

[Fact]
public void Constructor_ShouldThrowWithNullBot()
{
var config = new ConfigurationBuilder().Build();
var adapter = new TestAdapter();
var queue = new ActivityTaskQueue();
var logger = new Mock<ILogger<HostedActivityService>>();

Assert.Throws<ArgumentNullException>(() => new HostedActivityService(config, null, adapter, queue, logger.Object));
}

[Fact]
public void Constructor_ShouldThrowWithNullAdapter()
{
var config = new ConfigurationBuilder().Build();
var bot = new ActivityHandler();
var queue = new ActivityTaskQueue();
var logger = new Mock<ILogger<HostedActivityService>>();

Assert.Throws<ArgumentNullException>(() => new HostedActivityService(config, bot, null, queue, logger.Object));
}

[Fact]
public void Constructor_ShouldThrowWithNullActivityTaskQueue()
{
var config = new ConfigurationBuilder().Build();
var bot = new ActivityHandler();
var adapter = new TestAdapter();
var logger = new Mock<ILogger<HostedActivityService>>();

Assert.Throws<ArgumentNullException>(() => new HostedActivityService(config, bot, adapter, null, logger.Object));
}

[Fact]
public async Task Constructor_ShouldInstantiateNullLogger()
{
var config = new ConfigurationBuilder().Build();
var bot = new ActivityHandler();
var adapter = new TestAdapter();
var queue = new ActivityTaskQueue();

try
{
var service = new HostedActivityService(config, bot, adapter, queue, null);
await service.StopAsync(CancellationToken.None);
}
catch (Exception)
{
Assert.Fail("NullLogger wasn't instantiated.");
}
}

[Fact]
public async Task ExecuteAsync_ShouldProcessQueuedActivity()
{
var record = UseRecord();
var claims = new ClaimsIdentity();
var activity = new Activity();
var source = new CancellationTokenSource();

record.Adapter.Setup(a => a.ProcessActivityAsync(It.IsAny<ClaimsIdentity>(), It.IsAny<Activity>(), It.IsAny<BotCallbackHandler>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new InvokeResponse())
.Verifiable(Times.Once);

record.Queue.QueueBackgroundActivity(claims, activity);
await record.Service.StartAsync(source.Token).ContinueWith(async e =>
{
// Start and stop the service, waiting for the activity to be processed.
await record.Service.StopAsync(source.Token);
record.VerifyMocks();
});
}


[Fact]
public async Task ExecuteAsync_ShouldLogErrorWhenProcessingQueuedActivity()
{
var record = UseRecord();
var claims = new ClaimsIdentity();
var activity = new Activity();
var source = new CancellationTokenSource();

record.Adapter.Setup(a => a.ProcessActivityAsync(It.IsAny<ClaimsIdentity>(), It.IsAny<Activity>(), It.IsAny<BotCallbackHandler>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new Exception())
.Verifiable(Times.Once);
record.Logger.Setup(e => e.Log(LogLevel.Error,
It.IsAny<EventId>(),
It.IsAny<It.IsAnyType>(),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception, string>>()))
.Verifiable(Times.Once);

record.Queue.QueueBackgroundActivity(claims, activity);
await record.Service.StartAsync(source.Token).ContinueWith(async e =>
{
// Start and stop the service, waiting for the activity to be processed.
await record.Service.StopAsync(source.Token);
record.VerifyMocks();
});
}

[Fact]
public void ExecuteAsync_ShouldCancelBackgroundProcess()
{
var record = UseRecord();
var source = new CancellationTokenSource();

record.Adapter.Setup(a => a.ProcessActivityAsync(It.IsAny<ClaimsIdentity>(), It.IsAny<Activity>(), It.IsAny<BotCallbackHandler>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new InvokeResponse())
.Verifiable(Times.Never);

source.Cancel();
var task = record.Service.StartAsync(source.Token);

Assert.Equal(TaskStatus.RanToCompletion, task.Status);
record.VerifyMocks();
}

private static Record UseRecord()
{
var config = new ConfigurationBuilder().Build();
var queue = new ActivityTaskQueue();
var bot = new Mock<ActivityHandler>();
var adapter = new Mock<IChannelAdapter>();
var logger = new Mock<ILogger<HostedActivityService>>();

var service = new HostedActivityService(config, bot.Object, adapter.Object, queue, logger.Object);
return new(service, queue, bot, adapter, logger);
}

private record Record(
HostedActivityService Service,
ActivityTaskQueue Queue,
Mock<ActivityHandler> Bot,
Mock<IChannelAdapter> Adapter,
Mock<ILogger<HostedActivityService>> Logger)
{
public void VerifyMocks()
{
Mock.Verify(Bot, Adapter, Logger);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Agents.Core.Models;
using Microsoft.Agents.Hosting.AspNetCore.BackgroundQueue;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Agents.Hosting.AspNetCore.Tests.BackgroundTaskService
{
public class BackgroundTaskQueueTests
{
[Fact]
public async Task DequeueAsync_ShouldResolveQueuedTask()
{
var queue = new BackgroundTaskQueue();
var resolved = false;

queue.QueueBackgroundWorkItem((cancellationToken) =>
{
resolved = true;
return Task.FromResult(0);
});

var dequeued = await queue.DequeueAsync(CancellationToken.None);
await dequeued(CancellationToken.None);

Assert.True(resolved);
}
}
}
Loading
Loading