Skip to content
This repository has been archived by the owner on Dec 19, 2018. It is now read-only.

Commit

Permalink
#1256 Check HasStarted for StatusCode and ReasonPhrase
Browse files Browse the repository at this point in the history
  • Loading branch information
Tratcher committed Nov 9, 2017
1 parent 64596d5 commit 05fd382
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
34 changes: 32 additions & 2 deletions src/Microsoft.AspNetCore.TestHost/ResponseFeature.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ internal class ResponseFeature : IHttpResponseFeature
private Func<Task> _responseStartingAsync = () => Task.FromResult(true);
private Func<Task> _responseCompletedAsync = () => Task.FromResult(true);
private HeaderDictionary _headers = new HeaderDictionary();
private int _statusCode;
private string _reasonPhrase;

public ResponseFeature()
{
Expand All @@ -25,9 +27,37 @@ public ResponseFeature()
StatusCode = 200;
}

public int StatusCode { get; set; }
public int StatusCode
{
get => _statusCode;
set
{
if (HasStarted)
{
throw new InvalidOperationException("The status code cannot be set, the response has already started.");
}
if (value < 100)
{
throw new ArgumentOutOfRangeException(nameof(value), value, "The status code cannot be set to a value less than 100");
}

_statusCode = value;
}
}

public string ReasonPhrase
{
get => _reasonPhrase;
set
{
if (HasStarted)
{
throw new InvalidOperationException("The reason phrase cannot be set, the response has already started.");
}

public string ReasonPhrase { get; set; }
_reasonPhrase = value;
}
}

public IHeaderDictionary Headers { get; set; }

Expand Down
23 changes: 23 additions & 0 deletions test/Microsoft.AspNetCore.TestHost.Tests/ResponseFeatureTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,28 @@ public void OnStarting_ThrowsWhenHasStarted()
}, state: "string");
});
}

[Fact]
public void StatusCode_ThrowsWhenHasStarted()
{
var responseInformation = new ResponseFeature();
responseInformation.HasStarted = true;

Assert.Throws<InvalidOperationException>(() => responseInformation.StatusCode = 400);
Assert.Throws<InvalidOperationException>(() => responseInformation.ReasonPhrase = "Hello World");
}

[Fact]
public void StatusCode_MustBeGreaterThan99()
{
var responseInformation = new ResponseFeature();

Assert.Throws<ArgumentOutOfRangeException>(() => responseInformation.StatusCode = 99);
Assert.Throws<ArgumentOutOfRangeException>(() => responseInformation.StatusCode = 0);
Assert.Throws<ArgumentOutOfRangeException>(() => responseInformation.StatusCode = -200);
responseInformation.StatusCode = 100;
responseInformation.StatusCode = 200;
responseInformation.StatusCode = 1000;
}
}
}

0 comments on commit 05fd382

Please sign in to comment.