|
| 1 | +#if !NETCOREAPP2_1 && !NET48 |
| 2 | + |
| 3 | +using System.IO.Compression; |
| 4 | +using System.Net.Http.Headers; |
| 5 | +using Microsoft.AspNetCore.ResponseCompression; |
| 6 | + |
| 7 | +namespace Tests.Middleware; |
| 8 | + |
| 9 | +public class CompressionTests |
| 10 | +{ |
| 11 | + [Fact] |
| 12 | + public async Task ResponseCompression_ShouldCompressGraphQLResponse() |
| 13 | + { |
| 14 | + // Arrange |
| 15 | + var hostBuilder = new WebHostBuilder(); |
| 16 | + hostBuilder.ConfigureServices(services => |
| 17 | + { |
| 18 | + services.AddGraphQL(b => b |
| 19 | + .AddAutoSchema<Query>() |
| 20 | + .AddSystemTextJson()); |
| 21 | + services.AddRouting(); |
| 22 | + services.AddResponseCompression(options => |
| 23 | + { |
| 24 | + options.EnableForHttps = true; |
| 25 | + options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Append("application/graphql-response+json"); |
| 26 | + }); |
| 27 | + }); |
| 28 | + hostBuilder.Configure(app => |
| 29 | + { |
| 30 | + app.UseResponseCompression(); |
| 31 | + app.UseGraphQL(); |
| 32 | + }); |
| 33 | + |
| 34 | + using var server = new TestServer(hostBuilder); |
| 35 | + using var client = server.CreateClient(); |
| 36 | + |
| 37 | + // Act |
| 38 | + using var request = new HttpRequestMessage(HttpMethod.Post, "/graphql"); |
| 39 | + var content = new StringContent("{hello}"); |
| 40 | + content.Headers.ContentType = new MediaTypeHeaderValue("application/graphql"); |
| 41 | + request.Content = content; |
| 42 | + request.Headers.Add("Accept-Encoding", "gzip"); |
| 43 | + |
| 44 | + using var response = await client.SendAsync(request); |
| 45 | + |
| 46 | + // Assert |
| 47 | + response.EnsureSuccessStatusCode(); |
| 48 | + |
| 49 | + // Check if response is compressed |
| 50 | + response.Content.Headers.ContentEncoding.ShouldContain("gzip"); |
| 51 | + |
| 52 | + // Decompress and verify content |
| 53 | + using var responseStream = await response.Content.ReadAsStreamAsync(); |
| 54 | + using var decompressionStream = new GZipStream(responseStream, CompressionMode.Decompress); |
| 55 | + using var reader = new StreamReader(decompressionStream); |
| 56 | + var decompressedContent = await reader.ReadToEndAsync(); |
| 57 | + |
| 58 | + decompressedContent.ShouldBe("""{"data":{"hello":"world"}}"""); |
| 59 | + } |
| 60 | + |
| 61 | + public class Query |
| 62 | + { |
| 63 | + public static string Hello => "world"; |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +#endif |
0 commit comments