Beispiel #1
0
        private static void Main()
        {
            bool isFirstInstance;
            using(var mutex = new Mutex(true, "gitter-uac-instance", out isFirstInstance))
            {
                if(isFirstInstance)
                {
                    var args = Environment.GetCommandLineArgs();
                    if(args == null || args.Length < 2 || args[1] != "--remoting")
                        return;

                    ChannelServices.RegisterChannel(
                        new IpcChannel(
                            new Dictionary<string, string>
                            {
                                { "portName", RemotingChannelName }
                            },
                            new BinaryClientFormatterSinkProvider(),
                            new BinaryServerFormatterSinkProvider()
                            {
                                TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full,
                            }),
                        false);

                    RemotingConfiguration.RegisterWellKnownServiceType(
                        typeof(RemoteExecutor), RemotingObjectName, WellKnownObjectMode.Singleton);

                    _executor = (RemoteExecutor)Activator.GetObject(typeof(RemoteExecutor),
                        string.Format(@"ipc://{0}/{1}", RemotingChannelName, RemotingObjectName));
                    _executor.ExitEvent.WaitOne();
                    _executor.ExitEvent.Close();
                }
            }
        }
Beispiel #2
0
        public void PredefinedCulturesOnlyEnvVarTest(string predefinedCulturesOnlyEnvVar, string cultureName)
        {
            var psi = new ProcessStartInfo();

            psi.Environment.Clear();

            psi.Environment.Add("DOTNET_SYSTEM_GLOBALIZATION_PREDEFINED_CULTURES_ONLY", predefinedCulturesOnlyEnvVar);

            RemoteExecutor.Invoke((culture, predefined) =>
            {
                if (predefined == "1")
                {
                    AssertExtensions.Throws <CultureNotFoundException>(() => new CultureInfo(culture));
                }
                else
                {
                    CultureInfo ci = new CultureInfo(culture);
                    Assert.Equal(culture, ci.Name);
                }
            }, cultureName, predefinedCulturesOnlyEnvVar, new RemoteInvokeOptions {
                StartInfo = psi
            }).Dispose();
        }
Beispiel #3
0
        public void GetTypeByName()
        {
            RemoteInvokeOptions options = new RemoteInvokeOptions();

            RemoteExecutor.Invoke(() =>
            {
                string test1 = testtype;
                Type t1      = Type.GetType(test1,
                                            (aName) => aName.Name == "Foo" ?
                                            Assembly.LoadFrom(s_testAssemblyPath) : null,
                                            typeloader,
                                            true
                                            );

                Assert.NotNull(t1);

                string test2 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program, TestLoadAssembly]]";
                Type t2      = Type.GetType(test2, assemblyloader, typeloader, true);

                Assert.NotNull(t2);
                Assert.Equal(t1, t2);
            }, options).Dispose();
        }
Beispiel #4
0
        public void SdcaL1UpdateUTest(string mode, string test, string scale, Dictionary <string, string> environmentVariables)
        {
            RemoteExecutor.RemoteInvoke((arg0, arg1, arg2) =>
            {
                CheckProperFlag(arg0);
                float defaultScale = float.Parse(arg2, CultureInfo.InvariantCulture);
                float[] src        = (float[])_testArrays[int.Parse(arg1)].Clone();
                float[] v          = (float[])src.Clone();
                float[] w          = (float[])src.Clone();
                float[] expected   = (float[])w.Clone();

                for (int i = 0; i < expected.Length; i++)
                {
                    float value = src[i] * (1 + defaultScale);
                    expected[i] = Math.Abs(value) > defaultScale ? (value > 0 ? value - defaultScale : value + defaultScale) : 0;
                }

                CpuMathUtils.SdcaL1UpdateDense(defaultScale, src.Length, src, defaultScale, v, w);
                var actual = w;
                Assert.Equal(expected, actual, _comparer);
                return(RemoteExecutor.SuccessExitCode);
            }, mode, test, scale, new RemoteInvokeOptions(environmentVariables));
        }
        public void HttpClientUsesSslCertEnvironmentVariables()
        {
            // We set SSL_CERT_DIR and SSL_CERT_FILE to empty locations.
            // The HttpClient should fail to validate the server certificate.
            var psi = new ProcessStartInfo();
            string sslCertDir = GetTestFilePath();
            Directory.CreateDirectory(sslCertDir);
            psi.Environment.Add("SSL_CERT_DIR", sslCertDir);

            string sslCertFile = GetTestFilePath();
            File.WriteAllText(sslCertFile, "");
            psi.Environment.Add("SSL_CERT_FILE", sslCertFile);

            RemoteExecutor.Invoke(async (useVersionString) =>
            {
                const string Url = "https://www.microsoft.com";

                using (HttpClient client = CreateHttpClient(useVersionString))
                {
                    await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Url));
                }
            }, UseVersion.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose();
        }
