1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 
5 using System.Diagnostics;
6 using System.IO;
7 using Xunit;
8 
9 namespace System.Tests
10 {
11     public class Environment_Exit : RemoteExecutorTestBase
12     {
13         public static object[][] ExitCodeValues = new object[][]
14         {
15             new object[] { 0 },
16             new object[] { 1 },
17             new object[] { 42 },
18             new object[] { -1 },
19             new object[] { -45 },
20             new object[] { 255 },
21         };
22 
23         [Theory]
24         [MemberData(nameof(ExitCodeValues))]
CheckExitCode(int expectedExitCode)25         public static void CheckExitCode(int expectedExitCode)
26         {
27             RemoteInvoke(s => int.Parse(s), expectedExitCode.ToString(), new RemoteInvokeOptions { ExpectedExitCode = expectedExitCode }).Dispose();
28         }
29 
30         [Theory]
31         [MemberData(nameof(ExitCodeValues))]
ExitCode_Roundtrips(int exitCode)32         public static void ExitCode_Roundtrips(int exitCode)
33         {
34             Environment.ExitCode = exitCode;
35             Assert.Equal(exitCode, Environment.ExitCode);
36 
37             Environment.ExitCode = 0; // in case the test host has a void returning Main
38         }
39 
40         [Theory]
41         [InlineData(1)] // setting ExitCode and exiting Main
42         [InlineData(2)] // setting ExitCode both from Main and from an Unloading event handler.
43         [InlineData(3)] // using Exit(exitCode)
44         [ActiveIssue("https://github.com/dotnet/corefx/issues/21415", TargetFrameworkMonikers.UapNotUapAot)]
45         [ActiveIssue("https://github.com/dotnet/corefx/issues/20387 - ILC test pipeline does not accommodate tests in child processes built into custom assemblies.", TargetFrameworkMonikers.UapAot)]
ExitCode_VoidMainAppReturnsSetValue(int mode)46         public static void ExitCode_VoidMainAppReturnsSetValue(int mode)
47         {
48             int expectedExitCode = 123;
49             const string AppName = "VoidMainWithExitCodeApp.exe";
50             var psi = new ProcessStartInfo();
51             if (PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative)
52             {
53                 psi.FileName = AppName;
54                 psi.Arguments = $"{expectedExitCode} {mode}";
55             }
56             else
57             {
58                 psi.FileName = HostRunner;
59                 psi.Arguments = $"{AppName} {expectedExitCode} {mode}";
60             }
61 
62             using (Process p = Process.Start(psi))
63             {
64                 p.WaitForExit();
65                 Assert.Equal(expectedExitCode, p.ExitCode);
66             }
67         }
68     }
69 }
70