Skip to content

Commit

Permalink
* dsm.tryGetValue should catch exception
Browse files Browse the repository at this point in the history
* Dropped HostContext, replaced with dm.TurnState.Add(IConfig) or adapter.User(IConfig)
* Moved SkillDialog BotFrameworkClient to be turnstate based.
* Updated TestScript and unit tests to have Configuration for the test script
* Auto register DialogsComponentRegistration in DialogStateManager so users don't have to know to add it.
* Fix dialogManager.UserState => into turn state correctly.
  • Loading branch information
Tom Laird-McConnell committed May 6, 2020
1 parent f433026 commit 08590f9
Show file tree
Hide file tree
Showing 22 changed files with 76 additions and 163 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ namespace Microsoft.Bot.Builder.AI.Luis.Testing
{
public class MockLuisLoader : ICustomDeserializer
{
public MockLuisLoader()
private IConfiguration configuration;

public MockLuisLoader(IConfiguration configuration)
{
this.configuration = configuration;
}

public object Load(JToken obj, JsonSerializer serializer, Type type)
Expand All @@ -26,7 +29,6 @@ public object Load(JToken obj, JsonSerializer serializer, Type type)
name = name.Substring(start);
}

var configuration = HostContext.Current.Get<IConfiguration>();
return new MockLuisRecognizer(recognizer, configuration.GetValue<string>("luis:resources"), name);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,18 @@ public class TestScript
/// <remarks>If adapter is not provided a standard test adapter with all services will be registered.</remarks>
public TestScript()
{
Configuration = new ConfigurationBuilder().AddInMemoryCollection().Build();
}

/// <summary>
/// Gets or sets configuration to use for the test.
/// </summary>
/// <value>
/// IConfiguration to use for the test.
/// </value>
[JsonIgnore]
public IConfiguration Configuration { get; set; }

/// <summary>
/// Gets or sets the description property.
/// </summary>
Expand Down Expand Up @@ -100,6 +110,7 @@ public TestAdapter DefaultTestAdapter(ResourceExplorer resourceExplorer, [Caller
var userState = new UserState(storage);

var adapter = (TestAdapter)new TestAdapter(TestAdapter.CreateConversation(testName))
.Use(new RegisterClassMiddleware<IConfiguration>(this.Configuration))
.UseStorage(storage)
.UseBotState(userState, convoState)
.Use(new TranscriptLoggerMiddleware(new TraceTranscriptLogger(traceActivity: false)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ public override async Task<DialogTurnResult> BeginDialogAsync(DialogContext dc,
// Update the dialog options with the runtime settings.
DialogOptions.BotId = BotId.GetValue(dc.State);
DialogOptions.SkillHostEndpoint = new Uri(SkillHostEndpoint.GetValue(dc.State));
DialogOptions.ConversationIdFactory = HostContext.Current.Get<SkillConversationIdFactoryBase>() ?? throw new NullReferenceException("Unable to locate SkillConversationIdFactoryBase in HostContext");
DialogOptions.SkillClient = HostContext.Current.Get<BotFrameworkClient>() ?? throw new NullReferenceException("Unable to locate BotFrameworkClient in HostContext");
DialogOptions.ConversationIdFactory = dc.Context.TurnState.Get<SkillConversationIdFactoryBase>() ?? throw new NullReferenceException("Unable to locate SkillConversationIdFactoryBase in HostContext");
DialogOptions.SkillClient = dc.Context.TurnState.Get<BotFrameworkClient>() ?? throw new NullReferenceException("Unable to locate BotFrameworkClient in HostContext");
DialogOptions.ConversationState = dc.Context.TurnState.Get<ConversationState>() ?? throw new NullReferenceException($"Unable to get an instance of {nameof(ConversationState)} from TurnState.");
DialogOptions.ConnectionName = ConnectionName.GetValue(dc.State);

Expand Down
4 changes: 4 additions & 0 deletions libraries/Microsoft.Bot.Builder.Dialogs/DialogManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,10 @@ public async Task<DialogManagerResult> OnTurnAsync(ITurnContext context, Cancell
{
UserState = context.TurnState.Get<UserState>();
}
else
{
context.TurnState.Set(UserState);
}

if (UserState != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -31,6 +32,8 @@ public class DialogStateManager : IDictionary<string, object>

public DialogStateManager(DialogContext dc, DialogStateManagerConfiguration configuration = null)
{
ComponentRegistration.Add(new DialogsComponentRegistration());

dialogContext = dc ?? throw new ArgumentNullException(nameof(dc));
this.Configuration = configuration ?? dc.Context.TurnState.Get<DialogStateManagerConfiguration>();
if (this.Configuration == null)
Expand Down Expand Up @@ -181,7 +184,19 @@ public bool TryGetValue<T>(string path, out T value)
value = default;
path = TransformPath(path ?? throw new ArgumentNullException(nameof(path)));

var memoryScope = ResolveMemoryScope(path, out var remainingPath);
MemoryScope memoryScope = null;
string remainingPath;

try
{
memoryScope = ResolveMemoryScope(path, out remainingPath);
}
catch (Exception err)
{
Trace.TraceError(err.Message);
return false;
}

if (memoryScope == null)
{
return false;
Expand Down Expand Up @@ -490,7 +505,7 @@ IEnumerator IEnumerable.GetEnumerator()

private string GetBadScopeMessage(string path)
{
return $"'{path}' does not match memory scopes:{string.Join(",", Configuration.MemoryScopes.Select(ms => ms.Name))}";
return $"'{path}' does not match memory scopes:[{string.Join(",", Configuration.MemoryScopes.Select(ms => ms.Name))}]";
}

private bool TrackChange(string path, object value)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public override object GetMemory(DialogContext dc)

if (!dc.Context.TurnState.TryGetValue(ScopePath.Settings, out object settings))
{
var configuration = HostContext.Current.Get<IConfiguration>();
var configuration = dc.Context.TurnState.Get<IConfiguration>();
if (configuration != null)
{
settings = LoadSettings(configuration);
Expand Down
103 changes: 0 additions & 103 deletions libraries/Microsoft.Bot.Builder/HostContext.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -65,48 +65,42 @@ public class LuisAdaptiveRecognizerTests
'endpoint': '=settings.luis.endpoint',
'endpointKey': '=settings.luis.endpointKey', 'dynamicLists': " + DynamicListJSon + "}";

private readonly string dynamicListsDirectory = PathUtils.NormalizePath(@"..\..\..\Tests\LuisAdaptiveRecognizerTests");
private static readonly string DynamicListsDirectory = PathUtils.NormalizePath(@"..\..\..\Tests\LuisAdaptiveRecognizerTests");

public static ResourceExplorer ResourceExplorer { get; set; }

public static IConfiguration Configuration { get; set; }

public TestContext TestContext { get; set; }

[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
Configuration = new ConfigurationBuilder()
.UseMockLuisSettings(DynamicListsDirectory, "TestBot")
.Build();

ResourceExplorer = new ResourceExplorer()
.AddFolder(Path.Combine(TestUtils.GetProjectPath(), "Tests", nameof(LuisAdaptiveRecognizerTests)), monitorChanges: false)
.RegisterType(LuisAdaptiveRecognizer.Kind, typeof(MockLuisRecognizer), new MockLuisLoader());
.RegisterType(LuisAdaptiveRecognizer.Kind, typeof(MockLuisRecognizer), new MockLuisLoader(Configuration));
}

[TestMethod]
public async Task DynamicLists()
{
var config = new ConfigurationBuilder()
.UseMockLuisSettings(dynamicListsDirectory, "TestBot")
.Build();
HostContext.Current.Set<IConfiguration>(config);
await TestUtils.RunTestScript(ResourceExplorer);
await TestUtils.RunTestScript(ResourceExplorer, configuration: Configuration);
}

[TestMethod]
public async Task DynamicListsExpression()
{
var config = new ConfigurationBuilder()
.UseMockLuisSettings(dynamicListsDirectory, "TestBot")
.Build();
HostContext.Current.Set<IConfiguration>(config);
await TestUtils.RunTestScript(ResourceExplorer);
await TestUtils.RunTestScript(ResourceExplorer, configuration: Configuration);
}

[TestMethod]
public async Task ExternalEntities()
{
var config = new ConfigurationBuilder()
.UseMockLuisSettings(dynamicListsDirectory, "TestBot")
.Build();
HostContext.Current.Set<IConfiguration>(config);
await TestUtils.RunTestScript(ResourceExplorer);
await TestUtils.RunTestScript(ResourceExplorer, configuration: Configuration);
}

[TestMethod]
Expand Down
1 change: 0 additions & 1 deletion tests/Microsoft.Bot.Builder.AI.LUIS.Tests/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public class Startup
[AssemblyInitialize]
public static void Initialize(TestContext testContext)
{
ComponentRegistration.Add(new DialogsComponentRegistration());
ComponentRegistration.Add(new DeclarativeComponentRegistration());
ComponentRegistration.Add(new AdaptiveComponentRegistration());
ComponentRegistration.Add(new AdaptiveTestingComponentRegistration());
Expand Down
1 change: 0 additions & 1 deletion tests/Microsoft.Bot.Builder.AI.QnA.Tests/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ public class Startup
[AssemblyInitialize]
public static void Initialize(TestContext testContext)
{
ComponentRegistration.Add(new DialogsComponentRegistration());
ComponentRegistration.Add(new DeclarativeComponentRegistration());
ComponentRegistration.Add(new AdaptiveComponentRegistration());
ComponentRegistration.Add(new AdaptiveTestingComponentRegistration());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ public class Startup
[AssemblyInitialize]
public static void Initialize(TestContext testContext)
{
ComponentRegistration.Add(new DialogsComponentRegistration());
ComponentRegistration.Add(new DeclarativeComponentRegistration());
ComponentRegistration.Add(new AdaptiveComponentRegistration());
ComponentRegistration.Add(new AdaptiveTestingComponentRegistration());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.Bot.Builder.AI.Luis;
using Microsoft.Bot.Builder.AI.Luis.Testing;
using Microsoft.Bot.Builder.Dialogs.Declarative.Resources;
using Microsoft.Bot.Builder.Integration.ApplicationInsights.Core.Tests;
using Microsoft.Extensions.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;

Expand All @@ -17,27 +18,20 @@ public class GeneratorTests
private readonly string sandwichDirectory = PathUtils.NormalizePath(@"..\..\..\..\..\tests\Microsoft.Bot.Builder.Dialogs.Adaptive.Tests\Tests\GeneratorTests\sandwich\");
private readonly string unitTestsDirectory = PathUtils.NormalizePath(@"..\..\..\..\..\tests\Microsoft.Bot.Builder.Dialogs.Adaptive.Tests\Tests\GeneratorTests\unittests\");

public static ResourceExplorer ResourceExplorer { get; set; }

public TestContext TestContext { get; set; }

[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ResourceExplorer = new ResourceExplorer()
.AddFolder(Path.Combine(TestUtils.GetProjectPath(), "Tests", nameof(GeneratorTests)), monitorChanges: false)
.RegisterType(LuisAdaptiveRecognizer.Kind, typeof(MockLuisRecognizer), new MockLuisLoader());
}

[TestMethod]
public async Task Generator_sandwich()
{
var config = new ConfigurationBuilder()
.UseMockLuisSettings(sandwichDirectory, "TestBot")
.Build();
HostContext.Current.Set<IConfiguration>(config);

var resourceExplorer = new ResourceExplorer()
.AddFolder(Path.Combine(TestUtils.GetProjectPath(), "Tests", nameof(GeneratorTests)), monitorChanges: false)
.RegisterType(LuisAdaptiveRecognizer.Kind, typeof(MockLuisRecognizer), new MockLuisLoader(config));

await TestUtils.RunTestScript(ResourceExplorer);
await TestUtils.RunTestScript(resourceExplorer, configuration: config);
}

[TestMethod]
Expand All @@ -46,9 +40,12 @@ public async Task Generator_unittests()
var config = new ConfigurationBuilder()
.UseMockLuisSettings(unitTestsDirectory, "TestBot")
.Build();
HostContext.Current.Set<IConfiguration>(config);

await TestUtils.RunTestScript(ResourceExplorer);
var resourceExplorer = new ResourceExplorer()
.AddFolder(Path.Combine(TestUtils.GetProjectPath(), "Tests", nameof(GeneratorTests)), monitorChanges: false)
.RegisterType(LuisAdaptiveRecognizer.Kind, typeof(MockLuisRecognizer), new MockLuisLoader(config));

await TestUtils.RunTestScript(resourceExplorer, configuration: config);
}
}
}
Loading

0 comments on commit 08590f9

Please sign in to comment.