Beispiel #6
0
    public void InputEncoding_SetWithInInitialized_ResetsIn()
    {
        RemoteExecutor.Invoke(() =>
        {
            // Initialize Console.In
            TextReader inReader = Console.In;
            Assert.NotNull(inReader);
            Assert.Same(inReader, Console.In);

            // Change the InputEncoding
            Console.InputEncoding = Encoding.Unicode; // Not ASCII: not supported by Windows Nano
            Assert.Equal(Encoding.Unicode, Console.InputEncoding);

            if (PlatformDetection.IsWindows)
            {
                // Console.set_InputEncoding is effectively a nop on Unix,
                // so although the reader accessed by Console.In will be reset,
                // it'll be re-initialized on re-access to the same singleton,
                // (assuming input isn't redirected).
                Assert.NotSame(inReader, Console.In);
            }
        }).Dispose();
    }
        public void Ctor_TypeDescriptorNotFound_ExceptionFallback(Type type, bool returnNull, string stringToConvert, int expectedValue)
        {
            RemoteExecutor.Invoke((innerType, innerReturnNull, innerStringToConvert, innerExpectedValue) =>
            {
                FieldInfo s_convertFromInvariantString = typeof(DefaultValueAttribute).GetField("s_convertFromInvariantString", BindingFlags.GetField | Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Static);
                Assert.NotNull(s_convertFromInvariantString);

                // simulate TypeDescriptor.ConvertFromInvariantString not found
                s_convertFromInvariantString.SetValue(null, new object());

                // we fallback to empty catch in DefaultValueAttribute constructor
                DefaultValueAttribute attr = new DefaultValueAttribute(Type.GetType(innerType), innerStringToConvert);

                if (bool.Parse(innerReturnNull))
                {
                    Assert.Null(attr.Value);
                }
                else
                {
                    Assert.Equal(int.Parse(innerExpectedValue), attr.Value);
                }
            }, type.ToString(), returnNull.ToString(), stringToConvert, expectedValue.ToString()).Dispose();
        }
        public void AddSUTest(string mode, string test, Dictionary <string, string> environmentVariables)
        {
            RemoteExecutor.RemoteInvoke((arg0, arg1) =>
            {
                CheckProperFlag(arg0);
                float[] src      = (float[])_testArrays[int.Parse(arg1)].Clone();
                float[] dst      = (float[])src.Clone();
                int[] idx        = _testIndexArray;
                int limit        = int.Parse(arg1) == 2 ? 9 : 18;
                float[] expected = (float[])dst.Clone();

                for (int i = 0; i < limit; i++)
                {
                    int index        = idx[i];
                    expected[index] += src[i];
                }

                CpuMathUtils.Add(src, idx, dst, limit);
                var actual = dst;
                Assert.Equal(expected, actual, _comparer);
                return(RemoteExecutor.SuccessExitCode);
            }, mode, test, new RemoteInvokeOptions(environmentVariables));
        }
        public void FailFast_ExceptionStackTrace_StackOverflowException()
        {
            // Test using another type of exception
            var psi = new ProcessStartInfo();

            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;

            using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(
                       () => { Environment.FailFast("message", new StackOverflowException("SO exception")); return(RemoteExecutor.SuccessExitCode); },
                       new RemoteInvokeOptions {
                StartInfo = psi
            }))
            {
                Process p = handle.Process;
                handle.Process = null;
                p.WaitForExit();
                string consoleOutput = p.StandardError.ReadToEnd();
                Assert.Contains("Exception details:", consoleOutput);
                Assert.Contains("StackOverflowException", consoleOutput);
                Assert.Contains("SO exception", consoleOutput);
            }
        }
        public void CurrentCulture()
        {
            if (PlatformDetection.IsNetNative && !PlatformDetection.IsInAppContainer) // Tide us over until .NET Native ILC tests run are run inside an appcontainer.
            {
                return;
            }

            RemoteExecutor.Invoke(() =>
            {
                CultureInfo newCulture     = new CultureInfo(CultureInfo.CurrentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP");
                CultureInfo.CurrentCulture = newCulture;

                Assert.Equal(CultureInfo.CurrentCulture, newCulture);

                newCulture = new CultureInfo("de-DE_phoneb");
                CultureInfo.CurrentCulture = newCulture;

                Assert.Equal(CultureInfo.CurrentCulture, newCulture);
                Assert.Equal("de-DE_phoneb", newCulture.CompareInfo.Name);

                return(RemoteExecutor.SuccessExitCode);
            }).Dispose();
        }
        public void AddScaleSUTest(string mode, string test, string scale, Dictionary <string, string> environmentVariables)
        {
            RemoteExecutor.RemoteInvoke((arg0, arg1, arg2) =>
            {
                CheckProperFlag(arg0);
                float defaultScale = float.Parse(arg2, CultureInfo.InvariantCulture);
                float[] src        = (float[])_testArrays[int.Parse(arg1)].Clone();
                float[] dst        = (float[])src.Clone();
                int[] idx          = _testIndexArray;
                int limit          = int.Parse(arg1) == 2 ? 9 : 18;
                float[] expected   = (float[])dst.Clone();

                CpuMathUtils.AddScale(defaultScale, src, idx, dst, limit);
                for (int i = 0; i < limit; i++)
                {
                    int index        = idx[i];
                    expected[index] += defaultScale * src[i];
                }

                Assert.Equal(expected, dst, _comparer);
                return(RemoteExecutor.SuccessExitCode);
            }, mode, test, scale, new RemoteInvokeOptions(environmentVariables));
        }
        public void CurrentCulture_BasedOnLangEnvVar(string langEnvVar, string expectedCultureName)
        {
            var psi = new ProcessStartInfo();

            psi.Environment.Clear();

            CopyEssentialTestEnvironment(psi.Environment);

            psi.Environment["LANG"] = langEnvVar;

            RemoteExecutor.Invoke(expected =>
            {
                Assert.NotNull(CultureInfo.CurrentCulture);
                Assert.NotNull(CultureInfo.CurrentUICulture);

                Assert.Equal(expected, CultureInfo.CurrentCulture.Name);
                Assert.Equal(expected, CultureInfo.CurrentUICulture.Name);

                return(RemoteExecutor.SuccessExitCode);
            }, expectedCultureName, new RemoteInvokeOptions {
                StartInfo = psi
            }).Dispose();
        }
Beispiel #13
0
        public static void CurrentPrincipal_SetNull()
        {
            // We run test on remote process because we need to set same principal policy
            // On netfx default principal policy is PrincipalPolicy.UnauthenticatedPrincipal
            RemoteExecutor.Invoke(() =>
            {
                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.NoPrincipal);

                Assert.Null(Thread.CurrentPrincipal);

                Thread.CurrentPrincipal = null;
                Assert.Null(Thread.CurrentPrincipal);

                Thread.CurrentPrincipal = new ClaimsPrincipal();
                Assert.IsType <ClaimsPrincipal>(Thread.CurrentPrincipal);

                Thread.CurrentPrincipal = null;
                Assert.Null(Thread.CurrentPrincipal);

                Thread.CurrentPrincipal = new ClaimsPrincipal();
                Assert.IsType <ClaimsPrincipal>(Thread.CurrentPrincipal);
            }).Dispose();
        }
