public static void TryFormat() { RemoteExecutor.Invoke(() => { CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; foreach (var testdata in ToString_TestData()) { decimal localI = (decimal)testdata[0]; string localFormat = (string)testdata[1]; IFormatProvider localProvider = (IFormatProvider)testdata[2]; string localExpected = (string)testdata[3]; try { char[] actual; int charsWritten; // Just right actual = new char[localExpected.Length]; Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider)); Assert.Equal(localExpected.Length, charsWritten); Assert.Equal(localExpected, new string(actual)); // Longer than needed actual = new char[localExpected.Length + 1]; Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider)); Assert.Equal(localExpected.Length, charsWritten); Assert.Equal(localExpected, new string(actual, 0, charsWritten)); // Too short if (localExpected.Length > 0) { actual = new char[localExpected.Length - 1]; Assert.False(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider)); Assert.Equal(0, charsWritten); } if (localFormat != null) { // Upper localFormat actual = new char[localExpected.Length]; Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat.ToUpperInvariant(), localProvider)); Assert.Equal(localExpected.Length, charsWritten); Assert.Equal(localExpected.ToUpperInvariant(), new string(actual)); // Lower format actual = new char[localExpected.Length]; Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat.ToLowerInvariant(), localProvider)); Assert.Equal(localExpected.Length, charsWritten); Assert.Equal(localExpected.ToLowerInvariant(), new string(actual)); } } catch (Exception exc) { throw new Exception($"Failed on `{localI}`, `{localFormat}`, `{localProvider}`, `{localExpected}`. {exc}"); } } return(RemoteExecutor.SuccessExitCode); }).Dispose(); }
public async Task Kill_ExitedNonChildProcess_DoesNotThrow(bool killTree) { // In this test, we kill a process in a way the Process instance // is not aware the process has terminated when we invoke Process.Kill. using (Process nonChildProcess = CreateNonChildProcess()) { // Kill the process. int rv = kill(nonChildProcess.Id, SIGKILL); Assert.Equal(0, rv); // Wait until the process is reaped. while (rv == 0) { rv = kill(nonChildProcess.Id, 0); if (rv == 0) { // process still exists, wait some time. await Task.Delay(100); } } // Call Process.Kill. nonChildProcess.Kill(killTree); } Process CreateNonChildProcess() { // Create a process that isn't a direct child. int nonChildPid = -1; RemoteInvokeHandle createNonChildProcess = RemoteExecutor.Invoke(arg => { RemoteInvokeHandle nonChildProcess = RemoteExecutor.Invoke( // Process that lives as long as the test process. testProcessPid => Process.GetProcessById(int.Parse(testProcessPid)).WaitForExit(), arg, // Don't pass our standard out to the sleepProcess or the ReadToEnd below won't return. new RemoteInvokeOptions { StartInfo = new ProcessStartInfo() { RedirectStandardOutput = true } }); using (nonChildProcess) { Console.WriteLine(nonChildProcess.Process.Id); // Don't wait for the process to exit. nonChildProcess.Process = null; } }, Process.GetCurrentProcess().Id.ToString(), new RemoteInvokeOptions { StartInfo = new ProcessStartInfo() { RedirectStandardOutput = true } }); using (createNonChildProcess) { nonChildPid = int.Parse(createNonChildProcess.Process.StandardOutput.ReadToEnd()); } return(Process.GetProcessById(nonChildPid)); } }
public void PerformanceCounter_PerformanceData() { // We run test in isolated process to avoid interferences on internal performance counter shared state with other tests. // These interferences could lead to fail also after retries RemoteExecutor.Invoke((string providerId, string typingCounterSetId) => { // Create the 'Typing' counter set. using (CounterSet typingCounterSet = new CounterSet(Guid.Parse(providerId), Guid.Parse(typingCounterSetId), CounterSetInstanceType.Single)) { // Add the counters to the counter set definition. typingCounterSet.AddCounter(1, CounterType.RawData32, "Total Words Typed"); typingCounterSet.AddCounter(2, CounterType.Delta32, "Words Typed In Interval"); typingCounterSet.AddCounter(3, CounterType.RawData32, "Letter A Pressed"); typingCounterSet.AddCounter(4, CounterType.RawData32, "Words Containing A"); typingCounterSet.AddCounter(5, CounterType.SampleFraction, "Percent of Words Containing A"); typingCounterSet.AddCounter(6, CounterType.SampleBase, "Percent Base"); typingCounterSet.AddCounter(7, CounterType.SampleBase); // Create an instance of the counter set (contains the counter data). using (CounterSetInstance typingCsInstance = typingCounterSet.CreateCounterSetInstance("Typing Instance")) { typingCsInstance.Counters[1].Value = 0; typingCsInstance.Counters[2].Value = 0; typingCsInstance.Counters[3].Value = 0; typingCsInstance.Counters[4].Value = 0; typingCsInstance.Counters[5].Value = 0; typingCsInstance.Counters[6].Value = 0; // Instance counters readers using (PerformanceCounter totalWordsTyped = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Total Words Typed")), wordsTypedInInterval = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Words Typed In Interval")), aKeyPressed = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Letter A Pressed")), wordsContainingA = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Words Containing A")), percentofWordsContaingA = Helpers.RetryOnAllPlatforms(() => new PerformanceCounter("Typing", "Percent of Words Containing A"))) { typingCsInstance.Counters[1].Increment(); Assert.Equal(1, typingCsInstance.Counters[1].Value); Assert.Equal(1, typingCsInstance.Counters[1].RawValue); Assert.Equal(1, typingCsInstance.Counters["Total Words Typed"].RawValue); Assert.Equal(1, totalWordsTyped.RawValue); typingCsInstance.Counters[1].Increment(); Assert.Equal(2, typingCsInstance.Counters[1].Value); Assert.Equal(2, typingCsInstance.Counters[1].RawValue); Assert.Equal(2, typingCsInstance.Counters["Total Words Typed"].RawValue); Assert.Equal(2, totalWordsTyped.RawValue); typingCsInstance.Counters[2].IncrementBy(3); Assert.Equal(3, typingCsInstance.Counters[2].Value); Assert.Equal(3, typingCsInstance.Counters[2].RawValue); Assert.Equal(3, typingCsInstance.Counters["Words Typed In Interval"].RawValue); Assert.Equal(3, wordsTypedInInterval.RawValue); typingCsInstance.Counters[3].RawValue = 4; Assert.Equal(4, typingCsInstance.Counters[3].Value); Assert.Equal(4, typingCsInstance.Counters[3].RawValue); Assert.Equal(4, typingCsInstance.Counters["Letter A Pressed"].RawValue); Assert.Equal(4, aKeyPressed.RawValue); typingCsInstance.Counters[4].Value = 5; Assert.Equal(5, typingCsInstance.Counters[4].Value); Assert.Equal(5, typingCsInstance.Counters[4].RawValue); Assert.Equal(5, typingCsInstance.Counters["Words Containing A"].RawValue); Assert.Equal(5, wordsContainingA.RawValue); typingCsInstance.Counters[4].Decrement(); Assert.Equal(4, typingCsInstance.Counters[4].Value); Assert.Equal(4, typingCsInstance.Counters[4].RawValue); Assert.Equal(4, typingCsInstance.Counters["Words Containing A"].RawValue); Assert.Equal(4, wordsContainingA.RawValue); } } } }, _fixture._providerId.ToString(), _fixture._typingCounterSetId.ToString()).Dispose(); }
public void SetShadowCopyPath() { RemoteExecutor.Invoke(() => { AppDomain.CurrentDomain.SetShadowCopyPath("test"); }).Dispose(); }
public void CountTest() { RemoteExecutor.Invoke(() => { const int TimersPerThread = 64; int processorCount = Environment.ProcessorCount; int totalTimerCount = processorCount * TimersPerThread; var timers = new List <Timer>(totalTimerCount); TimerCallback timerCallback = _ => { }; var startCreateTimerThreads = new ManualResetEvent(false); Action createTimerThreadStart = () => { startCreateTimerThreads.WaitOne(); for (int i = 0; i < TimersPerThread; ++i) { lock (timers) { timers.Add( new Timer( timerCallback, null, ThreadTestHelpers.UnexpectedTimeoutMilliseconds, ThreadTestHelpers.UnexpectedTimeoutMilliseconds)); Assert.True(Timer.ActiveCount >= timers.Count); } } }; var waitsForThread = new Action[processorCount]; for (int i = 0; i < processorCount; ++i) { Thread t = ThreadTestHelpers.CreateGuardedThread(out waitsForThread[i], createTimerThreadStart); t.IsBackground = true; t.Start(); } startCreateTimerThreads.Set(); foreach (Action waitForThread in waitsForThread) { waitForThread(); } // To leave some room for unknown timers to be scheduled and removed, remove a large number of timers at a time and // verify that the timer count has decreased while (timers.Count > 0) { long timerCountBeforeRemove = Timer.ActiveCount; int endIndex = timers.Count - processorCount * 8; for (int i = timers.Count - 1; i >= Math.Max(0, endIndex); --i) { timers[i].Dispose(); timers.RemoveAt(i); } if (endIndex >= 0) { Assert.True(Timer.ActiveCount < timerCountBeforeRemove); } } }).Dispose(); }
public void AppendPrivatePath() { RemoteExecutor.Invoke(() => { AppDomain.CurrentDomain.AppendPrivatePath("test"); }).Dispose(); }
public void ClearShadowCopyPath() { RemoteExecutor.Invoke(() => { AppDomain.CurrentDomain.ClearShadowCopyPath(); }).Dispose(); }
public void TestAllowInvariantCultureOnly(bool enableInvariant, bool predefinedCulturesOnly, bool declarePredefinedCulturesOnly) { var psi = new ProcessStartInfo(); psi.Environment.Clear(); if (enableInvariant) { psi.Environment.Add("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT", "true"); } if (declarePredefinedCulturesOnly) { psi.Environment.Add("DOTNET_SYSTEM_GLOBALIZATION_PREDEFINED_CULTURES_ONLY", predefinedCulturesOnly ? "true" : "false"); } bool restricted = enableInvariant && (declarePredefinedCulturesOnly ? predefinedCulturesOnly : true); RemoteExecutor.Invoke((invariantEnabled, isRestricted) => { bool restrictedMode = bool.Parse(isRestricted); // First ensure we can create the current cultures regardless of the mode we are in Assert.NotNull(CultureInfo.CurrentCulture); Assert.NotNull(CultureInfo.CurrentUICulture); // Invariant culture should be valid all the time Assert.Equal("", new CultureInfo("").Name); Assert.Equal("", CultureInfo.InvariantCulture.Name); if (restrictedMode) { Assert.Equal("", CultureInfo.CurrentCulture.Name); Assert.Equal("", CultureInfo.CurrentUICulture.Name); // Throwing exception is testing accessing the resources in this restricted mode. // We should retrieve the resources from the neutral resources in the main assemblies. AssertExtensions.Throws <CultureNotFoundException>(() => new CultureInfo("en-US")); AssertExtensions.Throws <CultureNotFoundException>(() => new CultureInfo("en")); AssertExtensions.Throws <CultureNotFoundException>(() => new CultureInfo("ja-JP")); AssertExtensions.Throws <CultureNotFoundException>(() => new CultureInfo("es")); // Test throwing exceptions from non-core assemblies. Exception exception = Record.Exception(() => new ConcurrentBag <string>(null)); Assert.NotNull(exception); Assert.IsType <ArgumentNullException>(exception); Assert.Equal("collection", (exception as ArgumentNullException).ParamName); Assert.Equal("Value cannot be null. (Parameter 'collection')", exception.Message); } else { Assert.Equal("en-US", new CultureInfo("en-US").Name); Assert.Equal("ja-JP", new CultureInfo("ja-JP").Name); Assert.Equal("en", new CultureInfo("en").Name); Assert.Equal("es", new CultureInfo("es").Name); } // Ensure the Invariant Mode functionality still work if (bool.Parse(invariantEnabled)) { Assert.True(CultureInfo.CurrentCulture.Calendar is GregorianCalendar); Assert.True("abcd".Equals("ABCD", StringComparison.CurrentCultureIgnoreCase)); Assert.Equal("Invariant Language (Invariant Country)", CultureInfo.CurrentCulture.NativeName); } }, enableInvariant.ToString(), restricted.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose(); }
public void Create_Free_AllocationsAreTracked(int count) { RemoteExecutor.Invoke(RunTest, count.ToString()).Dispose();
public static void GetPermissionSet() { RemoteExecutor.Invoke(() => { Assert.Equal(new PermissionSet(PermissionState.Unrestricted), AppDomain.CurrentDomain.PermissionSet); }).Dispose(); }
public void CreateSymbolicLink_PathToTarget_RelativeToLinkPath() { RemoteExecutor.Invoke(() => CreateSymbolicLink_PathToTarget_RelativeToLinkPath_Internal(false)).Dispose(); RemoteExecutor.Invoke(() => CreateSymbolicLink_PathToTarget_RelativeToLinkPath_Internal(true)).Dispose(); }
public void Manual_SelectClientCertificateForRemoteServer_ServerOnlyReceivesValidClientCert( int certIndex, HttpStatusCode expectedStatusCode) { if (!CanTestClientCertificates) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler { _output.WriteLine($"Skipping {nameof(Manual_SelectClientCertificateForRemoteServer_ServerOnlyReceivesValidClientCert)}()"); return; } // UAP HTTP stack caches connections per-process. This causes interference when these tests run in // the same process as the other tests. Each test needs to be isolated to its own process. // See dicussion: https://github.com/dotnet/corefx/issues/21945 RemoteExecutor.Invoke((certIndexString, expectedStatusCodeString, useSocketsHttpHandlerString, useHttp2String) => { X509Certificate2 clientCert = null; // Get client certificate. RemoteInvoke doesn't allow easy marshaling of complex types. // So we have to select the certificate at this point in the test execution. if (certIndexString == "1") { // This is a valid client cert since it has an EKU with a ClientAuthentication OID. clientCert = Configuration.Certificates.GetClientCertificate(); } else if (certIndexString == "2") { // This is a valid client cert since it has no EKU thus all usages are permitted. clientCert = Configuration.Certificates.GetNoEKUCertificate(); } else if (certIndexString == "3") { // This is an invalid client cert since it has an EKU but is missing ClientAuthentication OID. clientCert = Configuration.Certificates.GetServerCertificate(); } Assert.NotNull(clientCert); var statusCode = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), expectedStatusCodeString); HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandlerString, useHttp2String); handler.ClientCertificates.Add(clientCert); using (HttpClient client = CreateHttpClient(handler, useHttp2String)) { var request = new HttpRequestMessage(); request.RequestUri = new Uri(Configuration.Http.EchoClientCertificateRemoteServer); // Issue #35239. Force HTTP/1.1. request.Version = new Version(1, 1); HttpResponseMessage response = client.SendAsync(request).GetAwaiter().GetResult(); // need a 4-arg overload of RemoteInvoke that returns a Task Assert.Equal(statusCode, response.StatusCode); if (statusCode == HttpStatusCode.OK) { string body = response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); // need a 4-arg overload of RemoteInvoke that returns a Task byte[] bytes = Convert.FromBase64String(body); var receivedCert = new X509Certificate2(bytes); Assert.Equal(clientCert, receivedCert); } return(RemoteExecutor.SuccessExitCode); } }, certIndex.ToString(), expectedStatusCode.ToString(), UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); }
public void RetainsUnmangedBuffers1(bool throwException) { RemoteExecutor.Invoke(RunTest, this.GetType().FullName, throwException.ToString()).Dispose();
public static async Task <int> RemoteInvoke(ITestOutputHelper output, TestConfiguration config, TimeSpan timeout, string dumpPath, Func <string, Task <int> > method) { RemoteInvokeOptions options = new() { StartInfo = new ProcessStartInfo() { RedirectStandardOutput = true, RedirectStandardError = true } }; // The remoteInvokeHandle is NOT disposed (i.e. with a using) here because the RemoteExecutor dispose code uses an older (1.x) version // of clrmd that conflicts with the 2.0 version diagnostics is using and throws the exception: // // "Method not found: 'Microsoft.Diagnostics.Runtime.DataTarget Microsoft.Diagnostics.Runtime.DataTarget.AttachToProcess(Int32, UInt32)'." // // When RemoteExecutor is fixed the "using" can be added and the GC.SuppressFinalize be removed. RemoteInvokeHandle remoteInvokeHandle = RemoteExecutor.Invoke(method, config.Serialize(), options); GC.SuppressFinalize(remoteInvokeHandle); try { Task stdOutputTask = WriteStreamToOutput(remoteInvokeHandle.Process.StandardOutput, output); Task stdErrorTask = WriteStreamToOutput(remoteInvokeHandle.Process.StandardError, output); Task outputTasks = Task.WhenAll(stdErrorTask, stdOutputTask); Task processExit = Task.Factory.StartNew(() => remoteInvokeHandle.Process.WaitForExit(), TaskCreationOptions.LongRunning); Task timeoutTask = Task.Delay(timeout); Task completedTask = await Task.WhenAny(outputTasks, processExit, timeoutTask); if (completedTask == timeoutTask) { if (!string.IsNullOrEmpty(dumpPath)) { output.WriteLine($"RemoteExecutorHelper.RemoteInvoke timed out: writing dump to {dumpPath}"); DiagnosticsClient client = new(remoteInvokeHandle.Process.Id); try { await client.WriteDumpAsync(DumpType.WithHeap, dumpPath, WriteDumpFlags.None, CancellationToken.None); } catch (Exception ex) when(ex is ArgumentException || ex is UnsupportedCommandException || ex is ServerErrorException) { output.WriteLine($"RemoteExecutorHelper.RemoteInvoke: writing dump FAILED {ex}"); } } throw new XunitException("RemoteExecutorHelper.RemoteInvoke timed out"); } else { return(remoteInvokeHandle.ExitCode); } } finally { if (remoteInvokeHandle.Process != null) { try { output.WriteLine($"RemoteExecutorHelper.RemoteInvoke: killing process {remoteInvokeHandle.Process.Id}"); remoteInvokeHandle.Process.Kill(entireProcessTree: true); } catch { } remoteInvokeHandle.Process.Dispose(); remoteInvokeHandle.Process = null; } } }
public static void DroppedIncompleteStateMachine_RaisesIncompleteAsyncMethodEvent() { RemoteExecutor.Invoke(() => { using (var listener = new TestEventListener("System.Threading.Tasks.TplEventSource", EventLevel.Verbose)) { var events = new ConcurrentQueue <EventWrittenEventArgs>(); listener.RunWithCallback(events.Enqueue, () => { NeverCompletes(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.WaitForPendingFinalizers(); }); // To help diagnose https://github.com/dotnet/runtime/issues/2198 // Assert.DoesNotContain(events, ev => ev.EventId == 0); // errors from the EventSource itself var sb = new StringBuilder(); foreach (EventWrittenEventArgs ev in events) { if (ev.EventId == 0) { sb.AppendLine("Events contained unexpected event:") .AppendLine($"ActivityId: {ev.ActivityId}") .AppendLine($"Channel: {ev.Channel}") .AppendLine($"EventId: {ev.EventId}") .AppendLine($"EventName: {ev.EventName}") .AppendLine($"EventSource: {ev.EventSource}") .AppendLine($"Keywords: {ev.Keywords}") .AppendLine($"Level: {ev.Level}") .AppendLine($"Message: {ev.Message}") .AppendLine($"Opcode: {ev.Opcode}") .AppendLine($"OSThreadId: {ev.OSThreadId}") .AppendLine($"Payload: {(ev.Payload != null ? string.Join(", ", ev.Payload) : "(null)")}") .AppendLine($"PayloadNames: {(ev.PayloadNames != null ? string.Join(", ", ev.PayloadNames) : "(null)")}") .AppendLine($"RelatedActivityId: {ev.RelatedActivityId}") .AppendLine($"Tags: {ev.Tags}") .AppendLine($"Task: {ev.Task}") .AppendLine($"TimeStamp: {ev.TimeStamp}") .AppendLine($"Version: {ev.Version}") .AppendLine(); } } if (sb.Length > 0) { throw new XunitException(sb.ToString()); } EventWrittenEventArgs iam = events.SingleOrDefault(e => e.EventName == "IncompleteAsyncMethod"); Assert.NotNull(iam); Assert.NotNull(iam.Payload); string description = iam.Payload[0] as string; Assert.NotNull(description); Assert.Contains(nameof(NeverCompletesAsync), description); Assert.Contains("__state", description); Assert.Contains("local1", description); Assert.Contains("local2", description); Assert.Contains("42", description); Assert.Contains("stored data", description); } }).Dispose(); }
public void XsdSchemaDeserializationIgnoresLocale() { RemoteExecutor.Invoke(() => { var serializer = new BinaryFormatter(); /* * * Test data generator: * * var table = new DataTable(); * table.Columns.Add(new DataColumn("RowID", typeof(int)) * { * AutoIncrement = true, * AutoIncrementSeed = -1, // These lines produce attributes within the schema portion of the underlying XML representation of the DataTable with the value "-1". * AutoIncrementStep = -2, * }); * table.Columns.Add("Value", typeof(string)); * table.Rows.Add(1, "Test"); * table.Rows.Add(2, "Data"); * * var buffer = new MemoryStream(); * serializer.Serialize(buffer, table); * * This test data (binary serializer output) embeds the following XML schema: * * <?xml version="1.0" encoding="utf-16"?> * <xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> * <xs:element name="Table1"> * <xs:complexType> * <xs:sequence> * <xs:element name="RowID" msdata:AutoIncrement="true" msdata:AutoIncrementSeed="-1" msdata:AutoIncrementStep="-2" type="xs:int" msdata:targetNamespace="" minOccurs="0" /> * <xs:element name="Value" type="xs:string" msdata:targetNamespace="" minOccurs="0" /> * </xs:sequence> * </xs:complexType> * </xs:element> * <xs:element name="tmpDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Table1" msdata:UseCurrentLocale="true"> * <xs:complexType> * <xs:choice minOccurs="0" maxOccurs="unbounded" /> * </xs:complexType> * </xs:element> * </xs:schema> * * The bug being tested here is that the negative integer values in AutoInecrementSeed and AutoIncrementStep fail to parse because the deserialization code * incorrectly uses the current culture instead of the invariant culture when parsing strings like "-1" and "-2". * */ var buffer = new MemoryStream(new byte[] { 0, 1, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 0, 0, 0, 0, 12, 2, 0, 0, 0, 78, 83, 121, 115, 116, 101, 109, 46, 68, 97, 116, 97, 44, 32, 86, 101, 114, 115, 105, 111, 110, 61, 52, 46, 48, 46, 48, 46, 48, 44, 32, 67, 117, 108, 116, 117, 114, 101, 61, 110, 101, 117, 116, 114, 97, 108, 44, 32, 80, 117, 98, 108, 105, 99, 75, 101, 121, 84, 111, 107, 101, 110, 61, 98, 55, 55, 97, 53, 99, 53, 54, 49, 57, 51, 52, 101, 48, 56, 57, 5, 1, 0, 0, 0, 21, 83, 121, 115, 116, 101, 109, 46, 68, 97, 116, 97, 46, 68, 97, 116, 97, 84, 97, 98, 108, 101, 3, 0, 0, 0, 25, 68, 97, 116, 97, 84, 97, 98, 108, 101, 46, 82, 101, 109, 111, 116, 105, 110, 103, 86, 101, 114, 115, 105, 111, 110, 9, 88, 109, 108, 83, 99, 104, 101, 109, 97, 11, 88, 109, 108, 68, 105, 102, 102, 71, 114, 97, 109, 3, 1, 1, 14, 83, 121, 115, 116, 101, 109, 46, 86, 101, 114, 115, 105, 111, 110, 2, 0, 0, 0, 9, 3, 0, 0, 0, 6, 4, 0, 0, 0, 177, 6, 60, 63, 120, 109, 108, 32, 118, 101, 114, 115, 105, 111, 110, 61, 34, 49, 46, 48, 34, 32, 101, 110, 99, 111, 100, 105, 110, 103, 61, 34, 117, 116, 102, 45, 49, 54, 34, 63, 62, 13, 10, 60, 120, 115, 58, 115, 99, 104, 101, 109, 97, 32, 120, 109, 108, 110, 115, 61, 34, 34, 32, 120, 109, 108, 110, 115, 58, 120, 115, 61, 34, 104, 116, 116, 112, 58, 47, 47, 119, 119, 119, 46, 119, 51, 46, 111, 114, 103, 47, 50, 48, 48, 49, 47, 88, 77, 76, 83, 99, 104, 101, 109, 97, 34, 32, 120, 109, 108, 110, 115, 58, 109, 115, 100, 97, 116, 97, 61, 34, 117, 114, 110, 58, 115, 99, 104, 101, 109, 97, 115, 45, 109, 105, 99, 114, 111, 115, 111, 102, 116, 45, 99, 111, 109, 58, 120, 109, 108, 45, 109, 115, 100, 97, 116, 97, 34, 62, 13, 10, 32, 32, 60, 120, 115, 58, 101, 108, 101, 109, 101, 110, 116, 32, 110, 97, 109, 101, 61, 34, 84, 97, 98, 108, 101, 49, 34, 62, 13, 10, 32, 32, 32, 32, 60, 120, 115, 58, 99, 111, 109, 112, 108, 101, 120, 84, 121, 112, 101, 62, 13, 10, 32, 32, 32, 32, 32, 32, 60, 120, 115, 58, 115, 101, 113, 117, 101, 110, 99, 101, 62, 13, 10, 32, 32, 32, 32, 32, 32, 32, 32, 60, 120, 115, 58, 101, 108, 101, 109, 101, 110, 116, 32, 110, 97, 109, 101, 61, 34, 82, 111, 119, 73, 68, 34, 32, 109, 115, 100, 97, 116, 97, 58, 65, 117, 116, 111, 73, 110, 99, 114, 101, 109, 101, 110, 116, 61, 34, 116, 114, 117, 101, 34, 32, 109, 115, 100, 97, 116, 97, 58, 65, 117, 116, 111, 73, 110, 99, 114, 101, 109, 101, 110, 116, 83, 101, 101, 100, 61, 34, 45, 49, 34, 32, 109, 115, 100, 97, 116, 97, 58, 65, 117, 116, 111, 73, 110, 99, 114, 101, 109, 101, 110, 116, 83, 116, 101, 112, 61, 34, 45, 50, 34, 32, 116, 121, 112, 101, 61, 34, 120, 115, 58, 105, 110, 116, 34, 32, 109, 115, 100, 97, 116, 97, 58, 116, 97, 114, 103, 101, 116, 78, 97, 109, 101, 115, 112, 97, 99, 101, 61, 34, 34, 32, 109, 105, 110, 79, 99, 99, 117, 114, 115, 61, 34, 48, 34, 32, 47, 62, 13, 10, 32, 32, 32, 32, 32, 32, 32, 32, 60, 120, 115, 58, 101, 108, 101, 109, 101, 110, 116, 32, 110, 97, 109, 101, 61, 34, 86, 97, 108, 117, 101, 34, 32, 116, 121, 112, 101, 61, 34, 120, 115, 58, 115, 116, 114, 105, 110, 103, 34, 32, 109, 115, 100, 97, 116, 97, 58, 116, 97, 114, 103, 101, 116, 78, 97, 109, 101, 115, 112, 97, 99, 101, 61, 34, 34, 32, 109, 105, 110, 79, 99, 99, 117, 114, 115, 61, 34, 48, 34, 32, 47, 62, 13, 10, 32, 32, 32, 32, 32, 32, 60, 47, 120, 115, 58, 115, 101, 113, 117, 101, 110, 99, 101, 62, 13, 10, 32, 32, 32, 32, 60, 47, 120, 115, 58, 99, 111, 109, 112, 108, 101, 120, 84, 121, 112, 101, 62, 13, 10, 32, 32, 60, 47, 120, 115, 58, 101, 108, 101, 109, 101, 110, 116, 62, 13, 10, 32, 32, 60, 120, 115, 58, 101, 108, 101, 109, 101, 110, 116, 32, 110, 97, 109, 101, 61, 34, 116, 109, 112, 68, 97, 116, 97, 83, 101, 116, 34, 32, 109, 115, 100, 97, 116, 97, 58, 73, 115, 68, 97, 116, 97, 83, 101, 116, 61, 34, 116, 114, 117, 101, 34, 32, 109, 115, 100, 97, 116, 97, 58, 77, 97, 105, 110, 68, 97, 116, 97, 84, 97, 98, 108, 101, 61, 34, 84, 97, 98, 108, 101, 49, 34, 32, 109, 115, 100, 97, 116, 97, 58, 85, 115, 101, 67, 117, 114, 114, 101, 110, 116, 76, 111, 99, 97, 108, 101, 61, 34, 116, 114, 117, 101, 34, 62, 13, 10, 32, 32, 32, 32, 60, 120, 115, 58, 99, 111, 109, 112, 108, 101, 120, 84, 121, 112, 101, 62, 13, 10, 32, 32, 32, 32, 32, 32, 60, 120, 115, 58, 99, 104, 111, 105, 99, 101, 32, 109, 105, 110, 79, 99, 99, 117, 114, 115, 61, 34, 48, 34, 32, 109, 97, 120, 79, 99, 99, 117, 114, 115, 61, 34, 117, 110, 98, 111, 117, 110, 100, 101, 100, 34, 32, 47, 62, 13, 10, 32, 32, 32, 32, 60, 47, 120, 115, 58, 99, 111, 109, 112, 108, 101, 120, 84, 121, 112, 101, 62, 13, 10, 32, 32, 60, 47, 120, 115, 58, 101, 108, 101, 109, 101, 110, 116, 62, 13, 10, 60, 47, 120, 115, 58, 115, 99, 104, 101, 109, 97, 62, 6, 5, 0, 0, 0, 221, 3, 60, 100, 105, 102, 102, 103, 114, 58, 100, 105, 102, 102, 103, 114, 97, 109, 32, 120, 109, 108, 110, 115, 58, 109, 115, 100, 97, 116, 97, 61, 34, 117, 114, 110, 58, 115, 99, 104, 101, 109, 97, 115, 45, 109, 105, 99, 114, 111, 115, 111, 102, 116, 45, 99, 111, 109, 58, 120, 109, 108, 45, 109, 115, 100, 97, 116, 97, 34, 32, 120, 109, 108, 110, 115, 58, 100, 105, 102, 102, 103, 114, 61, 34, 117, 114, 110, 58, 115, 99, 104, 101, 109, 97, 115, 45, 109, 105, 99, 114, 111, 115, 111, 102, 116, 45, 99, 111, 109, 58, 120, 109, 108, 45, 100, 105, 102, 102, 103, 114, 97, 109, 45, 118, 49, 34, 62, 13, 10, 32, 32, 60, 116, 109, 112, 68, 97, 116, 97, 83, 101, 116, 62, 13, 10, 32, 32, 32, 32, 60, 84, 97, 98, 108, 101, 49, 32, 100, 105, 102, 102, 103, 114, 58, 105, 100, 61, 34, 84, 97, 98, 108, 101, 49, 49, 34, 32, 109, 115, 100, 97, 116, 97, 58, 114, 111, 119, 79, 114, 100, 101, 114, 61, 34, 48, 34, 32, 100, 105, 102, 102, 103, 114, 58, 104, 97, 115, 67, 104, 97, 110, 103, 101, 115, 61, 34, 105, 110, 115, 101, 114, 116, 101, 100, 34, 62, 13, 10, 32, 32, 32, 32, 32, 32, 60, 82, 111, 119, 73, 68, 62, 49, 60, 47, 82, 111, 119, 73, 68, 62, 13, 10, 32, 32, 32, 32, 32, 32, 60, 86, 97, 108, 117, 101, 62, 84, 101, 115, 116, 60, 47, 86, 97, 108, 117, 101, 62, 13, 10, 32, 32, 32, 32, 60, 47, 84, 97, 98, 108, 101, 49, 62, 13, 10, 32, 32, 32, 32, 60, 84, 97, 98, 108, 101, 49, 32, 100, 105, 102, 102, 103, 114, 58, 105, 100, 61, 34, 84, 97, 98, 108, 101, 49, 50, 34, 32, 109, 115, 100, 97, 116, 97, 58, 114, 111, 119, 79, 114, 100, 101, 114, 61, 34, 49, 34, 32, 100, 105, 102, 102, 103, 114, 58, 104, 97, 115, 67, 104, 97, 110, 103, 101, 115, 61, 34, 105, 110, 115, 101, 114, 116, 101, 100, 34, 62, 13, 10, 32, 32, 32, 32, 32, 32, 60, 82, 111, 119, 73, 68, 62, 50, 60, 47, 82, 111, 119, 73, 68, 62, 13, 10, 32, 32, 32, 32, 32, 32, 60, 86, 97, 108, 117, 101, 62, 68, 97, 116, 97, 60, 47, 86, 97, 108, 117, 101, 62, 13, 10, 32, 32, 32, 32, 60, 47, 84, 97, 98, 108, 101, 49, 62, 13, 10, 32, 32, 60, 47, 116, 109, 112, 68, 97, 116, 97, 83, 101, 116, 62, 13, 10, 60, 47, 100, 105, 102, 102, 103, 114, 58, 100, 105, 102, 102, 103, 114, 97, 109, 62, 4, 3, 0, 0, 0, 14, 83, 121, 115, 116, 101, 109, 46, 86, 101, 114, 115, 105, 111, 110, 4, 0, 0, 0, 6, 95, 77, 97, 106, 111, 114, 6, 95, 77, 105, 110, 111, 114, 6, 95, 66, 117, 105, 108, 100, 9, 95, 82, 101, 118, 105, 115, 105, 111, 110, 0, 0, 0, 0, 8, 8, 8, 8, 2, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 11 }); DataTable table; var savedCulture = CultureInfo.CurrentCulture; try { // Before deserializing, update the culture to use a weird negative number format. This test is ensuring that this is ignored. // The bug this test is testing would cause "-1" to no longer be treated as a valid representation of the value -1, instead // only accepting the string "()1". CultureInfo.CurrentCulture = new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }; table = (DataTable)serializer.Deserialize(buffer); // BUG: System.Exception: "-1 is not a valid value for Int64." } } finally { CultureInfo.CurrentCulture = savedCulture; } DataColumn rowIDColumn = table.Columns["RowID"]; Assert.Equal(-1, rowIDColumn.AutoIncrementSeed); Assert.Equal(-2, rowIDColumn.AutoIncrementStep); }).Dispose(); }
public void HttpProxy_EnvironmentProxy_Loaded() { RemoteExecutor.Invoke(() => { IWebProxy p; Uri u; // It should not return object if there are no variables set. Assert.False(HttpEnvironmentProxy.TryCreate(out p)); Environment.SetEnvironmentVariable("all_proxy", "http://1.1.1.1:3000"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); Assert.Null(p.Credentials); u = p.GetProxy(fooHttp); Assert.True(u != null && u.Host == "1.1.1.1"); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.1"); u = p.GetProxy(fooWs); Assert.True(u != null && u.Host == "1.1.1.1"); u = p.GetProxy(fooWss); Assert.True(u != null && u.Host == "1.1.1.1"); Environment.SetEnvironmentVariable("http_proxy", "http://1.1.1.2:3001"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); // Protocol specific variables should take precedence over all_ // and https should still use all_proxy. u = p.GetProxy(fooHttp); Assert.True(u != null && u.Host == "1.1.1.2" && u.Port == 3001); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.1" && u.Port == 3000); u = p.GetProxy(fooWs); Assert.True(u != null && u.Host == "1.1.1.2" && u.Port == 3001); u = p.GetProxy(fooWss); Assert.True(u != null && u.Host == "1.1.1.1" && u.Port == 3000); // Set https to invalid strings and use only IP & port for http. Environment.SetEnvironmentVariable("http_proxy", "1.1.1.3:3003"); Environment.SetEnvironmentVariable("https_proxy", "ab!cd"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); u = p.GetProxy(fooHttp); Assert.True(u != null && u.Host == "1.1.1.3" && u.Port == 3003); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.1" && u.Port == 3000); u = p.GetProxy(fooWs); Assert.True(u != null && u.Host == "1.1.1.3" && u.Port == 3003); u = p.GetProxy(fooWss); Assert.True(u != null && u.Host == "1.1.1.1" && u.Port == 3000); // Try valid URI with unsupported protocol. It will be ignored // to mimic curl behavior. Environment.SetEnvironmentVariable("https_proxy", "socks5://1.1.1.4:3004"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.1" && u.Port == 3000); u = p.GetProxy(fooWss); Assert.True(u != null && u.Host == "1.1.1.1" && u.Port == 3000); // Set https to valid URI but different from http. Environment.SetEnvironmentVariable("https_proxy", "http://1.1.1.5:3005"); Assert.True(HttpEnvironmentProxy.TryCreate(out p)); Assert.NotNull(p); u = p.GetProxy(fooHttp); Assert.True(u != null && u.Host == "1.1.1.3" && u.Port == 3003); u = p.GetProxy(fooHttps); Assert.True(u != null && u.Host == "1.1.1.5" && u.Port == 3005); u = p.GetProxy(fooWs); Assert.True(u != null && u.Host == "1.1.1.3" && u.Port == 3003); u = p.GetProxy(fooWss); Assert.True(u != null && u.Host == "1.1.1.5" && u.Port == 3005); }).Dispose(); }
public void Finalize_ResultsInSingleRelease() { RemoteExecutor.Invoke(RunTest).Dispose();
public void ClearPrivatePath() { RemoteExecutor.Invoke(() => { AppDomain.CurrentDomain.ClearPrivatePath(); }).Dispose(); }
public void ProcessId_MatchesExpectedValue() { using RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => Console.WriteLine(Environment.ProcessId), new RemoteInvokeOptions { StartInfo = new ProcessStartInfo { RedirectStandardOutput = true } }); Assert.Equal(handle.Process.Id, int.Parse(handle.Process.StandardOutput.ReadToEnd())); }
public void SetShadowCopyFiles() { RemoteExecutor.Invoke(() => { AppDomain.CurrentDomain.SetShadowCopyFiles(); }).Dispose(); }
public void PreferContiguousImageBuffers_CreateImage_BufferIsContiguous() { // Run remotely to avoid large allocation in the test process: RemoteExecutor.Invoke(RunTest).Dispose();
public static void SetMinMaxThreadsTest() { RemoteExecutor.Invoke(() => { int minw, minc, maxw, maxc; ThreadPool.GetMinThreads(out minw, out minc); ThreadPool.GetMaxThreads(out maxw, out maxc); try { int mint = Environment.ProcessorCount * 2; int maxt = mint + 1; ThreadPool.SetMinThreads(mint, mint); ThreadPool.SetMaxThreads(maxt, maxt); Assert.False(ThreadPool.SetMinThreads(maxt + 1, mint)); Assert.False(ThreadPool.SetMinThreads(mint, maxt + 1)); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, mint)); Assert.False(ThreadPool.SetMinThreads(mint, MaxPossibleThreadCount)); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount + 1, mint)); Assert.False(ThreadPool.SetMinThreads(mint, MaxPossibleThreadCount + 1)); Assert.False(ThreadPool.SetMinThreads(-1, mint)); Assert.False(ThreadPool.SetMinThreads(mint, -1)); Assert.False(ThreadPool.SetMaxThreads(mint - 1, maxt)); Assert.False(ThreadPool.SetMaxThreads(maxt, mint - 1)); VerifyMinThreads(mint, mint); VerifyMaxThreads(maxt, maxt); Assert.True(ThreadPool.SetMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount)); VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.True(ThreadPool.SetMaxThreads(MaxPossibleThreadCount + 1, MaxPossibleThreadCount + 1)); VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.Equal(PlatformDetection.IsNetFramework, ThreadPool.SetMaxThreads(-1, -1)); VerifyMaxThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.True(ThreadPool.SetMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount)); VerifyMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount + 1, MaxPossibleThreadCount)); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount + 1)); Assert.False(ThreadPool.SetMinThreads(-1, MaxPossibleThreadCount)); Assert.False(ThreadPool.SetMinThreads(MaxPossibleThreadCount, -1)); VerifyMinThreads(MaxPossibleThreadCount, MaxPossibleThreadCount); Assert.True(ThreadPool.SetMinThreads(0, 0)); Assert.True(ThreadPool.SetMaxThreads(1, 1)); VerifyMaxThreads(1, 1); Assert.True(ThreadPool.SetMinThreads(1, 1)); VerifyMinThreads(1, 1); } finally { Assert.True(ThreadPool.SetMaxThreads(maxw, maxc)); VerifyMaxThreads(maxw, maxc); Assert.True(ThreadPool.SetMinThreads(minw, minc)); VerifyMinThreads(minw, minc); } }).Dispose(); }
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(); string scenario = null; try { scenario = nameof(memoryInfo2.HighMemoryLoadThresholdBytes); Assert.Equal(memoryInfo2.HighMemoryLoadThresholdBytes, memoryInfo1.HighMemoryLoadThresholdBytes); // Even though we have allocated, the overall load may decrease or increase depending what other processes are doing. // It cannot go above total available though. scenario = nameof(memoryInfo2.MemoryLoadBytes); Assert.InRange(memoryInfo2.MemoryLoadBytes, 1, memoryInfo1.TotalAvailableMemoryBytes); scenario = nameof(memoryInfo2.TotalAvailableMemoryBytes); Assert.Equal(memoryInfo2.TotalAvailableMemoryBytes, memoryInfo1.TotalAvailableMemoryBytes); scenario = nameof(memoryInfo2.HeapSizeBytes); Assert.InRange(memoryInfo2.HeapSizeBytes, memoryInfo1.HeapSizeBytes + 1, long.MaxValue); scenario = nameof(memoryInfo2.FragmentedBytes); Assert.InRange(memoryInfo2.FragmentedBytes, memoryInfo1.FragmentedBytes + 1, long.MaxValue); scenario = null; } finally { if (scenario != null) { System.Console.WriteLine("FAILED: " + scenario); } } }).Dispose(); }
public void ToString_ShowILOffset() { string AssemblyName = "ExceptionTestAssembly.dll"; string SourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, AssemblyName); string regPattern = @":token 0x([a-f0-9]*)\+0x([a-f0-9]*)"; // Normal loading case RemoteExecutor.Invoke((asmPath, asmName, p) => { AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true); var asm = Assembly.LoadFrom(asmPath); try { asm.GetType("Program").GetMethod("Foo").Invoke(null, null); } catch (Exception e) { Assert.Contains(asmName, e.InnerException.StackTrace); Assert.Matches(p, e.InnerException.StackTrace); } }, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose(); // Assembly.Load(Byte[]) case RemoteExecutor.Invoke((asmPath, asmName, p) => { AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true); var inMemBlob = File.ReadAllBytes(asmPath); var asm2 = Assembly.Load(inMemBlob); try { asm2.GetType("Program").GetMethod("Foo").Invoke(null, null); } catch (Exception e) { Assert.Contains(asmName, e.InnerException.StackTrace); Assert.Matches(p, e.InnerException.StackTrace); } }, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose(); // AssmblyBuilder.DefineDynamicAssembly() case RemoteExecutor.Invoke((p) => { AppContext.SetSwitch("Switch.System.Diagnostics.StackTrace.ShowILOffsets", true); AssemblyName asmName = new AssemblyName("ExceptionTestAssembly"); AssemblyBuilder asmBldr = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); ModuleBuilder modBldr = asmBldr.DefineDynamicModule(asmName.Name); TypeBuilder tBldr = modBldr.DefineType("Program"); MethodBuilder mBldr = tBldr.DefineMethod("Foo", MethodAttributes.Public | MethodAttributes.Static, null, null); ILGenerator ilGen = mBldr.GetILGenerator(); ilGen.ThrowException(typeof(NullReferenceException)); ilGen.Emit(OpCodes.Ret); Type t = tBldr.CreateType(); try { t.InvokeMember("Foo", BindingFlags.InvokeMethod, null, null, null); } catch (Exception e) { Assert.Contains("RefEmit_InMemoryManifestModule", e.InnerException.StackTrace); Assert.Matches(p, e.InnerException.StackTrace); } }, regPattern).Dispose(); }
public void Dns_GetHostEntry_DisableIPv6_ExcludesIPv6Addresses(string hostnameOuter) { RemoteExecutor.Invoke(RunTest, hostnameOuter).Dispose();
public static void CheckExitCode(int expectedExitCode) { RemoteExecutor.Invoke(s => int.Parse(s), expectedExitCode.ToString(), new RemoteInvokeOptions { ExpectedExitCode = expectedExitCode }).Dispose(); }
public async Task ProxySetViaEnvironmentVariable_DefaultProxyCredentialsUsed(bool useProxy) { const string ExpectedUsername = "******"; const string ExpectedPassword = "******"; LoopbackServer.Options options = new LoopbackServer.Options { IsProxy = true, Username = ExpectedUsername, Password = ExpectedPassword }; await LoopbackServer.CreateClientAndServerAsync(uri => Task.Run(() => { var psi = new ProcessStartInfo(); psi.Environment.Add("http_proxy", $"http://{uri.Host}:{uri.Port}"); RemoteExecutor.Invoke(async(useProxyString, useVersionString, uriString) => { using (HttpClientHandler handler = CreateHttpClientHandler(useVersionString)) using (HttpClient client = CreateHttpClient(handler, useVersionString)) { var creds = new NetworkCredential(ExpectedUsername, ExpectedPassword); handler.DefaultProxyCredentials = creds; handler.UseProxy = bool.Parse(useProxyString); HttpResponseMessage response = await client.GetAsync(uriString); // Correctness of user and password is done in server part. Assert.True(response.StatusCode == HttpStatusCode.OK); }; }, useProxy.ToString(), UseVersion.ToString(), // If proxy is used , the url does not matter. We set it to be different to avoid confusion. useProxy ? Configuration.Http.RemoteEchoServer.ToString() : uri.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose(); }), server => server.AcceptConnectionAsync(async connection => { const string headerName = "Proxy-Authorization"; List <string> lines = await connection.ReadRequestHeaderAsync().ConfigureAwait(false); // First request should not have proxy credentials in either case. for (int i = 1; i < lines.Count; i++) { Assert.False(lines[i].StartsWith(headerName)); } if (useProxy) { // Reject request and wait for authenticated one. await connection.SendResponseAsync(HttpStatusCode.ProxyAuthenticationRequired, "Proxy-Authenticate: Basic realm=\"NetCore\"\r\n").ConfigureAwait(false); lines = await connection.ReadRequestHeaderAsync().ConfigureAwait(false); bool valid = false; for (int i = 1; i < lines.Count; i++) { if (lines[i].StartsWith(headerName)) { valid = LoopbackServer.IsBasicAuthTokenValid(lines[i], options); } } Assert.True(valid); } await connection.SendResponseAsync(HttpStatusCode.OK).ConfigureAwait(false); })); }
public void CtorAndAccept_SocketNotKeptAliveViaInheritance(bool validateClientOuter, int acceptApiOuter) { // Run the test in another process so as to not have trouble with other tests // launching child processes that might impact inheritance. RemoteExecutor.Invoke((validateClientString, acceptApiString) => { bool validateClient = bool.Parse(validateClientString); int acceptApi = int.Parse(acceptApiString); // Create a listening server. using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(); EndPoint ep = listener.LocalEndPoint; // Create a client and connect to that listener. using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { client.Connect(ep); // Accept the connection using one of multiple accept mechanisms. Socket server = acceptApi == 0 ? listener.Accept() : acceptApi == 1 ? listener.AcceptAsync().GetAwaiter().GetResult() : acceptApi == 2 ? Task.Factory.FromAsync(listener.BeginAccept, listener.EndAccept, null).GetAwaiter().GetResult() : throw new Exception($"Unexpected {nameof(acceptApi)}: {acceptApi}"); // Get streams for the client and server, and create a pipe that we'll use // to communicate with a child process. using (var serverStream = new NetworkStream(server, ownsSocket: true)) using (var clientStream = new NetworkStream(client, ownsSocket: true)) using (var serverPipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)) { // Create a child process that blocks waiting to receive a signal on the anonymous pipe. // The whole purpose of the child is to test whether handles are inherited, so we // keep the child process alive until we're done validating that handles close as expected. using (RemoteExecutor.Invoke(clientPipeHandle => { using (var clientPipe = new AnonymousPipeClientStream(PipeDirection.In, clientPipeHandle)) { Assert.Equal(42, clientPipe.ReadByte()); } }, serverPipe.GetClientHandleAsString())) { if (validateClient) // Validate that the child isn't keeping alive the "new Socket" for the client { // Send data from the server to client, then validate the client gets EOF when the server closes. serverStream.WriteByte(84); Assert.Equal(84, clientStream.ReadByte()); serverStream.Close(); Assert.Equal(-1, clientStream.ReadByte()); } else // Validate that the child isn't keeping alive the "listener.Accept" for the server { // Send data from the client to server, then validate the server gets EOF when the client closes. clientStream.WriteByte(84); Assert.Equal(84, serverStream.ReadByte()); clientStream.Close(); Assert.Equal(-1, serverStream.ReadByte()); } // And validate that we after closing the listening socket, we're not able to connect. listener.Dispose(); using (var tmpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.ThrowsAny <SocketException>(() => tmpClient.Connect(ep)); } // Let the child process terminate. serverPipe.WriteByte(42); } } } } }, validateClientOuter.ToString(), acceptApiOuter.ToString()).Dispose(); }
public void MemoryAllocator_Create_WithoutSettings_AllocatesDiscontiguousMemory() { RemoteExecutor.Invoke(RunTest).Dispose();