| 1 | // Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. |
| 2 | |
| 3 | namespace WixTestTools |
| 4 | { |
| 5 | using System; |
| 6 | using System.Security.Principal; |
| 7 | using WixInternal.TestSupport.XunitExtensions; |
| 8 | using System.Runtime.InteropServices; |
| 9 | |
| 10 | public class RuntimeFactAttribute : SkippableFactAttribute |
| 11 | { |
| 12 | const string RequiredEnvironmentVariableName = "RuntimeTestsEnabled"; |
| 13 | |
| 14 | public static bool RuntimeTestsEnabled { get; } |
| 15 | public static bool RunningAsAdministrator { get; } |
| 16 | public static bool RunningOnWindowsServer { get; } |
| 17 | |
| 18 | [DllImport("shlwapi.dll", SetLastError = true, EntryPoint = "#437")] |
| 19 | private static extern bool IsOS(int os); |
| 20 | private static bool IsWindowsServer() |
| 21 | { |
| 22 | const int OS_ANYSERVER = 29; |
| 23 | return IsOS(OS_ANYSERVER); |
| 24 | } |
| 25 | |
| 26 | |
| 27 | static RuntimeFactAttribute() |
| 28 | { |
| 29 | using var identity = WindowsIdentity.GetCurrent(); |
| 30 | var principal = new WindowsPrincipal(identity); |
| 31 | RunningAsAdministrator = principal.IsInRole(WindowsBuiltInRole.Administrator); |
| 32 | |
| 33 | var testsEnabledString = Environment.GetEnvironmentVariable(RequiredEnvironmentVariableName); |
| 34 | RuntimeTestsEnabled = Boolean.TryParse(testsEnabledString, out var testsEnabled) && testsEnabled; |
| 35 | |
| 36 | RunningOnWindowsServer = IsWindowsServer(); |
| 37 | } |
| 38 | |
| 39 | private bool _RequireWindowsServer; |
| 40 | public bool RequireWindowsServer |
| 41 | { |
| 42 | get |
| 43 | { |
| 44 | return _RequireWindowsServer; |
| 45 | } |
| 46 | set |
| 47 | { |
| 48 | _RequireWindowsServer = value; |
| 49 | if (_RequireWindowsServer && !RunningOnWindowsServer) |
| 50 | { |
| 51 | this.Skip = $"These tests are only run on Windows Server"; |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | public RuntimeFactAttribute() |
| 57 | { |
| 58 | if (!RuntimeTestsEnabled || !RunningAsAdministrator) |
| 59 | { |
| 60 | this.Skip = $"These tests must run elevated ({(RunningAsAdministrator ? "passed" : "failed")}). These tests affect machine state. To accept the consequences, set the {RequiredEnvironmentVariableName} environment variable to true ({(RuntimeTestsEnabled ? "passed" : "failed")})."; |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | } |