Skip to content

Instantly share code, notes, and snippets.

@leandromoh
Created September 23, 2021 19:19
Show Gist options
  • Save leandromoh/05af069bccadf6b2484a6f5a5c6a7160 to your computer and use it in GitHub Desktop.
Save leandromoh/05af069bccadf6b2484a6f5a5c6a7160 to your computer and use it in GitHub Desktop.
tested using .net core 3.1
// controller
public async Task DownloadFile([FromQuery] DownloadFileQueryRequest request, CancellationToken cancellationToken)
{
var responseObj = await process(request, cancellationToken);
HttpContext.Response.ContentType = MediaTypeNames.Application.Octet;
HttpContext.Response.StatusCode = StatusCodes.Status200OK;
HttpContext.Response.Headers["Access-Control-Expose-Headers"] = "Content-Disposition";
HttpContext.Response.Headers["Content-Disposition"] = new ContentDispositionHeaderValue("attachment")
{
FileName = $"Subject.{request.filterDate:yyyy-MM-dd}.GeneratedAt.{DateTime.UtcNow:yyyy-MM-ddTHH-mm-ss}.json.gz"
}
.ToString();
await using var gzipStream = new GZipStream(HttpContext.Response.Body, CompressionMode.Compress);
await JsonSerializer.SerializeAsync(gzipStream, responseObj, cancellationToken: cancellationToken);
}
// integration test
// Assert
...
var fileNamePattern = "^Subject." + $"{filterDate:yyyy-MM-dd}"
+ @".GeneratedAt.(?<GeneratedAt>\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}).json.gz$";
// Act
var (httpResponseMessage, contentStream) = await _setup.GetStream(url);
await using var contentStreamDecompressed = new GZipStream(contentStream, CompressionMode.Decompress);
var responseResult = await JsonSerializer.DeserializeAsync<ResponseObjType>(contentStreamDecompressed);
var responseFileName = httpResponseMessage.Content.Headers.ContentDisposition.FileName;
// Assert
httpResponseMessage.StatusCode.Should().Be(HttpStatusCode.OK);
responseResult.Should().BeEquivalentTo(responseObjExpected);
responseFileName.Should().MatchRegex(fileNamePattern);
var generatedAtText = new Regex(fileNamePattern)
.Match(responseFileName)
.Groups["GeneratedAt"]
.Value;
var generatedAt = DateTime.ParseExact(generatedAtText, "yyyy-MM-ddTHH-mm-ss", null);
generatedAt.Should().BeCloseTo(DateTime.UtcNow, precision: TimeSpan.FromMinutes(1));
// setup test
public async Task<(HttpResponseMessage, Stream)> GetStream(string url, string accept = null, IReadOnlyDictionary<string, string> headers = null)
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
if (accept != null)
request.Headers.Add("Accept", accept);
if (headers != null)
foreach (var (key, value) in headers)
request.Headers.Add(key, value);
var result = await _client.SendAsync(request);
return (result, await result.Content.ReadAsStreamAsync());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment