Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat multipart file upload support #447

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions PactNet.sln
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Consumer.Tests", "samples\Messaging\Consumer.Tests\Consumer.Tests.csproj", "{AED4E706-6E99-47B8-BE17-A3503275DB3E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ReadMe", "ReadMe", "{87FC5A4B-1977-4FBA-AA71-63F48B28C3B0}"
ProjectSection(SolutionItems) = preProject
tests\PactNet.Tests\data\test_file.jpeg = tests\PactNet.Tests\data\test_file.jpeg
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Readme.Consumer", "samples\ReadMe\Consumer\Readme.Consumer.csproj", "{B7363201-F52A-49C4-A299-C9B459827C04}"
EndProject
Expand Down
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,37 @@ For writing messaging pacts instead of requests/response pacts, see the [messagi

![----------](https://raw.githubusercontent.com/pactumjs/pactum/master/assets/rainbow.png)

### Multipart/form-data Content-Type Support

Pact-Net supports API Requests where a single file is uploaded using the multipart/form-data content-type using the `WithFileUpload` method.

```csharp
this.pact
.UponReceiving($"a request to upload a file")
.WithRequest(HttpMethod.Post, $"/events/upload-file")
.WithFileUpload(contentType, fileInfo, "fileName")
.WillRespond()
.WithStatus(201);
```
### Params

contentType : The content-type of the file being uploaded, ie `image/jpeg`. Separate from the
content-type header of the request.

fileInfo : The FileInfo of the file being uploaded.

fileName : A string representing the name of the file being uploaded.

### Limitations

- The content-type of the file being uploaded will be verified when running the pact tests in a Unix environment such as your CI/CD environment.
- This feature is unsupported in Windows so it is recommended to ignore any tests that use WithFileUpload when running tests in a Windows environment.
- This is because the Pact core relies on the [Shared MIME-info Database](https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html), which is supported on Unix, can be installed in OSX and is not supported on Windows.
- Multipart/form-data payloads that contain more than one part are not supported currently. The recommended work around is to create a string payload with the expected parts and add this to the pact file using the .WithBody() method, which allows an arbitrary string to be set as the body.

![----------](https://raw.githubusercontent.com/pactumjs/pactum/master/assets/rainbow.png)


## Compatibility

### Operating System
Expand Down
6 changes: 6 additions & 0 deletions samples/EventApi/Consumer.Tests/Consumer.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Xunit.SkippableFact" Version="1.4.13" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\src\PactNet\PactNet.csproj" />
Expand All @@ -23,4 +24,9 @@
<ItemGroup>
<Folder Include="pacts\" />
</ItemGroup>
<ItemGroup>
<None Update="test_file.jpeg">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
74 changes: 74 additions & 0 deletions samples/EventApi/Consumer.Tests/EventsApiConsumerTestsV3.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Consumer.Models;
using FluentAssertions;
using FluentAssertions.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using PactNet;
using PactNet.Matchers;
using Xunit;
using Xunit.Abstractions;

namespace Consumer.Tests
{
public class EventsApiConsumerTestsV3
{
private const string Token = "SomeValidAuthToken";

private readonly IPactBuilderV3 pact;

public EventsApiConsumerTestsV3(ITestOutputHelper output)
{
var config = new PactConfig
{
PactDir = "../../../pacts/",
Outputters = new[]
{
new XUnitOutput(output)
},
DefaultJsonSettings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
};

var pact = Pact.V3("Event API ConsumerV3", "Event API", config);
this.pact = pact.WithHttpInteractions();
}

[SkippableFact]

// Feature not supported on Windows
public async Task UploadImage_WhenTheFileExists_Returns201()
{
Skip.If(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));

string contentType = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "application/octet-stream" : "image/jpeg";

var file = new FileInfo("test_file.jpeg");


this.pact
.UponReceiving($"a request to upload a file")
.WithRequest(HttpMethod.Post, $"/events/upload-file")
.WithFileUpload(contentType, file, "file")
.WillRespond()
.WithStatus(201);

await this.pact.VerifyAsync(async ctx =>
{
var client = new EventsApiClient(ctx.MockServerUri, Token);

var result = await client.UploadFile(file);

result.Should().BeEquivalentTo(HttpStatusCode.Created);
});
}
}
}
Binary file added samples/EventApi/Consumer.Tests/test_file.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
41 changes: 41 additions & 0 deletions samples/EventApi/Consumer/EventsApiClient.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Consumer.Models;
Expand Down Expand Up @@ -216,7 +218,46 @@ public async Task CreateEvent(Guid eventId, string eventType = "DetailsView")
Dispose(request, response);
}
}
public async Task<HttpStatusCode> UploadFile(FileInfo file)
{

using var fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);

var request = new MultipartFormDataContent();
request.Headers.ContentType.MediaType = "multipart/form-data";

var fileContent = new StreamContent(fileStream);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");

var fileName = file.Name;
var fileNameBytes = Encoding.UTF8.GetBytes(fileName);
var encodedFileName = Convert.ToBase64String(fileNameBytes);
request.Add(fileContent, "file", fileName);
request.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = fileName,
FileNameStar = $"utf-8''{encodedFileName}"
};

HttpResponseMessage response = await this.httpClient.PostAsync("/events/upload-file", request);
try
{
var statusCode = response.StatusCode;
if (statusCode == HttpStatusCode.Created)
{
return statusCode;
}
throw new HttpRequestException(
string.Format("The Events API request for POST /upload-file failed. Response Status: {0}, Response Body: {1}",
response.StatusCode,
await response.Content.ReadAsStringAsync()));
}
finally
{
Dispose(request, response);
}
}
private static async Task RaiseResponseError(HttpRequestMessage failedRequest, HttpResponseMessage failedResponse)
{
throw new HttpRequestException(
Expand Down
33 changes: 33 additions & 0 deletions samples/EventApi/Provider.Tests/EventAPITests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using PactNet;
using PactNet.Infrastructure.Outputters;
using PactNet.Verifier;
Expand Down Expand Up @@ -50,5 +51,37 @@ public void EnsureEventApiHonoursPactWithConsumer()
.WithSslVerificationDisabled()
.Verify();
}
[SkippableFact]
public void EnsureEventApiHonoursPactWithConsumerV3()
{
// Feature not supported on Windows
Skip.If(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));

var config = new PactVerifierConfig
{
LogLevel = PactLogLevel.Information,
Outputters = new List<IOutput>
{
new XUnitOutput(this.output)
}
};

string pactPath = Path.Combine("..",
"..",
"..",
"..",
"Consumer.Tests",
"pacts",
"Event API ConsumerV3-Event API.json");

IPactVerifier verifier = new PactVerifier(config);
verifier
.ServiceProvider("Event API", this.fixture.ServerUri)
.WithFileSource(new FileInfo(pactPath))
.WithProviderStateUrl(new Uri(this.fixture.ServerUri, "/provider-states"))
.WithRequestTimeout(TimeSpan.FromSeconds(2))
.WithSslVerificationDisabled()
.Verify();
}
}
}
1 change: 1 addition & 0 deletions samples/EventApi/Provider.Tests/Provider.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Xunit.SkippableFact" Version="1.4.13" />
</ItemGroup>

<ItemGroup>
Expand Down
18 changes: 18 additions & 0 deletions samples/EventApi/Provider/Controllers/EventsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Provider.Api.Web.Models;

Expand Down Expand Up @@ -41,6 +42,23 @@ public IActionResult Post(Event @event)
: this.StatusCode((int)HttpStatusCode.Created);
}

[HttpPost]
[Route("upload-file")]
[Consumes("multipart/form-data")]
public IActionResult FileUpload()
{
var singleFile = Request.Form.Files.SingleOrDefault(f => f.Name == "file");
if (singleFile == null || Request.Form.Files.Count != 1)
{
return BadRequest("Request must contain a single file with a parameter named 'file'");
}
if (singleFile.ContentType != "image/jpeg")
{
return BadRequest("File content-type must be image/jpeg");
}
return StatusCode(201);
}

