Here are the examples of the csharp api Xunit.Assert.Equal(int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
561 Examples
19
View Source File : FeatureDefinitionFactoryTests.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
[Fact]
public void FactoryAddActivatedFeaturesDoesNotAddExistingDefinitions()
{
// Arrange
Guid[] fIds = { TestFeatureDefinitions.Ids.Id004 ,
TestFeatureDefinitions.Ids.Id001,
TestFeatureDefinitions.Ids.Id002,
TestFeatureDefinitions.Ids.Id003 };
Guid[] lIds = { TestLocations.Ids.Id005,
TestLocations.Ids.Id006,
TestLocations.Ids.Id007 };
var featureDefinitions = TestFeatureDefinitions.GetFeatureDefinitions(fIds, lIds).ToList();
// Act
featureDefinitions.AddActivatedFeatures(Loaded3LocationsWithFirst4ActivatedFeaturesEach.ActivatedFeatures);
// replacedert
var expectedFeatureDefinitions = 4;
replacedert.Equal(expectedFeatureDefinitions, featureDefinitions.Count());
foreach (Guid featureId in fIds)
{
var definition = featureDefinitions.FirstOrDefault(fd => fd.Id == featureId);
var expectedActivatedFeatures = 6;
replacedert.Equal(expectedActivatedFeatures, definition.ActivatedFeatures.Count());
}
}
19
View Source File : FeatureDefinitionFactoryTests.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
[Fact]
public void FactoryAddActivatedFeaturesCanAddDefinitionsIfItDoesNotExist()
{
// Arrange
Guid[] fIds = { TestFeatureDefinitions.Ids.Id008 ,
TestFeatureDefinitions.Ids.Id009,
TestFeatureDefinitions.Ids.Id010 };
Guid[] lIds = { TestLocations.Ids.Id005,
TestLocations.Ids.Id008,
TestLocations.Ids.Id009 };
var featureDefinitions = TestFeatureDefinitions.GetFeatureDefinitions(fIds, lIds).ToList();
// Act
featureDefinitions.AddActivatedFeatures(Loaded3LocationsWithFirst4ActivatedFeaturesEach.ActivatedFeatures);
// replacedert
var expectedFeatureDefinitions = 7;
replacedert.Equal(expectedFeatureDefinitions, featureDefinitions.Count());
foreach (Guid featureId in fIds)
{
var definition = featureDefinitions.FirstOrDefault(fd => fd.Id == featureId);
var expectedActivatedFeatures = 3;
replacedert.Equal(expectedActivatedFeatures, definition.ActivatedFeatures.Count());
}
}
19
View Source File : FeatureActivationAndDeactivationTest.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
[Fact]
public void CanDeactivateAndActivateHealthyFeatures()
{
// Arrange
int processingCounter = 0;
Exception exception;
// Act
processingCounter = FeatureActivationAndDeactivationBulk.DeactivateAllFeatures(TestContent.TestFeatures.AllHealthyActivatedFeatures, false, out exception);
// replacedert
replacedert.Equal(6, processingCounter);
// Act - activate healthy web and sico feature in active sico
processingCounter = FeatureActivationAndDeactivationBulk.ActivateAllFeaturesWithinSharePointContainer(
TestContent.SharePointContainers.SiCoActivated.GetMockFeatureParent(),
TestContent.TestFeatures.AllHealthyFeatureDefinitions,
false,
out exception);
// after this, also the feature in inactive sub web is active ... :(
replacedert.Equal(4, processingCounter);
// Act - activate healthy web feature in inactive sico subweb active
processingCounter = FeatureActivationAndDeactivationBulk.ActivateAllFeaturesWithinSharePointContainer(
TestContent.SharePointContainers.SiCoInActive.SubWebActivated.GetMockFeatureParent(),
TestContent.TestFeatures.AllHealthyFeatureDefinitions,
false,
out exception);
// replacedert
replacedert.Equal(1, processingCounter);
// from here more or less do tests and rollback previous activation state ...
// Act - deactivate the healthy web feature in inactive sico subweb inactive
processingCounter = FeatureActivationAndDeactivationBulk.DeactivateAllFeatures(
new List<MockActivatedFeature>() {
TestContent.TestFeatures.HealthyWeb.GetMockActivatedFeature(TestContent.SharePointContainers.SiCoActivated.SubWebInactive.GetMockFeatureParent())
},
false,
out exception);
// replacedert
replacedert.Equal(1, processingCounter);
// Act activate web app feature
processingCounter = FeatureActivationAndDeactivationCore.ProcessWebAppFeatureInWebApp(
FarmRead.GetWebAppByUrl(TestContent.SharePointContainers.WebApplication.Url),
TestContent.TestFeatures.HealthyWebApp.Id,
true,
false,
out exception);
// replacedert
replacedert.Equal(1, processingCounter);
// Act activate farm feature
processingCounter = FeatureActivationAndDeactivationCore.ProcessFarmFeatureInFarm(
FarmRead.GetFarm(),
TestContent.TestFeatures.HealthyFarm.Id,
true,
false,
out exception);
// replacedert
replacedert.Equal(1, processingCounter);
}
19
View Source File : FeatureActivationAndDeactivationTest.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
[Fact]
/// <summary>
/// warning, after this test, the reference content needs to be re-set up
/// </summary>
public void CanDeactivateFaultyWebFeatures()
{
// Arrange
int processingCounter = 0;
Exception exception;
// Act
processingCounter = FeatureActivationAndDeactivationBulk.DeactivateAllFeatures(
//new List<MockActivatedFeature>() {
// TestContent.TestFeatures.FaultyWeb.GetMockActivatedFeatureInSiCoActivatedRootWeb() },
TestContent.TestFeatures.AllFaultyActivatedFeatures,
true,
out exception);
// replacedert
replacedert.Equal(4, processingCounter);
}
19
View Source File : GridifyExtensionsShould.cs
License : MIT License
Project Creator : alirezanet
License : MIT License
Project Creator : alirezanet
[Fact]
public void Gridify_ActionOverload()
{
var actual = _fakeRepository.AsQueryable()
.Gridify(q =>
{
q.Filter = "name=John";
q.PageSize = 13;
q.OrderBy = "name desc";
});
var query = _fakeRepository.AsQueryable().Where(q => q.Name == "John").OrderByDescending(q => q.Name);
var totalItems = query.Count();
var items = query.Skip(-2).Take(15).ToList();
var expected = new Paging<TestClreplaced>() { Data = items, Count = totalItems };
replacedert.Equal(expected.Count, actual.Count);
replacedert.Equal(expected.Data.Count(), actual.Data.Count());
replacedert.True(actual.Data.Any());
replacedert.Equal(expected.Data.First().Id, actual.Data.First().Id);
}
19
View Source File : GridifyMapperShould.cs
License : MIT License
Project Creator : alirezanet
License : MIT License
Project Creator : alirezanet
[Fact]
public void GenerateMappings()
{
_sut.GenerateMappings();
var props = typeof(TestClreplaced).GetProperties()
.Where(q => !q.PropertyType.IsClreplaced || q.PropertyType == typeof(string));
replacedert.Equal(props.Count(), _sut.GetCurrentMaps().Count());
replacedert.True(_sut.HasMap("Id"));
}
19
View Source File : AjaxRequest.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory, Trait("FunctionalTests", "Security")]
[InlineData(HostType.IIS)]
[InlineData(HostType.HttpListener)]
public void Security_AjaxUnAuthorizedResponses(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
string applicationUrl = deployer.Deploy(hostType, SimulateAjaxRequestConfiguration);
var httpClient = new HttpClient();
//Simulate an AJAX request
httpClient.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
var response = httpClient.GetAsync(applicationUrl).Result;
//For AJAX requests the cookie middleware should not send a 302 on a 401 response.
//Instead it should send a response back with this below header and a dictionary having the redirect location information
replacedert.NotEmpty(string.Join(",", response.Headers.GetValues("X-Responded-JSON")));
var ajaxResponseObject = JsonConvert.DeserializeObject<AjaxResponse>(string.Join(",", response.Headers.GetValues("X-Responded-JSON")));
replacedert.Equal<int>(401, ajaxResponseObject.status);
replacedert.Equal<int>(1, ajaxResponseObject.headers.Count);
replacedert.True(new Uri(ajaxResponseObject.headers["location"]).AbsolutePath.EndsWith("/Auth/CookiesLogin"));
replacedert.Equal<string>(new Uri(ajaxResponseObject.headers["location"]).ParseQueryString()["ReturnUrl"], new Uri(applicationUrl).AbsolutePath);
}
}
19
View Source File : WebSocketTest.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory, Trait("FunctionalTests", "General")]
[InlineData(HostType.HttpListener)]
public async Task WebsocketBasic(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
string applicationUrl = deployer.Deploy(hostType, WebsocketBasicConfiguration);
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(applicationUrl.Replace("http://", "ws://")), CancellationToken.None);
var receiveBody = new byte[100];
for (int i = 0; i < 4; i++)
{
var message = "Message " + i.ToString();
byte[] sendBody = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(sendBody), WebSocketMessageType.Text, true, CancellationToken.None);
var receiveResult = await client.ReceiveAsync(new ArraySegment<byte>(receiveBody), CancellationToken.None);
replacedert.Equal(WebSocketMessageType.Text, receiveResult.MessageType);
replacedert.True(receiveResult.EndOfMessage);
replacedert.Equal(sendBody.Length, receiveResult.Count);
replacedert.Equal(message, Encoding.UTF8.GetString(receiveBody, 0, receiveResult.Count));
}
}
}
}
19
View Source File : CanonicalRequestPatternsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task ShouldReturnSmallUrl()
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:8080/small-immediate-syncwrite");
replacedert.Equal("text/plain", response.Content.Headers.ContentType.MediaType);
string text = await response.Content.ReadreplacedtringAsync();
replacedert.Equal(1 << 10, text.Length);
}
19
View Source File : CanonicalRequestPatternsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task ShouldReturnLargeUrl()
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:8080/large-immediate-syncwrite");
replacedert.Equal("text/plain", response.Content.Headers.ContentType.MediaType);
string text = await response.Content.ReadreplacedtringAsync();
replacedert.Equal(1 << 20, text.Length);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void NullPolicyProvider_CallsNext()
{
IAppBuilder builder = new AppBuilder();
builder.UseCors(new CorsOptions
{
});
builder.Run(context =>
{
context.Response.StatusCode = 200;
return Task.FromResult(0);
});
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/sample");
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
replacedert.Equal(200, response.StatusCode);
replacedert.Empty(response.Headers);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void NullPolicy_CallsNext()
{
IAppBuilder builder = new AppBuilder();
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider()
});
builder.Run(context =>
{
context.Response.StatusCode = 200;
return Task.FromResult(0);
});
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/sample");
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
replacedert.Equal(200, response.StatusCode);
replacedert.Empty(response.Headers);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData(null, "*", null)]
[InlineData("", "*", null)]
[InlineData("header_not_set", "*", null)]
[InlineData("http://example.com", "*", "*")]
[InlineData("http://example.com", "http://example.com", "http://example.com")]
[InlineData("http://other.com", "http://other.com, http://example.com", "http://other.com")]
[InlineData("http://example.com", "http://other.com, http://example.com", "http://example.com")]
[InlineData("http://invalid.com", "http://example.com", null)]
[InlineData("http://invalid.com", "http://other.com, http://example.com", null)]
public void SendAsync_ReturnsAllowAOrigin(string requestOrigin, string policyOrigin, string expectedOrigin)
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy();
if (policyOrigin == "*")
{
policy.AllowAnyOrigin = true;
}
else
{
foreach (var o in policyOrigin.Split(','))
{
policy.Origins.Add(o.Trim());
}
}
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
builder.Use((context, next) => Task.FromResult<object>(null));
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/sample");
if ("header_not_set" != requestOrigin)
{
request.Headers.Set(CorsConstants.Origin, requestOrigin);
}
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get("Access-Control-Allow-Origin");
replacedert.Equal(200, response.StatusCode);
replacedert.Equal(expectedOrigin, origin);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("*", "DELETE", "*", "foo,bar")]
[InlineData("http://example.com, http://localhost", "PUT", "http://localhost", "content-type,custom")]
public void SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders(string policyOrigin, string requestedMethod, string expectedOrigin, string requestedHeaders)
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true
};
if (policyOrigin == "*")
{
policy.AllowAnyOrigin = true;
}
else
{
foreach (var o in policyOrigin.Split(','))
{
policy.Origins.Add(o.Trim());
}
}
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
builder.Use((context, next) => Task.FromResult<object>(null));
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/sample");
request.Method = "OPTIONS";
request.Headers.Set(CorsConstants.Origin, "http://localhost");
request.Headers.Set(CorsConstants.AccessControlRequestMethod, requestedMethod);
request.Headers.Set(CorsConstants.AccessControlRequestHeaders, requestedHeaders);
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get(CorsConstants.AccessControlAllowOrigin);
string allowMethod = response.Headers.Get(CorsConstants.AccessControlAllowMethods);
string[] allowHeaders = response.Headers.Get(CorsConstants.AccessControlAllowHeaders).Split(',');
string[] requestedHeaderArray = requestedHeaders.Split(',');
replacedert.Equal(200, response.StatusCode);
replacedert.Equal(expectedOrigin, origin);
replacedert.Equal(requestedMethod, allowMethod);
foreach (var requestedHeader in requestedHeaderArray)
{
replacedert.Contains(requestedHeader, allowHeaders);
}
request = CreateRequest("http://localhost/sample");
request.Method = requestedMethod;
request.Headers.Set(CorsConstants.Origin, "http://localhost");
foreach (var requestedHeader in requestedHeaderArray)
{
request.Headers.Set(requestedHeader, requestedHeader);
}
app(request.Environment).Wait();
response = new OwinResponse(request.Environment);
replacedert.Equal(200, response.StatusCode);
replacedert.Equal(expectedOrigin, origin);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void SendAsync_Preflight_ReturnsBadRequest_WhenOriginIsNotAllowed()
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy();
policy.AllowAnyMethod = true;
policy.AllowAnyHeader = true;
policy.Origins.Add("http://www.example.com");
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/default");
request.Method = "OPTIONS";
request.Headers.Set(CorsConstants.Origin, "http://localhost");
request.Headers.Set(CorsConstants.AccessControlRequestMethod, "POST");
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get(CorsConstants.AccessControlAllowOrigin);
replacedert.Equal(400, response.StatusCode);
replacedert.Equal(null, origin);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void SendAsync_Preflight_ReturnsBadRequest_WhenMethodIsNotAllowed()
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy();
policy.Methods.Add("DELETE");
policy.AllowAnyHeader = true;
policy.Origins.Add("http://www.example.com");
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/default");
request.Method = "OPTIONS";
request.Headers.Set(CorsConstants.Origin, "http://localhost");
request.Headers.Set(CorsConstants.AccessControlRequestMethod, "POST");
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get(CorsConstants.AccessControlAllowOrigin);
replacedert.Equal(400, response.StatusCode);
replacedert.Equal(null, origin);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void SendAsync_Preflight_ReturnsBadRequest_WhenHeaderIsNotAllowed()
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy();
policy.AllowAnyMethod = true;
policy.Headers.Add("TEST");
policy.Origins.Add("http://www.example.com");
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/default");
request.Method = "OPTIONS";
request.Headers.Set(CorsConstants.Origin, "http://localhost");
request.Headers.Set(CorsConstants.AccessControlRequestMethod, "POST");
request.Headers.Set(CorsConstants.AccessControlRequestHeaders, "INVALID");
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get(CorsConstants.AccessControlAllowOrigin);
replacedert.Equal(400, response.StatusCode);
replacedert.Equal(null, origin);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_EmptyGetRequest_RequiredHeadersPresentAndCorrect()
{
OwinHttpListener listener = CreateServer(
env =>
{
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
string[] values;
replacedert.True(requestHeaders.TryGetValue("host", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("localhost:8080", values[0]);
return Task.FromResult(0);
},
HttpServerAddress);
await SendGetRequest(listener, HttpClientAddress);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_MultiValueHeader_NotSplit()
{
OwinHttpListener listener = CreateServer(
env =>
{
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
string[] values;
replacedert.True(requestHeaders.TryGetValue("If-None-Match", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("Value1, value2", values[0]);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Get, HttpClientAddress);
request.Headers.TryAddWithoutValidation("If-None-Match", "Value1, value2");
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_PostContentLengthRequest_RequiredHeadersPresentAndCorrect()
{
string requestBody = "Hello World";
OwinHttpListener listener = CreateServer(
env =>
{
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
string[] values;
replacedert.True(requestHeaders.TryGetValue("host", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("localhost:8080", values[0]);
replacedert.True(requestHeaders.TryGetValue("Content-length", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal(requestBody.Length.ToString(), values[0]);
replacedert.True(requestHeaders.TryGetValue("exPect", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("100-continue", values[0]);
replacedert.True(requestHeaders.TryGetValue("Content-Type", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("text/plain; charset=utf-8", values[0]);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString");
request.Content = new StringContent(requestBody);
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_PostChunkedRequest_RequiredHeadersPresentAndCorrect()
{
string requestBody = "Hello World";
OwinHttpListener listener = CreateServer(
env =>
{
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
string[] values;
replacedert.True(requestHeaders.TryGetValue("host", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("localhost:8080", values[0]);
replacedert.True(requestHeaders.TryGetValue("Transfer-encoding", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("chunked", values[0]);
replacedert.True(requestHeaders.TryGetValue("exPect", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("100-continue", values[0]);
replacedert.True(requestHeaders.TryGetValue("Content-Type", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("text/plain; charset=utf-8", values[0]);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString");
request.Headers.TransferEncodingChunked = true;
request.Content = new StringContent(requestBody);
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Body_PostContentLengthZero_NullStream()
{
OwinHttpListener listener = CreateServer(
env =>
{
string[] values;
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
replacedert.True(requestHeaders.TryGetValue("Content-length", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("0", values[0]);
replacedert.NotNull(env.Get<Stream>("owin.RequestBody"));
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
request.Content = new StringContent(string.Empty);
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Body_PostContentLengthX_StreamWithXBytes()
{
OwinHttpListener listener = CreateServer(
env =>
{
string[] values;
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
replacedert.True(requestHeaders.TryGetValue("Content-length", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("11", values[0]);
var requestBody = env.Get<Stream>("owin.RequestBody");
replacedert.NotNull(requestBody);
var buffer = new MemoryStream();
requestBody.CopyTo(buffer);
replacedert.Equal(11, buffer.Length);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
request.Content = new StringContent("Hello World");
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Body_PostChunkedEmpty_StreamWithZeroBytes()
{
OwinHttpListener listener = CreateServer(
env =>
{
string[] values;
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
replacedert.True(requestHeaders.TryGetValue("Transfer-Encoding", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("chunked", values[0]);
var requestBody = env.Get<Stream>("owin.RequestBody");
replacedert.NotNull(requestBody);
var buffer = new MemoryStream();
requestBody.CopyTo(buffer);
replacedert.Equal(0, buffer.Length);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
request.Headers.TransferEncodingChunked = true;
request.Content = new StringContent(string.Empty);
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Body_PostChunkedX_StreamWithXBytes()
{
OwinHttpListener listener = CreateServer(
env =>
{
string[] values;
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
replacedert.True(requestHeaders.TryGetValue("Transfer-Encoding", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("chunked", values[0]);
var requestBody = env.Get<Stream>("owin.RequestBody");
replacedert.NotNull(requestBody);
var buffer = new MemoryStream();
requestBody.CopyTo(buffer);
replacedert.Equal(11, buffer.Length);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
request.Headers.TransferEncodingChunked = true;
request.Content = new StringContent("Hello World");
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task OwinHttpListenerResponse_Empty200Response_Success()
{
OwinHttpListener listener = CreateServer(call => Task.FromResult(0), HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("OK", response.ReasonPhrase);
replacedert.Equal(2, response.Headers.Count());
replacedert.False(response.Headers.TransferEncodingChunked.HasValue);
replacedert.True(response.Headers.Date.HasValue);
replacedert.Equal(1, response.Headers.Server.Count);
replacedert.Equal(1, response.Content.Headers.Count()); // Content-Length
replacedert.Equal(0, response.Content.Headers.ContentLength);
replacedert.Equal(string.Empty, await response.Content.ReadreplacedtringAsync());
}
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task OwinHttpListenerResponse_Empty404Response_Success()
{
OwinHttpListener listener = CreateServer(env =>
{
env["owin.ResponseStatusCode"] = 404;
return Task.FromResult(0);
}, HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
replacedert.Equal(HttpStatusCode.NotFound, response.StatusCode);
replacedert.Equal("Not Found", response.ReasonPhrase);
replacedert.Equal(2, response.Headers.Count());
replacedert.False(response.Headers.TransferEncodingChunked.HasValue);
replacedert.True(response.Headers.Date.HasValue);
replacedert.Equal(1, response.Headers.Server.Count);
replacedert.Equal(1, response.Content.Headers.Count()); // Content-Length
replacedert.Equal(0, response.Content.Headers.ContentLength);
replacedert.Equal(string.Empty, await response.Content.ReadreplacedtringAsync());
}
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task OwinHttpListenerResponse_HeadRequestWithContentLength_Success()
{
OwinHttpListener listener = CreateServer(env =>
{
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
responseHeaders["Content-Length"] = new string[] { "10" };
return Task.FromResult(0);
}, HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, HttpClientAddress);
HttpResponseMessage response = await client.SendAsync(request);
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("OK", response.ReasonPhrase);
replacedert.Equal(2, response.Headers.Count());
replacedert.False(response.Headers.TransferEncodingChunked.HasValue);
replacedert.True(response.Headers.Date.HasValue);
replacedert.Equal(1, response.Headers.Server.Count);
replacedert.Equal(1, response.Content.Headers.Count()); // Content-Length
replacedert.Equal(10, response.Content.Headers.ContentLength);
replacedert.Equal(string.Empty, await response.Content.ReadreplacedtringAsync());
}
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_CustomHeaders_PreplacededThrough()
{
OwinHttpListener listener = CreateServer(
env =>
{
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
responseHeaders.Add("Custom1", new string[] { "value1a", "value1b" });
responseHeaders.Add("Custom2", new string[] { "value2a, value2b" });
responseHeaders.Add("Custom3", new string[] { "value3a, value3b", "value3c" });
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal(5, response.Headers.Count()); // Date, Server
replacedert.Equal(2, response.Headers.GetValues("Custom1").Count());
replacedert.Equal("value1a", response.Headers.GetValues("Custom1").First());
replacedert.Equal("value1b", response.Headers.GetValues("Custom1").Skip(1).First());
replacedert.Equal(1, response.Headers.GetValues("Custom2").Count());
replacedert.Equal("value2a, value2b", response.Headers.GetValues("Custom2").First());
replacedert.Equal(2, response.Headers.GetValues("Custom3").Count());
replacedert.Equal("value3a, value3b", response.Headers.GetValues("Custom3").First());
replacedert.Equal("value3c", response.Headers.GetValues("Custom3").Skip(1).First());
}
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task OwinHttpListenerResponse_NoWrite_OnSendingHeaders()
{
OwinHttpListener listener = CreateServer(
env =>
{
env["owin.ResponseStatusCode"] = 200;
env["owin.ResponseReasonPhrase"] = "Custom";
var responseStream = env.Get<Stream>("owin.ResponseBody");
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
env.Get<Action<Action<object>, object>>("server.OnSendingHeaders")(state =>
{
env["owin.ResponseStatusCode"] = 201;
env["owin.ResponseReasonPhrase"] = "Custom1";
responseHeaders["custom-header"] = new string[] { "customvalue" };
}, null);
responseHeaders["content-length"] = new string[] { "0" };
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
replacedert.Equal(HttpStatusCode.Created, response.StatusCode);
replacedert.Equal("Custom1", response.ReasonPhrase);
replacedert.Equal(3, response.Headers.Count()); // Date, Server
replacedert.True(response.Headers.Date.HasValue);
replacedert.Equal(1, response.Headers.Server.Count);
replacedert.Equal("customvalue", response.Headers.GetValues("custom-header").First());
replacedert.Equal(0, (await response.Content.ReadAsByteArrayAsync()).Length);
}
}
19
View Source File : ExceptionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public async Task AsyncExceptionAfterHeaders(string serverName)
{
int port = RunWebServer(
serverName,
AsyncExceptionAfterHeadersApp);
var client = new HttpClient();
var response = await client.GetAsync("http://localhost:" + port, HttpCompletionOption.ResponseHeadersRead);
replacedert.True(response.IsSuccessStatusCode);
Stream body = response.Content.ReadreplacedtreamAsync().Result;
int read = body.Read(new byte[11], 0, 11);
replacedert.Equal(11, read);
replacedert.Throws<IOException>(() =>
{
read = body.Read(new byte[10], 0, 10);
replacedert.Equal(-1, read);
});
}
19
View Source File : ExceptionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public async Task ExceptionAfterHeadersWithContentLength(string serverName)
{
int port = RunWebServer(
serverName,
ExceptionAfterHeadersWithContentLengthApp);
var client = new HttpClient();
var response = await client.GetAsync("http://localhost:" + port, HttpCompletionOption.ResponseHeadersRead);
replacedert.True(response.IsSuccessStatusCode);
replacedert.Equal(20, response.Content.Headers.ContentLength.Value);
Stream body = response.Content.ReadreplacedtreamAsync().Result;
int read = body.Read(new byte[11], 0, 11);
replacedert.Equal(11, read);
replacedert.Throws<IOException>(() => body.Read(new byte[10], 0, 10));
}
19
View Source File : SystemWebCookieManagerTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("name", "value", "name=value; path=/")]
[InlineData("name123", "value456", "name123=value456; path=/")]
[InlineData("[email protected]#$%^&*()_", "[email protected]#$%^&*()_", "name%2B%21%40%23%24%25%5E%26%2A%28%29_=value%2B%21%40%23%24%25%5E%26%2A%28%29_; path=/")]
public async Task AppendCookie(string cookieName, string value, string expected)
{
int port = RunWebServer("Microsoft.Owin.Host.SystemWeb", CookieManagerAppendCookieApp);
var client = new HttpClient(new HttpClientHandler() { UseCookies = false });
var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost:" + port + "/AppendCookie");
message.Headers.TryAddWithoutValidation("CookieName", cookieName);
message.Headers.TryAddWithoutValidation("CookieValue", value);
var response = await client.SendAsync(message);
replacedert.Equal("AppendCookieApp", await response.Content.ReadreplacedtringAsync());
IEnumerable<string> values;
replacedert.True(response.Headers.TryGetValues("Set-Cookie", out values));
replacedert.Equal(1, values.Count());
replacedert.Equal(expected, values.First());
}
19
View Source File : SystemWebCookieManagerTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("name", "name=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/")]
[InlineData("name123", "name123=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/")]
[InlineData("[email protected]#$%^&*()_", "name%2B%21%40%23%24%25%5E%26%2A%28%29_=; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/")]
public async Task DeleteCookie(string cookieName, string expected)
{
int port = RunWebServer("Microsoft.Owin.Host.SystemWeb", CookieManagerDeleteCookieApp);
var client = new HttpClient(new HttpClientHandler() { UseCookies = false });
var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost:" + port + "/DeleteCookie");
message.Headers.TryAddWithoutValidation("CookieName", cookieName);
var response = await client.SendAsync(message);
replacedert.Equal("DeleteCookieApp", await response.Content.ReadreplacedtringAsync());
IEnumerable<string> values;
replacedert.True(response.Headers.TryGetValues("Set-Cookie", out values));
replacedert.Equal(1, values.Count());
replacedert.Equal(expected, values.First());
}
19
View Source File : HostingEngineTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void MultipleUrlsSpecified()
{
var startOptions = new StartOptions();
startOptions.Urls.Add("beta://localhost:3333");
startOptions.Urls.Add("delta://foo/");
startOptions.Urls.Add("gama://*:4444/");
startOptions.Port = 1111; // Ignored because of Url(s)
var serverFactory = new ServerFactoryAlpha();
var startInfo = new StartContext(startOptions);
startInfo.ServerFactory = new ServerFactoryAdapter(serverFactory);
startInfo.App = new AppFunc(env => Task.FromResult(0));
var engine = ServicesFactory.Create().GetService<IHostingEngine>();
serverFactory.InitializeCalled.ShouldBe(false);
serverFactory.CreateCalled.ShouldBe(false);
IDisposable server = engine.Start(startInfo);
serverFactory.InitializeProperties["host.Addresses"].ShouldBeTypeOf<IList<IDictionary<string, object>>>();
var addresses = (IList<IDictionary<string, object>>)serverFactory.InitializeProperties["host.Addresses"];
replacedert.Equal(3, addresses.Count);
var expectedAddresses = new[]
{
new[] { "beta", "localhost", "3333", string.Empty },
new[] { "delta", "foo", string.Empty, "/" },
new[] { "gama", "*", "4444", "/" },
};
for (int i = 0; i < addresses.Count; i++)
{
IDictionary<string, object> addressDictionary = addresses[i];
string[] expectedValues = expectedAddresses[i];
replacedert.Equal(expectedValues.Length, addressDictionary.Count);
replacedert.Equal(expectedValues[0], (string)addressDictionary["scheme"]);
replacedert.Equal(expectedValues[1], (string)addressDictionary["host"]);
replacedert.Equal(expectedValues[2], (string)addressDictionary["port"]);
replacedert.Equal(expectedValues[3], (string)addressDictionary["path"]);
}
server.Dispose();
}
19
View Source File : OwinWebSocketTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task EndToEnd_ConnectAndClose_Success()
{
OwinHttpListener listener = CreateServer(env =>
{
var accept = (WebSocketAccept)env["websocket.Accept"];
replacedert.NotNull(accept);
accept(
null,
async wsEnv =>
{
var sendAsync1 = wsEnv.Get<WebSocketSendAsync>("websocket.SendAsync");
var receiveAsync1 = wsEnv.Get<WebSocketReceiveAsync>("websocket.ReceiveAsync");
var closeAsync1 = wsEnv.Get<WebSocketCloseAsync>("websocket.CloseAsync");
var buffer1 = new ArraySegment<byte>(new byte[10]);
await receiveAsync1(buffer1, CancellationToken.None);
await closeAsync1((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
});
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);
await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
WebSocketReceiveResult readResult = await client.ReceiveAsync(new ArraySegment<byte>(new byte[10]), CancellationToken.None);
replacedert.Equal(WebSocketCloseStatus.NormalClosure, readResult.CloseStatus);
replacedert.Equal("Closing", readResult.CloseStatusDescription);
replacedert.Equal(0, readResult.Count);
replacedert.True(readResult.EndOfMessage);
replacedert.Equal(WebSocketMessageType.Close, readResult.MessageType);
}
}
}
19
View Source File : ExceptionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public async Task SyncExceptionAfterHeaders(string serverName)
{
int port = RunWebServer(
serverName,
SyncExceptionAfterHeadersApp);
var client = new HttpClient();
var response = await client.GetAsync("http://localhost:" + port, HttpCompletionOption.ResponseHeadersRead);
replacedert.True(response.IsSuccessStatusCode);
Stream body = response.Content.ReadreplacedtreamAsync().Result;
int read = body.Read(new byte[11], 0, 11);
replacedert.Equal(11, read);
replacedert.Throws<IOException>(() => body.Read(new byte[10], 0, 10));
}
19
View Source File : OwinClientHandlerTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void ExpectedKeysAreAvailable()
{
var handler = new OwinClientHandler(env =>
{
IOwinContext context = new OwinContext(env);
replacedert.Equal("1.0", context.Get<string>("owin.Version"));
replacedert.NotNull(context.Get<CancellationToken>("owin.CallCancelled"));
replacedert.Equal("HTTP/1.1", context.Request.Protocol);
replacedert.Equal("GET", context.Request.Method);
replacedert.Equal("https", context.Request.Scheme);
replacedert.Equal(string.Empty, context.Get<string>("owin.RequestPathBase"));
replacedert.Equal("/A/Path/and/file.txt", context.Get<string>("owin.RequestPath"));
replacedert.Equal("and=query", context.Get<string>("owin.RequestQueryString"));
replacedert.NotNull(context.Request.Body);
replacedert.NotNull(context.Get<IDictionary<string, string[]>>("owin.RequestHeaders"));
replacedert.NotNull(context.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"));
replacedert.NotNull(context.Response.Body);
replacedert.Equal(200, context.Get<int>("owin.ResponseStatusCode"));
replacedert.Null(context.Get<string>("owin.ResponseReasonPhrase"));
replacedert.Equal("example.com", context.Request.Headers.Get("Host"));
return Task.FromResult(0);
});
var httpClient = new HttpClient(handler);
httpClient.GetAsync("https://example.com/A/Path/and/file.txt?and=query").Wait();
}
19
View Source File : OwinClientHandlerTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task ClientDisposalCloses()
{
ManualResetEvent block = new ManualResetEvent(false);
var handler = new OwinClientHandler(env =>
{
IOwinContext context = new OwinContext(env);
context.Response.Headers["TestHeader"] = "TestValue";
context.Response.Body.Flush();
block.WaitOne();
return Task.FromResult(0);
});
var httpClient = new HttpClient(handler);
HttpResponseMessage response = await httpClient.GetAsync("https://example.com/",
HttpCompletionOption.ResponseHeadersRead);
replacedert.Equal("TestValue", response.Headers.GetValues("TestHeader").First());
Stream responseStream = await response.Content.ReadreplacedtreamAsync();
Task<int> readTask = responseStream.ReadAsync(new byte[100], 0, 100);
replacedert.False(readTask.IsCompleted);
responseStream.Dispose();
Thread.Sleep(50);
replacedert.True(readTask.IsCompleted);
replacedert.Equal(0, readTask.Result);
block.Set();
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_ReservedHeaders_PreplacededThrough()
{
OwinHttpListener listener = CreateServer(
env =>
{
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
env.Add("owin.ResponseProtocol", "HTTP/1.0");
responseHeaders.Add("KEEP-alive", new string[] { "TRUE" });
responseHeaders.Add("content-length", new string[] { "0" });
responseHeaders.Add("www-Authenticate", new string[] { "Basic", "NTLM" });
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal(3, response.Headers.Count()); // Date, Server
replacedert.Equal(0, response.Content.Headers.ContentLength);
replacedert.Equal(2, response.Headers.WwwAuthenticate.Count());
// The client does not expose KeepAlive
}
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_OtherReservedHeaders_PreplacededThrough()
{
OwinHttpListener listener = CreateServer(
env =>
{
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
responseHeaders.Add("Transfer-Encoding", new string[] { "ChUnKed" });
responseHeaders.Add("CONNECTION", new string[] { "ClOsE" });
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal(4, response.Headers.Count()); // Date, Server
replacedert.Equal("chunked", response.Headers.TransferEncoding.ToString()); // Normalized by server
replacedert.True(response.Headers.TransferEncodingChunked.Value);
replacedert.Equal("close", response.Headers.Connection.First()); // Normalized by server
replacedert.True(response.Headers.ConnectionClose.Value);
}
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task OwinHttpListenerResponse_Empty101Response_Success()
{
OwinHttpListener listener = CreateServer(
env =>
{
env["owin.ResponseStatusCode"] = 101;
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
replacedert.Equal(HttpStatusCode.SwitchingProtocols, response.StatusCode);
replacedert.Equal("Switching Protocols", response.ReasonPhrase);
replacedert.Equal(2, response.Headers.Count()); // Date, Server
replacedert.True(response.Headers.Date.HasValue);
replacedert.Equal(1, response.Headers.Server.Count);
replacedert.Equal(string.Empty, await response.Content.ReadreplacedtringAsync());
}
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task OwinHttpListenerResponse_101ResponseWithBody_BodyIgnoredByClient()
{
OwinHttpListener listener = CreateServer(
env =>
{
env["owin.ResponseStatusCode"] = 101;
var responseStream = env.Get<Stream>("owin.ResponseBody");
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
responseHeaders["content-length"] = new string[] { "10" };
responseStream.Write(new byte[10], 0, 10);
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
replacedert.Equal(HttpStatusCode.SwitchingProtocols, response.StatusCode);
replacedert.Equal("Switching Protocols", response.ReasonPhrase);
replacedert.Equal(2, response.Headers.Count()); // Date, Server
replacedert.True(response.Headers.Date.HasValue);
replacedert.Equal(1, response.Headers.Server.Count);
replacedert.Equal(0, (await response.Content.ReadAsByteArrayAsync()).Length);
}
}
19
View Source File : OwinHttpListenerResponseTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task OwinHttpListenerResponse_OnFirstWrite_OnSendingHeaders()
{
OwinHttpListener listener = CreateServer(
env =>
{
env["owin.ResponseStatusCode"] = 200;
env["owin.ResponseReasonPhrase"] = "Custom";
var responseStream = env.Get<Stream>("owin.ResponseBody");
var responseHeaders = env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders");
env.Get<Action<Action<object>, object>>("server.OnSendingHeaders")(state => responseHeaders["custom-header"] = new string[] { "customvalue" }, null);
responseHeaders["content-length"] = new string[] { "10" };
responseStream.Write(new byte[10], 0, 10);
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(HttpClientAddress);
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("Custom", response.ReasonPhrase);
replacedert.Equal(3, response.Headers.Count()); // Date, Server
replacedert.True(response.Headers.Date.HasValue);
replacedert.Equal(1, response.Headers.Server.Count);
replacedert.Equal("customvalue", response.Headers.GetValues("custom-header").First());
replacedert.Equal(10, (await response.Content.ReadAsByteArrayAsync()).Length);
}
}
19
View Source File : OwinWebSocketTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task EndToEnd_EchoData_Success()
{
ManualResetEvent echoComplete = new ManualResetEvent(false);
OwinHttpListener listener = CreateServer(env =>
{
var accept = (WebSocketAccept)env["websocket.Accept"];
replacedert.NotNull(accept);
accept(
null,
async wsEnv =>
{
var sendAsync = wsEnv.Get<WebSocketSendAsync>("websocket.SendAsync");
var receiveAsync = wsEnv.Get<WebSocketReceiveAsync>("websocket.ReceiveAsync");
var closeAsync = wsEnv.Get<WebSocketCloseAsync>("websocket.CloseAsync");
var buffer = new ArraySegment<byte>(new byte[100]);
Tuple<int, bool, int> serverReceive = await receiveAsync(buffer, CancellationToken.None);
await sendAsync(new ArraySegment<byte>(buffer.Array, 0, serverReceive.Item3),
serverReceive.Item1, serverReceive.Item2, CancellationToken.None);
replacedert.True(echoComplete.WaitOne(100), "Echo incomplete");
await closeAsync((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
});
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);
byte[] sendBody = Encoding.UTF8.GetBytes("Hello World");
await client.SendAsync(new ArraySegment<byte>(sendBody), WebSocketMessageType.Text, true, CancellationToken.None);
var receiveBody = new byte[100];
WebSocketReceiveResult readResult = await client.ReceiveAsync(new ArraySegment<byte>(receiveBody), CancellationToken.None);
echoComplete.Set();
replacedert.Equal(WebSocketMessageType.Text, readResult.MessageType);
replacedert.True(readResult.EndOfMessage);
replacedert.Equal(sendBody.Length, readResult.Count);
replacedert.Equal("Hello World", Encoding.UTF8.GetString(receiveBody, 0, readResult.Count));
}
}
}
19
View Source File : MapPathMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void ChainedRoutes_Success()
{
IAppBuilder builder = new AppBuilder();
builder.Map("/route1", map =>
{
map.Map((string)"/subroute1", UseSuccess);
map.Run(NotImplemented);
});
builder.Map("/route2/subroute2", UseSuccess);
var app = builder.Build<OwinMiddleware>();
IOwinContext context = CreateRequest(string.Empty, "/route1");
replacedert.Throws<AggregateException>(() => app.Invoke(context).Wait());
context = CreateRequest(string.Empty, "/route1/subroute1");
app.Invoke(context);
replacedert.Equal(200, context.Response.StatusCode);
replacedert.Equal(string.Empty, context.Request.PathBase.Value);
replacedert.Equal("/route1/subroute1", context.Request.Path.Value);
context = CreateRequest(string.Empty, "/route2");
app.Invoke(context);
replacedert.Equal(404, context.Response.StatusCode);
replacedert.Equal(string.Empty, context.Request.PathBase.Value);
replacedert.Equal("/route2", context.Request.Path.Value);
context = CreateRequest(string.Empty, "/route2/subroute2");
app.Invoke(context);
replacedert.Equal(200, context.Response.StatusCode);
replacedert.Equal(string.Empty, context.Request.PathBase.Value);
replacedert.Equal("/route2/subroute2", context.Request.Path.Value);
context = CreateRequest(string.Empty, "/route2/subroute2/subsub2");
app.Invoke(context);
replacedert.Equal(200, context.Response.StatusCode);
replacedert.Equal(string.Empty, context.Request.PathBase.Value);
replacedert.Equal("/route2/subroute2/subsub2", context.Request.Path.Value);
}
19
View Source File : MapPredicateMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void PredicateAsyncTrueAction_BranchTaken()
{
IOwinContext context = new OwinContext();
IAppBuilder builder = new AppBuilder();
builder.MapWhenAsync(TruePredicateAsync, UseSuccess);
var app = builder.Build<OwinMiddleware>();
app.Invoke(context).Wait();
replacedert.Equal(200, context.Response.StatusCode);
}
19
View Source File : MapPredicateMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void PredicateAsyncFalseAction_PreplacedThrough()
{
IOwinContext context = new OwinContext();
IAppBuilder builder = new AppBuilder();
builder.MapWhenAsync(FalsePredicateAsync, UseNotImplemented);
builder.Run(Success);
var app = builder.Build<OwinMiddleware>();
app.Invoke(context).Wait();
replacedert.Equal(200, context.Response.StatusCode);
}
19
View Source File : ResponseHeadersTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public void SetSpecialHeadersApp(IAppBuilder app)
{
app.UseErrorPage(new ErrorPageOptions() { ShowExceptionDetails = true });
app.Run(context =>
{
IHeaderDictionary responseHeaders = context.Response.Headers;
foreach (var header in _specialHeaders)
{
responseHeaders[header.Key] = header.Value;
replacedert.True(responseHeaders.ContainsKey(header.Key), header.Key);
replacedert.Equal(header.Value, responseHeaders[header.Key]);
}
replacedert.Equal(_specialHeaders.Length, responseHeaders.Count);
replacedert.Equal(_specialHeaders.Length, responseHeaders.Count());
// All show up in enumeration?
foreach (var specialPair in _specialHeaders)
{
replacedert.True(responseHeaders.Select(pair => pair.Key)
.Contains(specialPair.Key), specialPair.Key);
}
context.Response.StatusCode = ExpectedStatusCode;
// Some header issues are only visible after calling write and flush.
context.Response.Write("Hello World");
context.Response.Body.Flush();
return Task.FromResult(0);
});
}
19
View Source File : AspNetRequestHeadersTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void CreateEmptyRequestHeaders_Success()
{
var headers = new AspNetRequestHeaders(new FakeHttpRequest());
replacedert.Equal(0, headers.Count);
replacedert.Equal(0, headers.Count());
foreach (var header in headers)
{
// Should be empty
replacedert.True(false);
}
}
See More Examples