Skip to content

Commit 7871195

Browse files
committed
Clean up UI tests
1 parent 5584826 commit 7871195

File tree

6 files changed

+206
-157
lines changed

6 files changed

+206
-157
lines changed

UITests/UITests.App/App.AppService.xaml.cs

Lines changed: 59 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System;
6-
using System.Diagnostics;
6+
using System.Threading.Tasks;
77
using Microsoft.Toolkit.Mvvm.Messaging;
88
using UITests.App.Pages;
99
using Windows.ApplicationModel.Activation;
@@ -20,6 +20,9 @@ namespace UITests.App
2020
/// </summary>
2121
public sealed partial class App
2222
{
23+
private static readonly ValueSet BadResult = new() { { "Status", "BAD" } };
24+
private static readonly ValueSet OkResult = new() { { "Status", "OK" } };
25+
2326
private AppServiceConnection _appServiceConnection;
2427
private BackgroundTaskDeferral _appServiceDeferral;
2528

@@ -37,45 +40,42 @@ protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
3740

3841
private async void OnAppServiceRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
3942
{
40-
AppServiceDeferral messageDeferral = args.GetDeferral();
41-
ValueSet message = args.Request.Message;
42-
string cmd = message["Command"] as string;
43+
var messageDeferral = args.GetDeferral();
44+
var message = args.Request.Message;
45+
if(!TryGetValueAndLog(message, "Command", out var cmd))
46+
{
47+
messageDeferral.Complete();
48+
return;
49+
}
4350

44-
try
51+
switch (cmd)
4552
{
46-
// Return the data to the caller.
47-
if (cmd == "Start")
48-
{
49-
var pageName = message["Page"] as string;
53+
case "OpenPage":
54+
if (!TryGetValueAndLog(message, "Page", out var pageName))
55+
{
56+
await args.Request.SendResponseAsync(BadResult);
57+
break;
58+
}
5059

5160
Log.Comment("Received request for Page: {0}", pageName);
5261

53-
ValueSet returnMessage = new ValueSet();
54-
5562
// We await the OpenPage method to ensure the navigation has finished.
56-
if (await WeakReferenceMessenger.Default.Send(new RequestPageMessage(pageName)))
57-
{
58-
returnMessage.Add("Status", "OK");
59-
}
60-
else
61-
{
62-
returnMessage.Add("Status", "BAD");
63-
}
63+
var pageResponse = await WeakReferenceMessenger.Default.Send(new RequestPageMessage(pageName));
6464

65-
await args.Request.SendResponseAsync(returnMessage);
66-
}
67-
}
68-
catch (Exception e)
69-
{
70-
// Your exception handling code here.
71-
Log.Error("Exception processing request: {0}", e.Message);
72-
}
73-
finally
74-
{
75-
// Complete the deferral so that the platform knows that we're done responding to the app service call.
76-
// Note: for error handling: this must be called even if SendResponseAsync() throws an exception.
77-
messageDeferral.Complete();
65+
await args.Request.SendResponseAsync(pageResponse ? OkResult : BadResult);
66+
67+
break;
68+
case "Close":
69+
Current.Exit();
70+
await args.Request.SendResponseAsync(OkResult);
71+
break;
72+
default:
73+
break;
7874
}
75+
76+
// Complete the deferral so that the platform knows that we're done responding to the app service call.
77+
// Note: for error handling: this must be called even if SendResponseAsync() throws an exception.
78+
messageDeferral.Complete();
7979
}
8080

8181
private void OnAppServicesCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
@@ -88,16 +88,38 @@ private void AppServiceConnection_ServiceClosed(AppServiceConnection sender, App
8888
_appServiceDeferral.Complete();
8989
}
9090

91-
public async void SendLogMessage(string level, string msg)
91+
public async Task SendLogMessage(string level, string msg)
9292
{
93-
var message = new ValueSet();
94-
message.Add("Command", "Log");
95-
message.Add("Level", level);
96-
message.Add("Message", msg);
93+
var message = new ValueSet
94+
{
95+
{ "Command", "Log" },
96+
{ "Level", level },
97+
{ "Message", msg }
98+
};
9799

98100
await _appServiceConnection.SendMessageAsync(message);
99101

100102
// TODO: do we care if we have a problem here?
101103
}
104+
105+
private static bool TryGetValueAndLog(ValueSet message, string key, out string value)
106+
{
107+
value = null;
108+
if (!message.TryGetValue(key, out var o))
109+
{
110+
Log.Error($"Could not find the key \"{key}\" in the message.");
111+
return false;
112+
}
113+
114+
if (o is not string s)
115+
{
116+
Log.Error($"{key}'s value is not a string");
117+
return false;
118+
}
119+
120+
value = s;
121+
122+
return true;
123+
}
102124
}
103125
}