private IEnumerable<Event> GetAllEventsFromRepo()
{
return new List<Event>
Expand Down
10 changes: 10 additions & 0 deletions src/PactNet.Abstractions/IRequestBuilder.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using Newtonsoft.Json;
using PactNet.Matchers;
Expand Down Expand Up @@ -206,6 +207,15 @@ public interface IRequestBuilderV3
/// <returns>Fluent builder</returns>
IRequestBuilderV3 WithBody(string body, string contentType);

/// <summary>
/// Set a body which is multipart/form-data but contains only one part, which is a file upload
/// </summary>
/// <param name="contentType">The content type of the file being uploaded</param>
/// <param name="fileInfo">Path to the file being uploaded</param>
/// <param name="partName">The name of the file being uploaded as a part</param>
/// <returns>Fluent builder</returns>
IRequestBuilderV3 WithFileUpload(string contentType, FileInfo fileInfo, string partName);

// TODO: Support binary and multi-part body

/// <summary>
Expand Down
9 changes: 9 additions & 0 deletions src/PactNet/Drivers/HttpInteractionDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,5 +97,14 @@ public void WithRequestBody(string contentType, string body)
/// <param name="body">Serialised body</param>
public void WithResponseBody(string contentType, string body)
=> NativeInterop.WithBody(this.interaction, InteractionPart.Response, contentType, body).CheckInteropSuccess();

/// <summary>
/// Set the request body to multipart/form-data for file upload
/// </summary>
/// <param name="contentType">Content type override</param>
/// <param name="filePath">path to file being uploaded</param>
/// <param name="partName">the name of the mime part being uploaded</param>
public void WithFileUpload(string contentType, string filePath, string partName)
=> NativeInterop.WithFileUpload(this.interaction, InteractionPart.Request, contentType, filePath, partName).CheckInteropSuccess();
}
}
8 changes: 8 additions & 0 deletions src/PactNet/Drivers/IHttpInteractionDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,13 @@ internal interface IHttpInteractionDriver : IProviderStateDriver
/// <param name="contentType">Context type</param>
/// <param name="body">Serialised body</param>
void WithResponseBody(string contentType, string body);

/// <summary>
/// Set the response body for a single file to be uploaded as a multipart/form-data content type
/// </summary>
/// <param name="filePath">path to file being uploaded</param>
/// <param name="contentType">Content type override</param>
/// <param name="mimePartName">the name of the mime part being uploaded</param>
void WithFileUpload(string filePath, string contentType, string mimePartName);
}
}
18 changes: 17 additions & 1 deletion src/PactNet/Drivers/InteropActionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using PactNet.Exceptions;
using System.Runtime.InteropServices;
using PactNet.Exceptions;
using PactNet.Interop;

namespace PactNet.Drivers
{
Expand All @@ -19,5 +21,19 @@ public static void CheckInteropSuccess(this bool success)
throw new PactFailureException("Unable to perform the given action. The interop call indicated failure");
}
}

/// <summary>
/// Check the result of an interop action when the response is a StringResult
/// </summary>
/// <param name="success">The result of the action</param>
/// <exception cref="PactFailureException">Action failed</exception>
public static void CheckInteropSuccess(this StringResult success)
Inksprout marked this conversation as resolved.
Show resolved Hide resolved
{
if (success.tag != StringResult.Tag.StringResult_Ok)
{
string errorMsg = Marshal.PtrToStringAnsi(success.failed.errorPointer);
throw new PactFailureException($"Unable to perform the given action. The interop call returned failure: {errorMsg}");
}
}
}
}
3 changes: 3 additions & 0 deletions src/PactNet/Interop/NativeInterop.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,9 @@ internal static class NativeInterop
[DllImport(DllName, EntryPoint = "pactffi_with_body")]
public static extern bool WithBody(InteractionHandle interaction, InteractionPart part, string contentType, string body);

[DllImport(DllName, EntryPoint = "pactffi_with_multipart_file")]
public static extern StringResult WithFileUpload(InteractionHandle interaction, InteractionPart part, string contentType, string filePath, string partName);

[DllImport(DllName, EntryPoint = "pactffi_free_string")]
public static extern void FreeString(IntPtr s);

Expand Down
Loading