Beispiel #14
0
        public void PingPong(EventResetMode mode)
        {
            // Create names for the two events
            string outboundName = Guid.NewGuid().ToString("N");
            string inboundName  = Guid.NewGuid().ToString("N");

            // Create the two events and the other process with which to synchronize
            using (var inbound = new EventWaitHandle(true, mode, inboundName))
                using (var outbound = new EventWaitHandle(false, mode, outboundName))
                    using (var remote = RemoteExecutor.Invoke(PingPong_OtherProcess, mode.ToString(), outboundName, inboundName))
                    {
                        // Repeatedly wait for one event and then set the other
                        for (int i = 0; i < 10; i++)
                        {
                            Assert.True(inbound.WaitOne(RemoteExecutor.FailWaitTimeoutMilliseconds));
                            if (mode == EventResetMode.ManualReset)
                            {
                                inbound.Reset();
                            }
                            outbound.Set();
                        }
                    }
        }
Beispiel #15
0
        public void ToBitmap_PngIconNotSupportedInSwitches_ThrowsArgumentOutOfRangeException()
        {
            void VerifyPngNotSupported()
            {
                using (Icon icon = GetPngIcon())
                {
                    AssertExtensions.Throws <ArgumentOutOfRangeException>(null, () => icon.ToBitmap());
                }
            }

            if (RemoteExecutor.IsSupported && (!AppContext.TryGetSwitch(DontSupportPngFramesInIcons, out bool isEnabled) || !isEnabled))
            {
                RemoteExecutor.Invoke(() =>
                {
                    AppContext.SetSwitch(DontSupportPngFramesInIcons, true);
                    VerifyPngNotSupported();
                }).Dispose();
            }
            else
            {
                VerifyPngNotSupported();
            }
        }
