/
TestCommon.cs
1011 lines (895 loc) · 40.7 KB
/
TestCommon.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -----------------------------------------------------------------------------
// <copyright file="TestCommon.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. Licensed under the MIT License.
// </copyright>
// -----------------------------------------------------------------------------
namespace AppInstallerCLIE2ETests.Helpers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Reflection;
using System.Security.Principal;
using System.Text;
using System.Threading;
using AppInstallerCLIE2ETests;
using AppInstallerCLIE2ETests.PowerShell;
using Microsoft.Management.Deployment;
using Microsoft.Win32;
using NUnit.Framework;
/// <summary>
/// Test common.
/// </summary>
public static class TestCommon
{
/// <summary>
/// Scope.
/// </summary>
public enum Scope
{
/// <summary>
/// None.
/// </summary>
Unknown,
/// <summary>
/// User.
/// </summary>
User,
/// <summary>
/// Machine.
/// </summary>
Machine,
}
/// <summary>
/// The type of location.
/// </summary>
public enum TestModuleLocation
{
/// <summary>
/// Current user.
/// </summary>
CurrentUser,
/// <summary>
/// All users.
/// </summary>
AllUsers,
/// <summary>
/// Winget module path.
/// </summary>
WinGetModulePath,
/// <summary>
/// Custom.
/// </summary>
Custom,
/// <summary>
/// Default winget configure.
/// </summary>
Default,
}
/// <summary>
/// Gets a value indicating whether the current assembly is executing in an administrative context.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only API")]
public static bool ExecutingAsAdministrator
{
get
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new (identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
/// <summary>
/// Gets a value indicating whether the test is running in the CI build.
/// </summary>
public static bool IsCIEnvironment
{
get
{
return Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER") != null;
}
}
/// <summary>
/// Run winget command.
/// </summary>
/// <param name="command">Command to run.</param>
/// <param name="parameters">Parameters.</param>
/// <param name="stdIn">Optional std in.</param>
/// <param name="timeOut">Optional timeout.</param>
/// <param name="throwOnTimeout">Throw on timeout.</param>
/// <returns>The result of the command.</returns>
public static RunCommandResult RunAICLICommand(string command, string parameters, string stdIn = null, int timeOut = 60000, bool throwOnTimeout = true)
{
string inputMsg =
"AICLI path: " + TestSetup.Parameters.AICLIPath +
" Command: " + command +
" Parameters: " + parameters +
(string.IsNullOrEmpty(stdIn) ? string.Empty : " StdIn: " + stdIn) +
" Timeout: " + timeOut;
TestContext.Out.WriteLine($"Starting command run. {inputMsg}");
return RunAICLICommandViaDirectProcess(command, parameters, stdIn, timeOut, throwOnTimeout);
}
/// <summary>
/// Run command.
/// </summary>
/// <param name="fileName">File name.</param>
/// <param name="args">Args.</param>
/// <param name="timeOut">Time out.</param>
/// <param name="throwOnFailure">If true, throw instead of returning false on a failure.</param>
/// <returns>True if exit code is 0.</returns>
public static bool RunCommand(string fileName, string args = "", int timeOut = 60000, bool throwOnFailure = false)
{
RunCommandResult result = RunCommandWithResult(fileName, args, timeOut);
if (result.ExitCode != 0)
{
TestContext.Out.WriteLine($"Command failed with: {result.ExitCode}");
if (throwOnFailure)
{
throw new RunCommandException(fileName, args, result);
}
return false;
}
else
{
return true;
}
}
/// <summary>
/// Run command with result.
/// </summary>
/// <param name="fileName">File name.</param>
/// <param name="args">Args.</param>
/// <param name="timeOut">Optional timeout.</param>
/// <returns>Command result.</returns>
public static RunCommandResult RunCommandWithResult(string fileName, string args, int timeOut = 60000)
{
TestContext.Out.WriteLine($"Running command: {fileName} {args}");
Process p = new Process();
p.StartInfo = new ProcessStartInfo(fileName, args);
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.Start();
RunCommandResult result = new ();
if (p.WaitForExit(timeOut))
{
result.ExitCode = p.ExitCode;
result.StdOut = p.StandardOutput.ReadToEnd();
result.StdErr = p.StandardError.ReadToEnd();
if (TestSetup.Parameters.VerboseLogging)
{
TestContext.Out.WriteLine($"Command run finished. {fileName} {args} {timeOut}. Output: {result.StdOut} Error: {result.StdErr}");
}
}
else
{
throw new TimeoutException($"Command run timed out. {fileName} {args} {timeOut}");
}
return result;
}
/// <summary>
/// Get test file path.
/// </summary>
/// <param name="fileName">Test file name.</param>
/// <returns>Path of test file.</returns>
public static string GetTestFile(string fileName)
{
return Path.Combine(TestContext.CurrentContext.TestDirectory, fileName);
}
/// <summary>
/// Get test data file path.
/// </summary>
/// <param name="fileName">File name.</param>
/// <returns>Test file data path.</returns>
public static string GetTestDataFile(string fileName)
{
return GetTestFile(Path.Combine("TestData", fileName));
}
/// <summary>
/// Get test work directory. Creates if not exists.
/// </summary>
/// <returns>The work directory.</returns>
public static string GetTestWorkDir()
{
string workDir = Path.Combine(TestContext.CurrentContext.TestDirectory, "WorkDirectory");
Directory.CreateDirectory(workDir);
return workDir;
}
/// <summary>
/// Create random test directory.
/// </summary>
/// <returns>Path of new test directory.</returns>
public static string GetRandomTestDir()
{
string randDir = Path.Combine(GetTestWorkDir(), Path.GetRandomFileName());
Directory.CreateDirectory(randDir);
return randDir;
}
/// <summary>
/// Creates new random file name. File is not created.
/// </summary>
/// <param name="extension">Extension of random file.</param>
/// <returns>Path of random file.</returns>
public static string GetRandomTestFile(string extension)
{
return Path.Combine(GetTestWorkDir(), Path.GetRandomFileName() + extension);
}
/// <summary>
/// Install msix package via PowerShell.
/// </summary>
/// <param name="file">Msix file.</param>
/// <returns>True if installed.</returns>
public static bool InstallMsix(string file)
{
return RunCommand("powershell", $"Add-AppxPackage \"{file}\"", throwOnFailure: true);
}
/// <summary>
/// Install and register msix package via appx manifest.
/// </summary>
/// <param name="packagePath">Path to package.</param>
/// <param name="forceShutdown">Force shutdown.</param>
/// <param name="throwOnFailure">Throw on failure.</param>
/// <returns>True if installed correctly.</returns>
public static bool InstallMsixRegister(string packagePath, bool forceShutdown = false, bool throwOnFailure = true)
{
string manifestFile = Path.Combine(packagePath, "AppxManifest.xml");
var command = $"Add-AppxPackage -Register \"{manifestFile}\"";
if (forceShutdown)
{
command += " -ForceTargetApplicationShutdown";
}
return RunCommand("powershell", command, throwOnFailure: throwOnFailure);
}
/// <summary>
/// Remove msix package.
/// </summary>
/// <param name="name">Package to remove.</param>
/// <param name="isProvisioned">Whether the package is provisioned.</param>
/// <returns>True if removed correctly.</returns>
public static bool RemoveMsix(string name, bool isProvisioned = false)
{
if (isProvisioned)
{
return RunCommand("powershell", $"Get-AppxProvisionedPackage -Online | Where-Object {{$_.PackageName -like \"*{name}*\"}} | Remove-AppxProvisionedPackage -Online -AllUsers") &&
RunCommand("powershell", $"Get-AppxPackage \"{name}\" | Remove-AppxPackage -AllUsers");
}
else
{
return RunCommand("powershell", $"Get-AppxPackage \"{name}\" | Remove-AppxPackage");
}
}
/// <summary>
/// Gets the portable symlink directory.
/// </summary>
/// <param name="scope">Scope.</param>
/// <returns>The path of the symlinks.</returns>
public static string GetPortableSymlinkDirectory(Scope scope)
{
if (scope == Scope.User)
{
return Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), "Microsoft", "WinGet", "Links");
}
else
{
return Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles"), "WinGet", "Links");
}
}
/// <summary>
/// Gets the portable package directory.
/// </summary>
/// <returns>The portable package directory.</returns>
public static string GetPortablePackagesDirectory()
{
return Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), "Microsoft", "WinGet", "Packages");
}
/// <summary>
/// Gets the default download directory for the download command.
/// </summary>
/// <returns>The default download directory.</returns>
public static string GetDefaultDownloadDirectory()
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
}
/// <summary>
/// Gets the checkpoints directory based on whether the command is invoked in desktop package or not.
/// </summary>
/// <returns>The default checkpoints directory.</returns>
public static string GetCheckpointsDirectory()
{
if (TestSetup.Parameters.PackagedContext)
{
return Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), Constants.CheckpointDirectoryPackaged);
}
else
{
return Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), Constants.CheckpointDirectoryUnpackaged);
}
}
/// <summary>
/// Verify portable package.
/// </summary>
/// <param name="installDir">Install dir.</param>
/// <param name="commandAlias">Command alias.</param>
/// <param name="filename">File name.</param>
/// <param name="productCode">Product code.</param>
/// <param name="shouldExist">Should exists.</param>
/// <param name="scope">Scope.</param>
public static void VerifyPortablePackage(
string installDir,
string commandAlias,
string filename,
string productCode,
bool shouldExist,
Scope scope = Scope.User)
{
// When portables are installed, if the exe path is inside a directory it will not be aliased
// if the exe path is at the root level, it will be aliased. Therefore, if either exist, the exe exists
string exePath = Path.Combine(installDir, filename);
string exeAliasedPath = Path.Combine(installDir, commandAlias);
bool exeExists = File.Exists(exePath) || File.Exists(exeAliasedPath);
string symlinkDirectory = GetPortableSymlinkDirectory(scope);
string symlinkPath = Path.Combine(symlinkDirectory, commandAlias);
bool symlinkExists = File.Exists(symlinkPath);
bool portableEntryExists;
RegistryKey baseKey = scope == Scope.User ? Registry.CurrentUser : Registry.LocalMachine;
string uninstallSubKey = Constants.UninstallSubKey;
using (RegistryKey uninstallRegistryKey = baseKey.OpenSubKey(uninstallSubKey, true))
{
RegistryKey portableEntry = uninstallRegistryKey.OpenSubKey(productCode, true);
portableEntryExists = portableEntry != null;
}
bool isAddedToPath;
string pathSubKey = scope == Scope.User ? Constants.PathSubKey_User : Constants.PathSubKey_Machine;
using (RegistryKey environmentRegistryKey = baseKey.OpenSubKey(pathSubKey, true))
{
string pathName = "Path";
var currentPathValue = (string)environmentRegistryKey.GetValue(pathName);
var portablePathValue = symlinkDirectory + ';';
isAddedToPath = currentPathValue.Contains(portablePathValue);
}
if (shouldExist)
{
RunAICLICommand("uninstall", $"--product-code {productCode} --force");
}
Assert.AreEqual(shouldExist, exeExists, $"Expected portable exe path: {exePath}");
Assert.AreEqual(shouldExist, symlinkExists, $"Expected portable symlink path: {symlinkPath}");
Assert.AreEqual(shouldExist, portableEntryExists, $"Expected {productCode} subkey in path: {uninstallSubKey}");
Assert.AreEqual(shouldExist, isAddedToPath, $"Expected path variable: {symlinkDirectory}");
}
/// <summary>
/// Copies log files to the path %TEMP%\E2ETestLogs.
/// </summary>
public static void PublishE2ETestLogs()
{
string tempPath = Path.GetTempPath();
string localAppDataPath = Environment.GetEnvironmentVariable("LocalAppData");
string testLogsPackagedSourcePath = Path.Combine(localAppDataPath, Constants.E2ETestLogsPathPackaged);
string testLogsUnpackagedSourcePath = Path.Combine(tempPath, Constants.E2ETestLogsPathUnpackaged);
string testLogsDestPath = Path.Combine(tempPath, "E2ETestLogs");
string testLogsPackagedDestPath = Path.Combine(testLogsDestPath, "Packaged");
string testLogsUnpackagedDestPath = Path.Combine(testLogsDestPath, "Unpackaged");
if (Directory.Exists(testLogsPackagedSourcePath))
{
CopyDirectory(testLogsPackagedSourcePath, testLogsPackagedDestPath);
}
if (Directory.Exists(testLogsUnpackagedSourcePath))
{
CopyDirectory(testLogsUnpackagedSourcePath, testLogsUnpackagedDestPath);
}
}
/// <summary>
/// Gets the server certificate as a hex string.
/// </summary>
/// <returns>Hex string.</returns>
public static string GetTestServerCertificateHexString()
{
if (string.IsNullOrEmpty(TestSetup.Parameters.LocalServerCertPath))
{
throw new Exception($"{Constants.LocalServerCertPathParameter} not set.");
}
if (!File.Exists(TestSetup.Parameters.LocalServerCertPath))
{
throw new FileNotFoundException(TestSetup.Parameters.LocalServerCertPath);
}
return Convert.ToHexString(File.ReadAllBytes(TestSetup.Parameters.LocalServerCertPath));
}
/// <summary>
/// Verify exe installer correctly.
/// </summary>
/// <param name="installDir">Install directory.</param>
/// <param name="expectedContent">Optional expected content.</param>
/// <returns>True if success.</returns>
public static bool VerifyTestExeInstalled(string installDir, string expectedContent = null)
{
bool verifyInstallSuccess = true;
if (!File.Exists(Path.Combine(installDir, Constants.TestExeInstalledFileName)))
{
TestContext.Out.WriteLine($"TestExeInstalled.exe not found at {installDir}");
verifyInstallSuccess = false;
}
if (verifyInstallSuccess && !string.IsNullOrEmpty(expectedContent))
{
string content = File.ReadAllText(Path.Combine(installDir, Constants.TestExeInstalledFileName));
TestContext.Out.WriteLine($"TestExeInstalled.exe content: {content}");
verifyInstallSuccess = content.Contains(expectedContent);
}
return verifyInstallSuccess;
}
/// <summary>
/// Verify installer and manifest downloaded correctly and cleanup.
/// </summary>
/// <param name="downloadDir">Download directory.</param>
/// <param name="name">Package name.</param>
/// <param name="version">Package version.</param>
/// <param name="arch">Installer architecture.</param>
/// <param name="scope">Installer scope.</param>
/// <param name="installerType">Installer type.</param>
/// <param name="locale">Installer locale.</param>
/// <param name="isArchive">Boolean value indicating whether the installer is an archive.</param>
/// <param name="cleanup">Boolean value indicating whether to remove the installer file and directory.</param>
/// <returns>True if success.</returns>
public static bool VerifyInstallerDownload(
string downloadDir,
string name,
string version,
Windows.System.ProcessorArchitecture arch,
Scope scope,
PackageInstallerType installerType,
string locale = null,
bool isArchive = false,
bool cleanup = true)
{
string expectedFileName = $"{name}_{version}";
if (scope != Scope.Unknown)
{
expectedFileName += $"_{scope}";
}
expectedFileName += $"_{arch}_{installerType}";
if (!string.IsNullOrEmpty(locale))
{
expectedFileName += $"_{locale}";
}
string installerExtension;
if (isArchive)
{
installerExtension = ".zip";
}
else
{
installerExtension = installerType switch
{
PackageInstallerType.Msi => ".msi",
PackageInstallerType.Msix => ".msix",
_ => ".exe"
};
}
string installerDownloadPath = Path.Combine(downloadDir, expectedFileName + installerExtension);
string manifestDownloadPath = Path.Combine(downloadDir, expectedFileName + ".yaml");
bool downloadResult = false;
if (Directory.Exists(downloadDir) && File.Exists(installerDownloadPath) && File.Exists(manifestDownloadPath))
{
downloadResult = true;
if (cleanup)
{
File.Delete(installerDownloadPath);
File.Delete(manifestDownloadPath);
Directory.Delete(downloadDir, true);
}
}
return downloadResult;
}
/// <summary>
/// Verify exe installer correctly and then uninstall it.
/// </summary>
/// <param name="installDir">Install directory.</param>
/// <param name="expectedContent">Optional expected content.</param>
/// <returns>True if success.</returns>
public static bool VerifyTestExeInstalledAndCleanup(string installDir, string expectedContent = null)
{
bool verifyInstallSuccess = VerifyTestExeInstalled(installDir, expectedContent);
// Always try clean up and ignore clean up failure
var uninstallerPath = Path.Combine(installDir, Constants.TestExeUninstallerFileName);
if (File.Exists(uninstallerPath))
{
RunCommand(Path.Combine(installDir, Constants.TestExeUninstallerFileName));
}
return verifyInstallSuccess;
}
/// <summary>
/// Verify msi installed correctly.
/// </summary>
/// <param name="installDir">Installed directory.</param>
/// <returns>True if success.</returns>
public static bool VerifyTestMsiInstalledAndCleanup(string installDir)
{
string pathToCheck = Path.Combine(installDir, Constants.AppInstallerTestExeInstallerExe);
if (!File.Exists(pathToCheck))
{
TestContext.Out.WriteLine($"File not found: {pathToCheck}");
return false;
}
return RunCommand("msiexec.exe", $"/qn /x {Constants.MsiInstallerProductCode}");
}
/// <summary>
/// Verify msix installed correctly.
/// </summary>
/// <param name="isProvisioned">Whether the package is provisioned.</param>
/// <returns>True if success.</returns>
public static bool VerifyTestMsixInstalledAndCleanup(bool isProvisioned = false)
{
var result = RunCommandWithResult("powershell", $"Get-AppxPackage {Constants.MsixInstallerName}");
if (!result.StdOut.Contains(Constants.MsixInstallerName))
{
return false;
}
if (isProvisioned)
{
result = RunCommandWithResult("powershell", $"Get-AppxProvisionedPackage -Online | Where-Object {{$_.PackageName -like \"*{Constants.MsixInstallerName}*\"}}");
if (!result.StdOut.Contains(Constants.MsixInstallerName))
{
return false;
}
}
return RemoveMsix(Constants.MsixInstallerName, isProvisioned);
}
/// <summary>
/// Verify test exe uninstalled.
/// </summary>
/// <param name="installDir">Installed directory.</param>
/// <returns>True if success.</returns>
public static bool VerifyTestExeUninstalled(string installDir)
{
return File.Exists(Path.Combine(installDir, Constants.TestExeUninstalledFileName));
}
/// <summary>
/// Verify msi uninstalled.
/// </summary>
/// <param name="installDir">Install directory.</param>
/// <returns>True if success.</returns>
public static bool VerifyTestMsiUninstalled(string installDir)
{
return !File.Exists(Path.Combine(installDir, Constants.AppInstallerTestExeInstallerExe));
}
/// <summary>
/// Verify msix uninstalled.
/// </summary>
/// <param name="isProvisioned">Whether the package is provisioned.</param>
/// <returns>True if success.</returns>
public static bool VerifyTestMsixUninstalled(bool isProvisioned = false)
{
bool isUninstalled = false;
var result = RunCommandWithResult("powershell", $"Get-AppxPackage {Constants.MsixInstallerName}");
isUninstalled = string.IsNullOrWhiteSpace(result.StdOut);
if (isProvisioned)
{
result = RunCommandWithResult("powershell", $"Get-AppxProvisionedPackage -Online | Where-Object {{$_.PackageName -like \"*{Constants.MsixInstallerName}*\"}}");
isUninstalled = isUninstalled && string.IsNullOrWhiteSpace(result.StdOut);
}
return isUninstalled;
}
/// <summary>
/// Modify uninstalled registry key.
/// </summary>
/// <param name="productCode">Product code.</param>
/// <param name="name">Name.</param>
/// <param name="value">Value.</param>
public static void ModifyPortableARPEntryValue(string productCode, string name, string value)
{
using (RegistryKey uninstallRegistryKey = Registry.CurrentUser.OpenSubKey(Constants.UninstallSubKey, true))
{
RegistryKey entry = uninstallRegistryKey.OpenSubKey(productCode, true);
entry.SetValue(name, value);
}
}
/// <summary>
/// Set up test source.
/// </summary>
/// <param name="useGroupPolicyForTestSource">Use group policy.</param>
public static void SetupTestSource(bool useGroupPolicyForTestSource = false)
{
RunAICLICommand("source reset", "--force");
RunAICLICommand("source remove", Constants.DefaultWingetSourceName);
RunAICLICommand("source remove", Constants.DefaultMSStoreSourceName);
// TODO: If/when cert pinning is implemented on the packaged index source, useGroupPolicyForTestSource should be set to default true
// to enable testing it by default. Until then, leaving this here...
if (useGroupPolicyForTestSource)
{
GroupPolicyHelper.EnableAdditionalSources.SetEnabledList(new GroupPolicyHelper.GroupPolicySource[]
{
new GroupPolicyHelper.GroupPolicySource
{
Name = Constants.TestSourceName,
Arg = Constants.TestSourceUrl,
Type = Constants.TestSourceType,
Data = Constants.TestSourceIdentifier,
Identifier = Constants.TestSourceIdentifier,
CertificatePinning = new GroupPolicyHelper.GroupPolicyCertificatePinning
{
Chains = new GroupPolicyHelper.GroupPolicyCertificatePinningChain[]
{
new GroupPolicyHelper.GroupPolicyCertificatePinningChain
{
Chain = new GroupPolicyHelper.GroupPolicyCertificatePinningDetails[]
{
new GroupPolicyHelper.GroupPolicyCertificatePinningDetails
{
Validation = new string[] { "publickey" },
EmbeddedCertificate = GetTestServerCertificateHexString(),
},
},
},
},
},
},
});
}
else
{
GroupPolicyHelper.EnableAdditionalSources.SetNotConfigured();
RunAICLICommand("source add", $"{Constants.TestSourceName} {Constants.TestSourceUrl}");
}
Thread.Sleep(2000);
}
/// <summary>
/// Tear down test source.
/// </summary>
public static void TearDownTestSource()
{
RunAICLICommand("source remove", Constants.TestSourceName);
RunAICLICommand("source reset", "--force");
}
/// <summary>
/// Ensures that a module is in the desired state.
/// </summary>
/// <param name="moduleName">The module.</param>
/// <param name="present">Whether the module is present or not.</param>
/// <param name="repository">The repository to get the module from if needed.</param>
/// <param name="location">The location to install the module.</param>
public static void EnsureModuleState(string moduleName, bool present, string repository = null, TestCommon.TestModuleLocation location = TestModuleLocation.CurrentUser)
{
string wingetModulePath = TestCommon.GetExpectedModulePath(TestModuleLocation.WinGetModulePath);
string customPath = TestCommon.GetExpectedModulePath(TestModuleLocation.Custom);
ICollection<PSModuleInfo> e2eModule;
bool isPresent = false;
{
using var pwsh = new PowerShellHost();
pwsh.AddModulePath($"{wingetModulePath};{customPath}");
e2eModule = pwsh.PowerShell.AddCommand("Get-Module").AddParameter("Name", moduleName).AddParameter("ListAvailable").Invoke<PSModuleInfo>();
isPresent = e2eModule.Any();
}
if (isPresent)
{
// If the module was saved in a different location we can't Uninstall-Module.
foreach (var module in e2eModule)
{
var moduleBase = module.Path;
while (Path.GetFileName(moduleBase) != moduleName)
{
moduleBase = Path.GetDirectoryName(moduleBase);
}
if (!present)
{
Directory.Delete(moduleBase, true);
}
else
{
// Must be present in the right location.
var expectedLocation = TestCommon.GetExpectedModulePath(location);
if (!moduleBase.StartsWith(expectedLocation))
{
Directory.Delete(moduleBase, true);
isPresent = false;
}
}
}
}
if (!isPresent && present)
{
if (location == TestModuleLocation.CurrentUser ||
location == TestModuleLocation.AllUsers)
{
using var pwsh = new PowerShellHost();
pwsh.AddModulePath($"{wingetModulePath};{customPath}");
pwsh.PowerShell.AddCommand("Install-Module").AddParameter("Name", moduleName).AddParameter("Force");
if (!string.IsNullOrEmpty(repository))
{
pwsh.PowerShell.AddParameter("Repository", repository);
}
if (location == TestModuleLocation.AllUsers)
{
pwsh.PowerShell.AddParameter("Scope", "AllUsers");
}
_ = pwsh.PowerShell.Invoke();
}
else
{
string path = customPath;
if (location == TestModuleLocation.WinGetModulePath ||
location == TestModuleLocation.Default)
{
path = wingetModulePath;
}
using var pwsh = new PowerShellHost();
pwsh.AddModulePath($"{wingetModulePath};{customPath}");
pwsh.PowerShell.AddCommand("Save-Module").AddParameter("Name", moduleName).AddParameter("Path", path).AddParameter("Force");
if (!string.IsNullOrEmpty(repository))
{
pwsh.PowerShell.AddParameter("Repository", repository);
}
_ = pwsh.PowerShell.Invoke();
}
}
}
/// <summary>
/// Creates an ARP entry from the given values.
/// </summary>
/// <param name="productCode">Product code of the entry.</param>
/// <param name="properties">The properties to set in the entry.</param>
/// <param name="scope">Scope of the entry.</param>
public static void CreateARPEntry(
string productCode,
object properties,
Scope scope = Scope.User)
{
RegistryKey baseKey = scope == Scope.User ? Registry.CurrentUser : Registry.LocalMachine;
using (RegistryKey uninstallRegistryKey = baseKey.OpenSubKey(Constants.UninstallSubKey, true))
{
RegistryKey entry = uninstallRegistryKey.CreateSubKey(productCode, true);
foreach (PropertyInfo property in properties.GetType().GetProperties())
{
entry.SetValue(property.Name, property.GetValue(properties));
}
}
}
/// <summary>
/// Removes an ARP entry.
/// </summary>
/// <param name="productCode">Product code of the entry.</param>
/// <param name="scope">Scope of the entry.</param>
public static void RemoveARPEntry(
string productCode,
Scope scope = Scope.User)
{
RegistryKey baseKey = scope == Scope.User ? Registry.CurrentUser : Registry.LocalMachine;
using (RegistryKey uninstallRegistryKey = baseKey.OpenSubKey(Constants.UninstallSubKey, true))
{
uninstallRegistryKey.DeleteSubKey(productCode);
}
}
/// <summary>
/// Copies the contents of a given directory from a source path to a destination path.
/// </summary>
/// <param name="sourceDirName">Source directory name.</param>
/// <param name="destDirName">Destination directory name.</param>
public static void CopyDirectory(string sourceDirName, string destDirName)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
CopyDirectory(subdir.FullName, temppath);
}
}
/// <summary>
/// Gets the expected module path.
/// </summary>
/// <param name="location">Location.</param>
/// <returns>The expected path of the module.</returns>
public static string GetExpectedModulePath(TestModuleLocation location)
{
switch (location)
{
case TestModuleLocation.CurrentUser:
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"PowerShell\Modules");
case TestModuleLocation.AllUsers:
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"PowerShell\Modules");
case TestModuleLocation.WinGetModulePath:
case TestModuleLocation.Default:
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\WinGet\Configuration\Modules");
case TestModuleLocation.Custom:
return Path.Combine(Path.GetTempPath(), "E2ECustomModules");
default:
throw new ArgumentException(location.ToString());
}
}
/// <summary>
/// Run winget command via direct process.
/// </summary>
/// <param name="command">Command to run.</param>
/// <param name="parameters">Parameters.</param>
/// <param name="stdIn">Optional std in.</param>
/// <param name="timeOut">Optional timeout.</param>
/// <param name="throwOnTimeout">Throw on timeout.</param>
/// <returns>The result of the command.</returns>
private static RunCommandResult RunAICLICommandViaDirectProcess(string command, string parameters, string stdIn, int timeOut, bool throwOnTimeout)
{
RunCommandResult result = new ();
Process p = new Process();
p.StartInfo = new ProcessStartInfo(TestSetup.Parameters.AICLIPath, command + ' ' + parameters);
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
StringBuilder outputData = new ();
p.OutputDataReceived += (sender, args) =>
{
if (args.Data != null)
{
outputData.AppendLine(args.Data);
}
};
p.StartInfo.RedirectStandardError = true;
StringBuilder errorData = new ();
p.ErrorDataReceived += (sender, args) =>
{
if (args.Data != null)
{
errorData.AppendLine(args.Data);
}
};
if (!string.IsNullOrEmpty(stdIn))
{
p.StartInfo.RedirectStandardInput = true;
}
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
if (!string.IsNullOrEmpty(stdIn))
{
p.StandardInput.Write(stdIn);
}
if (p.WaitForExit(timeOut))
{
// According to documentation, this extra call will ensure that the redirected streams
// have finished reading all of the data.
p.WaitForExit();
result.ExitCode = p.ExitCode;
result.StdOut = outputData.ToString();
result.StdErr = errorData.ToString();
TestContext.Out.WriteLine("Command run completed with exit code: " + result.ExitCode);
if (!string.IsNullOrEmpty(result.StdErr))
{
TestContext.Error.WriteLine("Command run error. Error: " + result.StdErr);
}
if (TestSetup.Parameters.VerboseLogging && !string.IsNullOrEmpty(result.StdOut))
{
TestContext.Out.WriteLine("Command run output. Output: " + result.StdOut);
}
}
else if (throwOnTimeout)
{
throw new TimeoutException($"Direct winget command run timed out: {command} {parameters}");
}
return result;
}
/// <summary>
/// Run command result.
/// </summary>
public struct RunCommandResult
{
/// <summary>
/// Exit code.
/// </summary>
public int ExitCode;
/// <summary>