Skip to content

Commit

Permalink
Fixing more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeyzimarev committed Dec 6, 2021
1 parent 92b9e6f commit 710d55a
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 105 deletions.
78 changes: 29 additions & 49 deletions src/RestSharp/Http.Sync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,11 @@
using RestSharp.Authenticators.OAuth.Extensions;
using RestSharp.Extensions;

namespace RestSharp
{
namespace RestSharp {
/// <summary>
/// HttpWebRequest wrapper (sync methods)
/// </summary>
public partial class Http
{
public partial class Http {
/// <summary>
/// Execute a POST request
/// </summary>
Expand Down Expand Up @@ -81,75 +79,66 @@ public partial class Http

HttpResponse GetStyleMethodInternal(string method)
=> ExecuteRequest(
method, r =>
{
method,
r => {
if (!HasBody) return;
if (!CanGetWithBody())
throw new NotSupportedException($"Http verb {method} does not support body");
throw new NotSupportedException($"HTTP verb {method} does not support body");
r.ContentType = RequestContentType;
WriteRequestBody(r);
bool CanGetWithBody() => method == "DELETE" || method == "OPTIONS";
bool CanGetWithBody() => method is "DELETE" or "OPTIONS";
}
);

HttpResponse PostPutInternal(string method)
=> ExecuteRequest(
method, r =>
{
method,
r => {
PreparePostBody(r);
WriteRequestBody(r);
}
);

HttpResponse ExecuteRequest(string httpMethod, Action<HttpWebRequest> prepareRequest)
{
HttpResponse ExecuteRequest(string httpMethod, Action<HttpWebRequest> prepareRequest) {
var webRequest = ConfigureWebRequest(httpMethod, Url);

prepareRequest(webRequest);

try
{
try {
using var webResponse = GetRawResponse(webRequest);

return ExtractResponseData(webResponse);
}
catch (Exception ex)
{
catch (Exception ex) {
if (ThrowOnAnyError)
throw;

return ExtractErrorResponse(ex);
}

static HttpResponse ExtractErrorResponse(Exception ex)
{
var response = new HttpResponse {ErrorMessage = ex.Message};
static HttpResponse ExtractErrorResponse(Exception ex) {
var response = new HttpResponse { ErrorMessage = ex.Message };

if (ex is WebException webException && webException.Status == WebExceptionStatus.Timeout)
{
if (ex is WebException webException && webException.Status == WebExceptionStatus.Timeout) {
response.ResponseStatus = ResponseStatus.TimedOut;
response.ErrorException = webException;
}
else
{
else {
response.ErrorException = ex;
response.ResponseStatus = ResponseStatus.Error;
}

return response;
}

static HttpWebResponse GetRawResponse(WebRequest request)
{
try
{
return (HttpWebResponse) request.GetResponse();
static HttpWebResponse GetRawResponse(WebRequest request) {
try {
return (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
catch (WebException ex) {
// Check to see if this is an HTTP error or a transport error.
// In cases where an HTTP error occurs ( status code >= 400 )
// return the underlying HTTP response, otherwise assume a
Expand All @@ -164,8 +153,7 @@ static HttpWebResponse GetRawResponse(WebRequest request)
}
}

void WriteRequestBody(WebRequest webRequest)
{
void WriteRequestBody(WebRequest webRequest) {
if (HasBody || HasFiles || AlwaysMultipartFormData)
webRequest.ContentLength = CalculateContentLength();

Expand All @@ -180,8 +168,7 @@ void WriteRequestBody(WebRequest webRequest)
}

[Obsolete("Use the WebRequestConfigurator delegate instead of overriding this method")]
protected virtual HttpWebRequest ConfigureWebRequest(string method, Uri url)
{
protected virtual HttpWebRequest ConfigureWebRequest(string method, Uri url) {
var webRequest = CreateWebRequest(url) ?? CreateRequest(url);

webRequest.UseDefaultCredentials = UseDefaultCredentials;
Expand All @@ -192,12 +179,10 @@ protected virtual HttpWebRequest ConfigureWebRequest(string method, Uri url)
#if NETSTANDARD2_0
webRequest.Proxy = null;
#endif
try
{
try {
webRequest.ServicePoint.Expect100Continue = false;
}
catch (PlatformNotSupportedException)
{
catch (PlatformNotSupportedException) {
// Avoid to crash in UWP apps
}

Expand Down Expand Up @@ -253,25 +238,20 @@ protected virtual HttpWebRequest ConfigureWebRequest(string method, Uri url)

// handle restricted headers the .NET way - thanks @dimebrain!
// http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers.aspx
void AppendHeaders()
{
foreach (var header in Headers)
{
void AppendHeaders() {
foreach (var header in Headers) {
if (_restrictedHeaderActions.TryGetValue(header.Name, out var restrictedHeaderAction))
restrictedHeaderAction.Invoke(webRequest, header.Value);
else
webRequest.Headers.Add(header.Name, header.Value);
}
}

void AppendCookies()
{
void AppendCookies() {
webRequest.CookieContainer = CookieContainer ?? new CookieContainer();

foreach (var httpCookie in Cookies)
{
var cookie = new Cookie
{
foreach (var httpCookie in Cookies) {
var cookie = new Cookie {
Name = httpCookie.Name,
Value = httpCookie.Value,
Domain = webRequest.RequestUri.Host
Expand Down
2 changes: 1 addition & 1 deletion src/RestSharp/Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ public partial class Http : IHttp {
public IList<HttpCookie> Cookies { get; internal set; } = null!;

/// <inheritdoc />
public string RequestBody { get; set; } = null!;
public string? RequestBody { get; set; }

/// <inheritdoc />
public string RequestContentType { get; set; } = null!;
Expand Down
2 changes: 1 addition & 1 deletion src/RestSharp/IHttp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public interface IHttp
/// <summary>
/// Request body to be sent with request
/// </summary>
string RequestBody { get; set; }
string? RequestBody { get; set; }

/// <summary>
/// Content type of the request body.
Expand Down
55 changes: 13 additions & 42 deletions test/RestSharp.IntegrationTests/AsyncRequestBodyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,44 +24,18 @@ public class AsyncRequestBodyTests : IClassFixture<RequestBodyFixture> {
Assert.Equal(bodyData, RequestBodyCapturer.CapturedEntityBody);
}

class RequestBodyCapturer {
public const string RESOURCE = "Capture";

public static string CapturedContentType { get; set; }

public static bool CapturedHasEntityBody { get; set; }

public static string CapturedEntityBody { get; set; }

public static void Capture(HttpListenerContext context) {
var request = context.Request;

CapturedContentType = request.ContentType;
CapturedHasEntityBody = request.HasEntityBody;
CapturedEntityBody = StreamToString(request.InputStream);
}

static string StreamToString(Stream stream) {
var streamReader = new StreamReader(stream);
return streamReader.ReadToEnd();
}
}

[Fact]
public void Can_Be_Added_To_COPY_Request() {
public async Task Can_Be_Added_To_COPY_Request() {
const Method httpMethod = Method.COPY;

var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);

const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";

request.AddParameter(contentType, bodyData, ParameterType.RequestBody);

var resetEvent = new ManualResetEvent(false);

_client.ExecuteAsync(request, response => resetEvent.Set());
resetEvent.WaitOne();
await _client.ExecuteAsync(request);

AssertHasRequestBody(contentType, bodyData);
}
Expand All @@ -70,7 +44,7 @@ class RequestBodyCapturer {
public void Can_Be_Added_To_DELETE_Request() {
const Method httpMethod = Method.DELETE;

var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);

const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";
Expand All @@ -89,7 +63,7 @@ class RequestBodyCapturer {
public void Can_Be_Added_To_OPTIONS_Request() {
const Method httpMethod = Method.OPTIONS;

var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);

const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";
Expand All @@ -108,7 +82,7 @@ class RequestBodyCapturer {
public void Can_Be_Added_To_PATCH_Request() {
const Method httpMethod = Method.PATCH;

var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);

const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";
Expand All @@ -127,7 +101,7 @@ class RequestBodyCapturer {
public void Can_Be_Added_To_POST_Request() {
const Method httpMethod = Method.POST;

var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);

const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";
Expand All @@ -146,7 +120,7 @@ class RequestBodyCapturer {
public void Can_Be_Added_To_PUT_Request() {
const Method httpMethod = Method.PUT;

var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);

const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";
Expand All @@ -165,7 +139,7 @@ class RequestBodyCapturer {
public void Can_Have_No_Body_Added_To_POST_Request() {
const Method httpMethod = Method.POST;

var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);
var resetEvent = new ManualResetEvent(false);

_client.ExecuteAsync(request, response => resetEvent.Set());
Expand All @@ -175,20 +149,17 @@ class RequestBodyCapturer {
}

[Fact]
public void Can_Not_Be_Added_To_GET_Request() {
public async Task Can_Be_Added_To_GET_Request() {
const Method httpMethod = Method.GET;

var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);

const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";

request.AddParameter(contentType, bodyData, ParameterType.RequestBody);

var resetEvent = new ManualResetEvent(false);

_client.ExecuteAsync(request, response => resetEvent.Set());
resetEvent.WaitOne();
await _client.ExecuteAsync(request);

AssertHasNoRequestBody();
}
Expand All @@ -197,7 +168,7 @@ class RequestBodyCapturer {
public void Can_Not_Be_Added_To_HEAD_Request() {
const Method httpMethod = Method.HEAD;

var request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod);
var request = new RestRequest(RequestBodyCapturer.Resource, httpMethod);

const string contentType = "text/plain";
const string bodyData = "abc123 foo bar baz BING!";
Expand Down
12 changes: 6 additions & 6 deletions test/RestSharp.IntegrationTests/RequestBodyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,14 @@ public class RequestBodyTests : IClassFixture<RequestBodyFixture> {
}

static void AssertHasNoRequestBody() {
Assert.Null(RequestBodyCapturer.CapturedContentType);
Assert.False(RequestBodyCapturer.CapturedHasEntityBody);
Assert.Equal(string.Empty, RequestBodyCapturer.CapturedEntityBody);
RequestBodyCapturer.CapturedContentType.Should().BeNull();
RequestBodyCapturer.CapturedHasEntityBody.Should().BeFalse();
RequestBodyCapturer.CapturedEntityBody.Should().BeNullOrEmpty();
}

static void AssertHasRequestBody(string contentType, string bodyData) {
Assert.Equal(contentType, RequestBodyCapturer.CapturedContentType);
Assert.True(RequestBodyCapturer.CapturedHasEntityBody);
Assert.Equal(bodyData, RequestBodyCapturer.CapturedEntityBody);
RequestBodyCapturer.CapturedContentType.Should().Be(contentType);
RequestBodyCapturer.CapturedHasEntityBody.Should().BeTrue();
RequestBodyCapturer.CapturedEntityBody.Should().Be(bodyData);
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net452;net5</TargetFrameworks>
<TargetFrameworks>net452;net6.0</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net452|AnyCPU'">
<WarningLevel>0</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)'=='net5'">
<PropertyGroup Condition="'$(TargetFramework)'=='net6.0'">
<DefineConstants>NETCORE</DefineConstants>
</PropertyGroup>
<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RestSharp\RestSharp.csproj"/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net461;net5</TargetFrameworks>
<TargetFrameworks>net461;net6.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RestSharp.Serializers.NewtonsoftJson\RestSharp.Serializers.NewtonsoftJson.csproj"/>
Expand Down
2 changes: 1 addition & 1 deletion test/RestSharp.Tests.Shared/RestSharp.Tests.Shared.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net452;net5</TargetFrameworks>
<TargetFrameworks>net452;net6.0</TargetFrameworks>
<IsTestProject>false</IsTestProject>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net452'">
Expand Down
2 changes: 1 addition & 1 deletion test/RestSharp.Tests/RestSharp.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net452;net5</TargetFrameworks>
<TargetFrameworks>net452;net6.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Moq" Version="4.16.1" />
Expand Down

0 comments on commit 710d55a

Please sign in to comment.