Beispiel #16
0
        public void ProfileOptimization_CheckFileExists()
        {
            string profileFile = GetTestFileName();

            RemoteExecutor.Invoke((_profileFile) =>
            {
                // tracking down why test sporadically fails on RedHat69
                // write to the file first to check permissions
                // See https://github.com/dotnet/corefx/issues/31792
                File.WriteAllText(_profileFile, "42");

                // Verify this write succeeded
                Assert.True(File.Exists(_profileFile), $"'{_profileFile}' does not exist");
                Assert.True(new FileInfo(_profileFile).Length > 0, $"'{_profileFile}' is empty");

                // Delete the file and verify the delete
                File.Delete(_profileFile);
                Assert.True(!File.Exists(_profileFile), $"'{_profileFile} ought to not exist now");

                // Perform the test work
                ProfileOptimization.SetProfileRoot(Path.GetDirectoryName(_profileFile));
                ProfileOptimization.StartProfile(Path.GetFileName(_profileFile));
            }, profileFile).Dispose();

            // profileFile should deterministically exist now -- if not, wait 5 seconds
            bool existed = File.Exists(profileFile);

            if (!existed)
            {
                Thread.Sleep(5000);
            }

            Assert.True(File.Exists(profileFile), $"'{profileFile}' does not exist");
            Assert.True(new FileInfo(profileFile).Length > 0, $"'{profileFile}' is empty");

            Assert.True(existed, $"'{profileFile}' did not immediately exist, but did exist 5 seconds later");
        }
    public void ExitDetectionNotBlockedByHandler()
    {
        // .NET Core respects ignored disposition for SIGINT/SIGQUIT.
        if (IsSignalIgnored(SIGINT))
        {
            return;
        }

        RemoteExecutor.Invoke(() =>
        {
            var mre = new ManualResetEventSlim();
            var tcs = new TaskCompletionSource();

            // CancelKeyPress is triggered by SIGINT/SIGQUIT
            Console.CancelKeyPress += (sender, e) =>
            {
                tcs.SetResult();
                // Block CancelKeyPress
                Assert.True(mre.Wait(WaitFailTestTimeoutSeconds * 1000));
            };

            // Generate CancelKeyPress
            Assert.Equal(0, kill(Environment.ProcessId, SIGINT));
            // Wait till we block CancelKeyPress
            Assert.True(tcs.Task.Wait(WaitFailTestTimeoutSeconds * 1000));

            // Create a process and wait for it to exit.
            using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => RemoteExecutor.SuccessExitCode))
            {
                // Process exit is detected on SIGCHLD
                Assert.Equal(RemoteExecutor.SuccessExitCode, handle.ExitCode);
            }

            // Release CancelKeyPress
            mre.Set();
        }).Dispose();
    }
        public void PingPong()
        {
            // Create two anonymous pipes, one for each direction of communication.
            // Then spawn another process to communicate with.
            using (var outbound = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                using (var inbound = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
                    using (var remote = RemoteExecutor.Invoke(new Func <string, string, int>(ChildFunc), outbound.GetClientHandleAsString(), inbound.GetClientHandleAsString()))
                    {
                        // Close our local copies of the handles now that we've passed them of to the other process
                        outbound.DisposeLocalCopyOfClientHandle();
                        inbound.DisposeLocalCopyOfClientHandle();

                        // Ping-pong back and forth by writing then reading bytes one at a time.
                        for (byte i = 0; i < 10; i++)
                        {
                            outbound.WriteByte(i);
                            int received = inbound.ReadByte();
                            Assert.Equal(i, received);
                        }
                    }

            int ChildFunc(string inHandle, string outHandle)
            {
                // Create the clients associated with the supplied handles
                using (var inbound = new AnonymousPipeClientStream(PipeDirection.In, inHandle))
                    using (var outbound = new AnonymousPipeClientStream(PipeDirection.Out, outHandle))
                    {
                        // Repeatedly read then write a byte from and to the server
                        for (int i = 0; i < 10; i++)
                        {
                            int b = inbound.ReadByte();
                            outbound.WriteByte((byte)b);
                        }
                    }
                return(RemoteExecutor.SuccessExitCode);
            }
        }
Beispiel #19
0
        public static void GetGCMemoryInfo()
        {
            RemoteExecutor.Invoke(() =>
            {
                // Allows to update the value returned by GC.GetGCMemoryInfo
                GC.Collect();

                GCMemoryInfo memoryInfo1 = GC.GetGCMemoryInfo();

                Assert.InRange(memoryInfo1.HighMemoryLoadThresholdBytes, 1, long.MaxValue);
                Assert.InRange(memoryInfo1.MemoryLoadBytes, 1, long.MaxValue);
                Assert.InRange(memoryInfo1.TotalAvailableMemoryBytes, 1, long.MaxValue);
                Assert.InRange(memoryInfo1.HeapSizeBytes, 1, long.MaxValue);
                Assert.InRange(memoryInfo1.FragmentedBytes, 0, long.MaxValue);

                GCHandle[] gch = new GCHandle[64 * 1024];
                for (int i = 0; i < gch.Length * 2; ++i)
                {
                    byte[] arr = new byte[64];
                    if (i % 2 == 0)
                    {
                        gch[i / 2] = GCHandle.Alloc(arr, GCHandleType.Pinned);
                    }
                }

                // Allows to update the value returned by GC.GetGCMemoryInfo
                GC.Collect();

                GCMemoryInfo memoryInfo2 = GC.GetGCMemoryInfo();

                Assert.Equal(memoryInfo2.HighMemoryLoadThresholdBytes, memoryInfo1.HighMemoryLoadThresholdBytes);
                Assert.InRange(memoryInfo2.MemoryLoadBytes, memoryInfo1.MemoryLoadBytes, long.MaxValue);
                Assert.Equal(memoryInfo2.TotalAvailableMemoryBytes, memoryInfo1.TotalAvailableMemoryBytes);
                Assert.InRange(memoryInfo2.HeapSizeBytes, memoryInfo1.HeapSizeBytes + 1, long.MaxValue);
                Assert.InRange(memoryInfo2.FragmentedBytes, memoryInfo1.FragmentedBytes + 1, long.MaxValue);
            }).Dispose();
        }
Beispiel #20
0
        /// <summary>
        /// Runs the given test <paramref name="action"/> within an environment
        /// where the given <paramref name="intrinsics"/> features.
        /// </summary>
        /// <param name="action">The test action to run.</param>
        /// <param name="arg0">The value to pass as a parameter #0 to the test action.</param>
        /// <param name="arg1">The value to pass as a parameter #1 to the test action.</param>
        /// <param name="intrinsics">The intrinsics features.</param>
        public static void RunWithHwIntrinsicsFeature <T>(
            Action <string, string> action,
            T arg0,
            T arg1,
            HwIntrinsics intrinsics)
            where T : IConvertible
        {
            if (!RemoteExecutor.IsSupported)
            {
                return;
            }

            foreach (KeyValuePair <HwIntrinsics, string> intrinsic in intrinsics.ToFeatureKeyValueCollection())
            {
                var processStartInfo = new ProcessStartInfo();
                if (intrinsic.Key != HwIntrinsics.AllowAll)
                {
                    processStartInfo.Environment[$"COMPlus_{intrinsic.Value}"] = "0";

                    RemoteExecutor.Invoke(
                        action,
                        arg0.ToString(),
                        arg1.ToString(),
                        new RemoteInvokeOptions
                    {
                        StartInfo = processStartInfo
                    })
                    .Dispose();
                }
                else
                {
                    // Since we are running using the default architecture there is no
                    // point creating the overhead of running the action in a separate process.
                    action(arg0.ToString(), arg1.ToString());
                }
            }
        }
Beispiel #21
0
        public void AssemblyResolve()
        {
            CopyTestAssemblies();

            RemoteExecutor.Invoke(() => {
                // bool AssemblyResolveFlag = false;
                ResolveEventHandler handler = (sender, args) =>
                {
                    Assert.Same(AppDomain.CurrentDomain, sender);
                    Assert.NotNull(args);
                    Assert.NotNull(args.Name);
                    Assert.NotNull(args.RequestingAssembly);
                    // AssemblyResolveFlag = true;
                    return(Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTestApp.dll")));
                };

                AppDomain.CurrentDomain.AssemblyResolve += handler;

                Type t = Type.GetType("AssemblyResolveTestApp.Class1, AssemblyResolveTestApp", true);
                Assert.NotNull(t);
                // https://github.com/dotnet/runtime/issues/29817
                // Assert.True(AssemblyResolveFlag);
            }).Dispose();
        }
Beispiel #22
0
 public void FirstChanceException_Called()
 {
     RemoteExecutor.Invoke(() => {
         bool flag = false;
         EventHandler <FirstChanceExceptionEventArgs> handler = (sender, e) =>
         {
             Exception ex = e.Exception;
             if (ex is FirstChanceTestException)
             {
                 flag = !flag;
             }
         };
         AppDomain.CurrentDomain.FirstChanceException += handler;
         try
         {
             throw new FirstChanceTestException("testing");
         }
         catch
         {
         }
         AppDomain.CurrentDomain.FirstChanceException -= handler;
         Assert.True(flag, "FirstChanceHandler not called");
     }).Dispose();
 }
Beispiel #23
0
        public void MemberInfoGeneric_IsCollectibleTrue_WhenUsingAssemblyLoadContext(string memberName)
        {
            RemoteExecutor.Invoke((marshalledName) =>
            {
                AssemblyLoadContext alc = new TestAssemblyLoadContext();

                Type t1 = Type.GetType(
                    "TestCollectibleAssembly.MyGenericTestClass`1[System.Int32], TestCollectibleAssembly, Version=1.0.0.0",
                    collectibleAssemblyResolver(alc),
                    typeResolver(false),
                    true
                    );

                Assert.NotNull(t1);

                var member = t1.GetMember(marshalledName).FirstOrDefault();

                Assert.NotNull(member);

                Assert.True(member.IsCollectible);

                return(RemoteExecutor.SuccessExitCode);
            }, memberName).Dispose();
        }
        public void PingPong_Sync()
        {
            // Create names for two pipes
            string outName = PipeStreamConformanceTests.GetUniquePipeName();
            string inName  = PipeStreamConformanceTests.GetUniquePipeName();

            // Create the two named pipes, one for each direction, then create
            // another process with which to communicate
            using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out))
                using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
                    using (RemoteExecutor.Invoke(new Action <string, string>(PingPong_OtherProcess), outName, inName))
                    {
                        // Wait for both pipes to be connected
                        Task.WaitAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync());

                        // Repeatedly write then read a byte to and from the other process
                        for (byte i = 0; i < 10; i++)
                        {
                            outbound.WriteByte(i);
                            int received = inbound.ReadByte();
                            Assert.Equal(i, received);
                        }
                    }
        }