UITests/UITests.App/UITests.App.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
<GenerateAppxPackageOnBuild>true</GenerateAppxPackageOnBuild>
2828
<AppxPackageSigningEnabled>True</AppxPackageSigningEnabled>
2929
<IsTestHost>true</IsTestHost>
30+
<LangVersion>9.0</LangVersion>
3031
</PropertyGroup>
3132
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
3233
<DebugSymbols>true</DebugSymbols>

UITests/UITests.Tests.MSTest/UITests.Tests.MSTest.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<TargetFrameworkIdentifier>.NETCoreApp</TargetFrameworkIdentifier>
77
<TargetFrameworkVersion>v3.1</TargetFrameworkVersion>
88
<RuntimeIdentifier>win10-x86</RuntimeIdentifier>
9-
<LangVersion>8.0</LangVersion>
9+
<LangVersion>9.0</LangVersion>
1010

1111
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
1212
<PlatformTarget>x86</PlatformTarget>

UITests/UITests.Tests.Shared/TestAssembly.cs

Lines changed: 98 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System;
6-
using System.IO;
7-
using System.Linq;
8-
using System.Reflection;
6+
using System.Threading.Tasks;
7+
using Windows.ApplicationModel.AppService;
8+
using Windows.Foundation.Collections;
99
using Windows.UI.Xaml.Tests.MUXControls.InteractionTests.Infra;
1010

1111
#if USING_TAEF
@@ -23,6 +23,8 @@ namespace UITests.Tests
2323
[TestClass]
2424
public class TestAssembly
2525
{
26+
private static AppServiceConnection CommunicationService { get; set; }
27+
2628
[AssemblyInitialize]
2729
[TestProperty("CoreClrProfile", ".")]
2830
[TestProperty("RunFixtureAs:Assembly", "ElevatedUserOrSystem")]
@@ -35,6 +37,99 @@ public static void AssemblyInitialize(TestContext testContext)
3537
public static void AssemblyCleanup()
3638
{
3739
TestEnvironment.AssemblyCleanup();
40+
CloseTestApp();
41+
}
42+
43+
private static async Task InitalizeComService()
44+
{
45+
CommunicationService = new AppServiceConnection();
46+
47+
CommunicationService.RequestReceived += CommunicationService_RequestReceived;
48+
49+
// Here, we use the app service name defined in the app service
50+
// provider's Package.appxmanifest file in the <Extension> section.
51+
CommunicationService.AppServiceName = "TestHarnessCommunicationService";
52+
53+
// Use Windows.ApplicationModel.Package.Current.Id.FamilyName
54+
// within the app service provider to get this value.
55+
CommunicationService.PackageFamilyName = "3568ebdf-5b6b-4ddd-bb17-462d614ba50f_gspb8g6x97k2t";
56+
57+
var status = await CommunicationService.OpenAsync();
58+
59+
if (status != AppServiceConnectionStatus.Success)
60+
{
61+
Log.Error("Failed to connect to App Service host.");
62+
CommunicationService = null;
63+
throw new Exception("Failed to connect to App Service host.");
64+
}
65+
}
66+
67+
private static Task<bool> CloseTestApp() => SendMessageToApp(new () { { "Command", "Close" } });
68+
69+
internal static Task<bool> OpenPage(string pageName)
70+
{
71+
Log.Comment("[Harness] Sending Host Page Request: {0}", pageName);
72+
73+
return SendMessageToApp(new()
74+
{
75+
{ "Command", "OpenPage" },
76+
{ "Page", pageName }
77+
});
78+
}
79+
80+
private static async Task<bool> SendMessageToApp(ValueSet message)
81+
{
82+
if (CommunicationService is null)
83+
{
84+
await InitalizeComService();
85+
}
86+
87+
var response = await CommunicationService.SendMessageAsync(message);
88+
89+
return response.Status == AppServiceResponseStatus.Success
90+
&& response.Message.TryGetValue("Status", out var s)
91+
&& s is string status
92+
&& status == "OK";
93+
}
94+
95+
private static void CommunicationService_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
96+
{
97+
var messageDeferral = args.GetDeferral();
98+
var message = args.Request.Message;
99+
string cmd = message["Command"] as string;
100+
101+
try
102+
{
103+
// Return the data to the caller.
104+
if (cmd == "Log")
105+
{
106+
string level = message["Level"] as string;
107+
string msg = message["Message"] as string;
108+
109+
switch (level)
110+
{
111+
case "Comment":
112+
Log.Comment("[Host] {0}", msg);
113+
break;
114+
case "Warning":
115+
Log.Warning("[Host] {0}", msg);
116+
break;
117+
case "Error":
118+
Log.Error("[Host] {0}", msg);
119+
break;
120+
}
121+
}
122+
}
123+
catch (Exception e)
124+
{
125+
Log.Error("Exception receiving message: {0}", e.Message);
126+
}
127+
finally
128+
{
129+
// Complete the deferral so that the platform knows that we're done responding to the app service call.
130+
// Note: for error handling: this must be called even if SendResponseAsync() throws an exception.
131+
messageDeferral.Complete();
132+
}
38133
}
39134
}
40135
}

0 commit comments

Comments
 (0)