Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,6 +4,8 @@

using NUnit.Framework;

using Xamarin.Android.NetTests;

namespace System.NetTests {

[TestFixture, Category ("InetAccess")]
Expand All@@ -13,27 +15,23 @@ public class ProxyTest {
[Test]
public void QuoteInvalidQuoteUrlsShouldWork ()
{
try {
string url = "http://www.msftconnecttest.com/connecttest.txt?query&foo|bar";
var request = (HttpWebRequest) WebRequest.Create (url);
request.Method = "GET";
var response = (HttpWebResponse) request.GetResponse ();
int len = 0;
using (var _r = new StreamReader (response.GetResponseStream ())) {
char[] buf = new char [4096];
int n;
while ((n = _r.Read (buf, 0, buf.Length)) > 0) {
/* ignore; we just want to make sure we can read */
len += n;
}
using var server = LocalHttpServer.Start ();
string url = $"{server.Url}ok?query&foo|bar";
var request = (HttpWebRequest) WebRequest.Create (url);
request.Method = "GET";
var response = (HttpWebResponse) request.GetResponse ();
int len = 0;
using (var _r = new StreamReader (response.GetResponseStream ())) {
char[] buf = new char [4096];
int n;
while ((n = _r.Read (buf, 0, buf.Length)) > 0) {
/* ignore; we just want to make sure we can read */
len += n;
}
Assert.IsTrue (len > 0);
} catch (WebException ex) when (
ex.Status == WebExceptionStatus.ConnectFailure ||
ex.Status == WebExceptionStatus.NameResolutionFailure ||
ex.Status == WebExceptionStatus.Timeout) {
Assert.Ignore ($"Ignoring network failure: {ex.Message}");
}
Assert.IsTrue (len > 0);

server.AssertNoUnhandledExceptions ();
}
}
}
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,6 +8,8 @@

using NUnit.Framework;

using Xamarin.Android.NetTests;

namespace System.NetTests {
// TODO: https://github.com/dotnet/android/issues/10069
[TestFixture, Category ("InetAccess"), Category ("SSL")]
Expand All@@ -29,6 +31,7 @@ bool ShouldIgnoreException (WebException wex)
[Test]
public void SslWithinTasksShouldWork ()
{
using var server = LocalHttpsServer.Start ();
var cb = ServicePointManager.ServerCertificateValidationCallback;
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, policy) => {
Console.WriteLine ("# ServerCertificateValidationCallback");
Expand All@@ -39,9 +42,7 @@ public void SslWithinTasksShouldWork ()
Exception exception = null;

var thread = new Thread (() => {
string url = "https://dotnet.microsoft.com/";

var downloadTask = new WebClient ().DownloadDataTaskAsync (url);
var downloadTask = new WebClient ().DownloadDataTaskAsync (server.OkUri);
Comment thread
simonrozsival marked this conversation as resolved.
var completeTask = downloadTask.ContinueWith (t => {
Console.WriteLine ("# DownloadDataTaskAsync complete; status={0}; exception={1}", t.Status, t.Exception);
status = t.Status;
Expand All@@ -55,17 +56,14 @@ public void SslWithinTasksShouldWork ()
ServicePointManager.ServerCertificateValidationCallback = cb;
var wex = (exception as AggregateException)?.InnerException as WebException;
if (wex != null) {
if (ShouldIgnoreException (wex)) {
Assert.Ignore ($"Ignoring network failure: {wex}");
return;
}
throw wex;
}

if (exception != null)
throw exception;

Assert.AreEqual (TaskStatus.RanToCompletion, status);
server.AssertNoUnhandledExceptions ();
}

[Test]
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,20 +4,23 @@
using System.Threading;
using System.Threading.Tasks;

using Xamarin.Android.NetTests;

namespace System.NetTests
{
[TestFixture]
public class WebSocketTests
{
[Test, Category ("InetAccess")]
[Ignore ("echo.websocket.org is not available anymore")]
public void TestSocketConnection()
{
string testMessage = "This is a test!";
var messageBytes = CustomWebSocket.GetBytes (testMessage);
CustomWebSocket.BytesSize = messageBytes.Length;
var result = CustomWebSocket.Connect ("ws://echo.websocket.org", messageBytes).Result;
using var server = LocalWebSocketServer.Start ();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 💡 Testing — Now that this test talks to a loopback LocalWebSocketServer instead of echo.websocket.org, the [Category ("InetAccess")] on the test is arguably stale. InetAccess is excluded on EnableLLVM runs (see TestInstrumentation.cs), so keeping it means this newly re-enabled test still won't run under LLVM even though it no longer needs the internet. Consider dropping the InetAccess category (the same applies to ProxyTest/SslTest.SslWithinTasksShouldWork, which are also loopback-only now).

(Rule: Keep test categories accurate)

var result = CustomWebSocket.Connect (server.Url, messageBytes).Result;
Assert.AreEqual (result, testMessage, $"Socket test failed. Expected: {testMessage}, Received: {result}");
server.AssertNoUnhandledExceptions ();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 💡 Testing — After .Result returns, the client ClientWebSocket is already disposed (Connect closes it), so it tears down the connection without a WebSocket close handshake. That means the server's HandleClient is still running (blocked in EchoLoop's ReceiveAsync) when AssertNoUnhandledExceptions () executes here — a genuine server-side handler failure could be recorded after this assert and silently missed. Consider giving the server a brief drain/join before asserting (e.g. signal completion from HandleClient), or document that the assert is best-effort for this server.

(Rule: Verify async handlers before asserting)

}
}

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -73,14 +73,12 @@ public bool IsBypassed (Uri host)
[Test]
public void Disposed ()
{
using var server = LocalHttpServer.Start ();
var h = CreateHandler ();
h.Dispose ();
var c = new HttpClient (h);
try {
var t = ConnectIgnoreFailure (() => c.GetAsync ("http://google.com"), out bool connectionFailed);
if (connectionFailed)
return;

var t = c.GetAsync (server.OkUri);
t.Wait ();
Assert.Fail ("#1");
} catch (AggregateException e) {
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -147,7 +147,7 @@ public void CancelRequestViaProxy ()
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

var httpClient = new HttpClient (handler) {
BaseAddress = new Uri ("https://google.com"),
BaseAddress = new Uri ("https://localhost/"),
Timeout = TimeSpan.FromMilliseconds (1)
};

Expand DownExpand Up@@ -273,10 +273,12 @@ public void Send_Invalid ()
[Test]
public void GetString_Many ()
{
using var server = LocalHttpServer.Start ();
var client = new HttpClient (new Xamarin.Android.Net.AndroidMessageHandler ());
var t1 = client.GetStringAsync ("https://google.com");
var t2 = client.GetStringAsync ("https://google.com");
var t1 = client.GetStringAsync (server.OkUri);
var t2 = client.GetStringAsync (server.OkUri);
Assert.IsTrue (Task.WaitAll (new [] { t1, t2 }, WaitTimeout));
server.AssertNoUnhandledExceptions ();
}

[Test]
Expand All@@ -285,7 +287,7 @@ public void DisallowAutoRedirect ()
var listener = CreateListener (l => {
using (var response = l.Response)
{
response.Redirect("http://xamarin.com/");
response.Redirect("http://localhost/");
}
});

Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -111,32 +111,33 @@ public async Task DoesNotDisposeContentStream()
public async Task ServerCertificateCustomValidationCallback_ApproveRequest ()
{
bool callbackHasBeenCalled = false;
using var server = LocalHttpsServer.Start ();

var handler = new AndroidMessageHandler {
ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
Assert.NotNull (request, "request");
Assert.AreEqual ("www.microsoft.com", request.RequestUri.Host);
Assert.AreEqual ("localhost", request.RequestUri.Host);
Assert.NotNull (cert, "cert");
Assert.True (cert!.Subject.Contains ("www.microsoft.com"), $"Unexpected certificate subject {cert!.Subject}");
Assert.True (cert!.Issuer.Contains ("Microsoft"), $"Unexpected certificate issuer {cert!.Issuer}");
Assert.True (cert.Subject.Contains ("localhost"), $"Unexpected certificate subject {cert.Subject}");
Assert.NotNull (chain, "chain");
Assert.AreEqual (SslPolicyErrors.None, errors);

callbackHasBeenCalled = true;
return true;
}
};

var client = new HttpClient (handler);
await client.GetStringAsync ("https://www.microsoft.com/");
Assert.AreEqual ("OK", await client.GetStringAsync (server.OkUri));

Assert.IsTrue (callbackHasBeenCalled, "custom validation callback hasn't been called");
server.AssertNoUnhandledExceptions ();
}

[Test]
public async Task ServerCertificateCustomValidationCallback_RejectRequest ()
{
bool callbackHasBeenCalled = false;
using var server = LocalHttpsServer.Start ();

var handler = new AndroidMessageHandler {
ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
Expand All@@ -146,7 +147,7 @@ public async Task ServerCertificateCustomValidationCallback_RejectRequest ()
};
var client = new HttpClient (handler);

await AssertRejectsRemoteCertificate (() => client.GetStringAsync ("https://www.microsoft.com/"));
await AssertRejectsRemoteCertificate (() => client.GetStringAsync (server.OkUri));

Assert.IsTrue (callbackHasBeenCalled, "custom validation callback hasn't been called");
}
Expand DownExpand Up@@ -259,19 +260,23 @@ public async Task AndroidMessageHandlerFollows308PermanentRedirect ()
public async Task AndroidMessageHandlerSendsClientCertificate ([Values(true, false)] bool setClientCertificateOptionsExplicitly)
{
using X509Certificate2 certificate = BuildClientCertificate ();
using var server = LocalHttpsServer.Start (clientCertificateRequired: true);

using var handler = new AndroidMessageHandler ();
using var handler = new AndroidMessageHandler {
ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => true,
};
if (setClientCertificateOptionsExplicitly) {
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
}
handler.ClientCertificates.Add (certificate);

using var client = new HttpClient (handler);
var response = await client.GetAsync ("https://corefx-net-tls.azurewebsites.net/EchoClientCertificate.ashx");
var response = await client.GetAsync (server.GetUri ("echo-client-certificate"));
var content = await response.EnsureSuccessStatusCode ().Content.ReadAsStringAsync ();

X509Certificate2 certificate2 = new X509Certificate2 (global::System.Convert.FromBase64String (content));
Assert.AreEqual (certificate.Thumbprint, certificate2.Thumbprint);
server.AssertNoUnhandledExceptions ();
}

[Test]
Expand Down
Loading