Beispiel #25
0
        public void Authentication_UseMemoryStreamVisibleBufferContent_Success()
        {
            RemoteExecutor.Invoke(async(useSocketsHttpHandlerString, useHttp2String) =>
            {
                string username           = "******";
                string password           = "******";
                Uri uri                   = Configuration.Http.RemoteHttp11Server.BasicAuthUriForCreds(userName: username, password: password);
                HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandlerString, useHttp2String);
                handler.Credentials       = new NetworkCredential(username, password);

                using (HttpClient client = CreateHttpClient(handler, useHttp2String))
                {
                    byte[] postData = Encoding.UTF8.GetBytes("This is data to post.");
                    var stream      = new MemoryStream(postData, 0, postData.Length, false, true);
                    var content     = new MultiInterfaceStreamContent(stream);

                    using (HttpResponseMessage response = await client.PostAsync(uri, content))
                    {
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                        string responseContent = await response.Content.ReadAsStringAsync();
                    }
                }
            }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
        }
        public void ProfileOptimization_CheckFileExists()
        {
            string profileFile = GetTestFileName();

            RemoteExecutor.Invoke((_profileFile) =>
            {
                // Perform the test work
                ProfileOptimization.SetProfileRoot(Path.GetDirectoryName(_profileFile));
                ProfileOptimization.StartProfile(Path.GetFileName(_profileFile));
            }, profileFile).Dispose();

            // profileFile should deterministically exist now -- if not, wait 5 seconds
            bool existed = File.Exists(profileFile);

            if (!existed)
            {
                Thread.Sleep(5000);
            }

            Assert.True(File.Exists(profileFile), $"'{profileFile}' does not exist");
            Assert.True(new FileInfo(profileFile).Length > 0, $"'{profileFile}' is empty");

            Assert.True(existed, $"'{profileFile}' did not immediately exist, but did exist 5 seconds later");
        }
Beispiel #27
0
        public void HttpProxy_Uri_Parsing(string _input, string _host, string _port, string _user, string _password)
        {
            RemoteExecutor.Invoke((input, host, port, user, password) =>
            {
                // Remote exec does not allow to pass null at this moment.
                if (user == "null")
                {
                    user = null;
                }
                if (password == "null")
                {
                    password = null;
                }

                Environment.SetEnvironmentVariable("all_proxy", input);
                IWebProxy p;
                Uri u;

                Assert.True(HttpEnvironmentProxy.TryCreate(out p));
                Assert.NotNull(p);

                u = p.GetProxy(fooHttp);
                Assert.Equal(host, u.Host);
                Assert.Equal(Convert.ToInt32(port), u.Port);

                if (user != null)
                {
                    NetworkCredential nc = p.Credentials.GetCredential(u, "Basic");
                    Assert.NotNull(nc);
                    Assert.Equal(user, nc.UserName);
                    Assert.Equal(password, nc.Password);
                }

                return(RemoteExecutor.SuccessExitCode);
            }, _input, _host, _port, _user ?? "null", _password ?? "null").Dispose();
        }
Beispiel #28
0
        public void FailFast_ExceptionStackTrace_InnerException()
        {
            // Test if inner exception details are also logged
            var psi = new ProcessStartInfo();

            psi.RedirectStandardError  = true;
            psi.RedirectStandardOutput = true;

            using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(
                       () => Environment.FailFast("message", new ArgumentException("first exception", new NullReferenceException("inner exception"))),
                       new RemoteInvokeOptions {
                StartInfo = psi
            }))
            {
                Process p = handle.Process;
                handle.Process = null;
                p.WaitForExit();
                string consoleOutput = p.StandardError.ReadToEnd();
                Assert.Contains("first exception", consoleOutput);
                Assert.Contains("inner exception", consoleOutput);
                Assert.Contains("ArgumentException", consoleOutput);
                Assert.Contains("NullReferenceException", consoleOutput);
            }
        }
Beispiel #29
0
        public static void ProcessExit_Called()
        {
            // We expect the launched process to crash; don't let it write the resulting AV message to the console.
            var psi = new ProcessStartInfo()
            {
                RedirectStandardError = true, RedirectStandardOutput = true
            };

            using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => { CauseAVInNative(); return(RemoteExecutor.SuccessExitCode); }, new RemoteInvokeOptions {
                CheckExitCode = false, StartInfo = psi
            }))
            {
                Process p = handle.Process;
                p.WaitForExit();
                if (PlatformDetection.IsFullFramework)
                {
                    Assert.Equal(RemoteExecutor.SuccessExitCode, p.ExitCode);
                }
                else
                {
                    Assert.NotEqual(RemoteExecutor.SuccessExitCode, p.ExitCode);
                }
            }
        }
Beispiel #30
0
    private void HandlerInvokedForSignal(int signalOuter)
    {
        // On Windows we could use GenerateConsoleCtrlEvent to send a ctrl-C to the process,
        // however that'll apply to all processes associated with the same group, which will
        // include processes like the code coverage tool when doing code coverage runs, causing
        // those other processes to exit.  As such, we test this only on Unix, where we can
        // send a SIGINT signal to this specific process only.

        // This test sends a SIGINT back to itself... if run in the xunit process, this would end
        // up canceling the rest of xunit's tests.  So we run the test itself in a separate process.
        RemoteExecutor.Invoke(signalStr =>
        {
            var tcs = new TaskCompletionSource <ConsoleSpecialKey>();

            ConsoleCancelEventHandler handler = (sender, e) =>
            {
                e.Cancel = true;
                tcs.SetResult(e.SpecialKey);
            };

            Console.CancelKeyPress += handler;
            try
            {
                int signalInner = int.Parse(signalStr);
                Assert.Equal(0, kill(Process.GetCurrentProcess().Id, signalInner));
                Assert.True(tcs.Task.Wait(WaitFailTestTimeoutSeconds * 1000));
                Assert.Equal(
                    signalInner == SIGINT ? ConsoleSpecialKey.ControlC : ConsoleSpecialKey.ControlBreak,
                    tcs.Task.Result);
            }
            finally
            {
                Console.CancelKeyPress -= handler;
            }
        }, signalOuter.ToString()).Dispose();
    }
        public void CurrentCulture_DefaultWithNoLang(string langEnvVar)
        {
            var psi = new ProcessStartInfo();

            psi.Environment.Clear();

            CopyEssentialTestEnvironment(psi.Environment);

            if (langEnvVar != null)
            {
                psi.Environment["LANG"] = langEnvVar;
            }

            RemoteExecutor.Invoke(() =>
            {
                Assert.NotNull(CultureInfo.CurrentCulture);
                Assert.NotNull(CultureInfo.CurrentUICulture);

                Assert.Equal("", CultureInfo.CurrentCulture.Name);
                Assert.Equal("", CultureInfo.CurrentUICulture.Name);
            }, new RemoteInvokeOptions {
                StartInfo = psi
            }).Dispose();
        }