Skip to content

Commit

Permalink
fix(repo): ensure response type edge cases covereD
Browse files Browse the repository at this point in the history
  • Loading branch information
AJCJ1 committed Dec 24, 2024
1 parent 5e6735c commit ee10476
Show file tree
Hide file tree
Showing 5 changed files with 132 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,6 @@ public void AllOptions_ShouldSetCorrectly()
.Selector("#content")
.Clip("0,0,400,400")
.Gpu()
.ResponseType(ResponseType.Json)
.BlockAds()
.HideCookieBanners()
.ClickAccept()
Expand Down
94 changes: 89 additions & 5 deletions UrlboxSDK.MsTest/UrlboxTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
using System.Collections.Generic;
using UrlboxSDK.Exception;
using UrlboxSDK.MsTest.Utils;
using System.Reflection;

namespace UrlboxSDK.MsTest;

Expand Down Expand Up @@ -1017,16 +1016,38 @@ public async Task DownloadToFile_succeeds_overload()
string urlboxUrl = "https://api.urlbox.com/v1/MY_API_KEY/png?url=https%3A%2F%2Furlbox.com";

UrlboxOptions options = Urlbox.Options(url: "https://urlbox.com").Build();
string filename = "someFileName";

client.StubRequest(
HttpMethod.Get,
urlboxUrl,
(HttpStatusCode)200,
"somebuffer" // No response body or error headers
"somebuffer"
);

string result = await urlbox.DownloadToFile(options, filename, sign: false);
string result = await urlbox.DownloadToFile(options, "filename", sign: false);
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(String));
Assert.IsTrue(result.Length >= 0);
}

[TestMethod]
public async Task DownloadToFile_succeeds_overload_jsonResponseType()
{
// Should be this endpoint that is hit instead of with response_type=json
string urlboxUrl = "https://api.urlbox.com/v1/MY_API_KEY/png?response_type=base64&url=https%3A%2F%2Furlbox.com";

UrlboxOptions options = Urlbox.Options(url: "https://urlbox.com").Build();

options.ResponseType = ResponseType.Json;

client.StubRequest(
HttpMethod.Get,
urlboxUrl,
(HttpStatusCode)200,
"somebuffer"
);

string result = await urlbox.DownloadToFile(options, "somefile", sign: false);
Assert.IsNotNull(result);
Assert.IsInstanceOfType(result, typeof(String));
Assert.IsTrue(result.Length >= 0);
Expand All @@ -1041,7 +1062,7 @@ public async Task DownloadToFile_succeeds()
HttpMethod.Get,
urlboxUrl,
(HttpStatusCode)200,
"somebuffer" // No response body or error headers
"somebuffer"
);

string result = await urlbox.DownloadToFile(urlboxUrl, "result.png");
Expand Down Expand Up @@ -1116,6 +1137,32 @@ public async Task DownloadBase64_succeeds_overload()
Assert.AreEqual(expectedBase64, base64result, "Expected the base64 string to match the mocked content.");
}

[TestMethod]
public async Task DownloadBase64_succeeds_overload_jsonResponse()
{
// Should reconfigure options to base64 instead
string urlboxUrl = "https://api.urlbox.com/v1/MY_API_KEY/png?response_type=base64&url=https%3A%2F%2Furlbox.com";
string mockContent = "Test Image Content";

string encodedContent = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(mockContent));
string expectedBase64 = "text/plain; charset=utf-8;base64," + encodedContent;

UrlboxOptions options = Urlbox.Options(url: "https://urlbox.com").Build();

options.ResponseType = ResponseType.Json;

client.StubRequest(
HttpMethod.Get,
urlboxUrl,
HttpStatusCode.OK,
mockContent
);
string base64result = await urlbox.DownloadAsBase64(options, sign: false);

Assert.IsNotNull(base64result);
Assert.AreEqual(expectedBase64, base64result, "Expected the base64 string to match the mocked content.");
}

[TestMethod]
public async Task DownloadFail()
{
Expand All @@ -1141,6 +1188,43 @@ public async Task DownloadFail()
Assert.AreEqual("Request failed: " + expectedErrorMessage, exception.Message, "Expected the error message to match the mocked content.");
}

[TestMethod]
public async Task DownloadFail_wrongResponseType()
{
string urlboxUrl = "https://api.urlbox.com/v1/ca482d7e-9417-4569-90fe-80f7c5e1c781/59148a4e454a2c7051488defdb8b246bdea61ac/jpeg?url=bbc.co.uk&response_type=json";

string mockResponse = @"
{
""renderId"": ""abc123"",
""renderUrl"": ""https://example.com/screenshot.png"",
""size"": 123456
}";

client.StubRequest(
HttpMethod.Get,
urlboxUrl,
HttpStatusCode.OK,
mockResponse,
new Dictionary<string, string>
{
{ "Content-Type", "application/json" }
}
);

System.Exception exception = await Assert.ThrowsExceptionAsync<System.Exception>(
async () => await urlbox.DownloadAsBase64(urlboxUrl)
);

System.Exception exceptionFile = await Assert.ThrowsExceptionAsync<System.Exception>(
async () => await urlbox.DownloadToFile(urlboxUrl, "filename")
);

Assert.IsNotNull(exception);
Assert.IsNotNull(exceptionFile);
Assert.AreEqual("Please use Response Type of Binary when downloading a render link.", exception.Message, "Expected the error message to match the mocked content.");
Assert.AreEqual("Please use Response Type of Binary when downloading a render link.", exceptionFile.Message, "Expected the error message to match the mocked content.");
}

[TestMethod]
public async Task ExtractMetadata()
{
Expand Down
9 changes: 8 additions & 1 deletion UrlboxSDK.MsTest/Utils/MockHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,14 @@ public void StubRequest(HttpMethod method, string url, HttpStatusCode status, st
{
foreach (KeyValuePair<string, string> header in headers)
{
response.Headers.Add(header.Key, header.Value);
if (header.Key.Equals("Content-Type", System.StringComparison.OrdinalIgnoreCase))
{
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(header.Value);
}
else
{
response.Headers.Add(header.Key, header.Value);
}
}
}

Expand Down
6 changes: 0 additions & 6 deletions UrlboxSDK/Options/Builder/UrlboxOptionsBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,6 @@ public UrlboxOptionsBuilder Gpu()
return this;
}

public UrlboxOptionsBuilder ResponseType(ResponseType responseType)
{
_options.ResponseType = responseType;
return this;
}

public UrlboxOptionsBuilder BlockAds()
{
_options.BlockAds = true;
Expand Down
49 changes: 35 additions & 14 deletions UrlboxSDK/Urlbox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,13 @@ public async Task<string> ExtractMhtml(UrlboxOptions options)
/// <returns>A Base64-encoded string of the screenshot.</returns>
public async Task<string> DownloadAsBase64(UrlboxOptions options, bool sign = true)
{
if (
options.ResponseType != null &&
(options.ResponseType != ResponseType.Binary || options.ResponseType != ResponseType.Base64)
)
{
options.ResponseType = ResponseType.Base64;
}
string urlboxUrl = GenerateRenderLink(options, sign);
return await DownloadAsBase64(urlboxUrl);
}
Expand All @@ -355,6 +362,26 @@ static async Task<string> onSuccess(HttpResponseMessage result)
return await Download(urlboxUrl, onSuccess);
}

/// <summary>
/// Downloads a screenshot and saves it as a file.
/// </summary>
/// <param name="options">The options for the screenshot.</param>
/// <param name="filename">The file path where the screenshot will be saved.</param>
/// <param name="format">The image format (e.g., "png"). Default is "png".</param>
/// <returns>The contents of the downloaded file as a string.</returns>
public async Task<string> DownloadToFile(UrlboxOptions options, string filename, bool sign = true)
{
if (
options.ResponseType != null &&
(options.ResponseType != ResponseType.Binary || options.ResponseType != ResponseType.Base64)
)
{
options.ResponseType = ResponseType.Base64;
}
string urlboxUrl = GenerateRenderLink(options, sign);
return await DownloadToFile(urlboxUrl, filename);
}

/// <summary>
/// Downloads a screenshot from the given Urlbox URL and saves it as a file.
/// </summary>
Expand All @@ -376,19 +403,6 @@ async Task<string> onSuccess(HttpResponseMessage result)
return await Download(urlboxUrl, onSuccess);
}

/// <summary>
/// Downloads a screenshot and saves it as a file.
/// </summary>
/// <param name="options">The options for the screenshot.</param>
/// <param name="filename">The file path where the screenshot will be saved.</param>
/// <param name="format">The image format (e.g., "png"). Default is "png".</param>
/// <returns>The contents of the downloaded file as a string.</returns>
public async Task<string> DownloadToFile(UrlboxOptions options, string filename, bool sign = true)
{
string urlboxUrl = GenerateRenderLink(options, sign);
return await DownloadToFile(urlboxUrl, filename);
}

// ** URL Generation Methods **

/// <summary>
Expand Down Expand Up @@ -665,6 +679,7 @@ private async Task<AbstractUrlboxResponse> MakeUrlboxPostRequest(string endpoint
}
else
{

throw UrlboxException.FromResponse(responseData, deserializerOptions);
}
}
Expand All @@ -678,8 +693,14 @@ private async Task<AbstractUrlboxResponse> MakeUrlboxPostRequest(string endpoint
private async Task<string> Download(string urlboxUrl, Func<HttpResponseMessage, Task<string>> onSuccess)
{
HttpResponseMessage response = await httpClient.GetAsync(urlboxUrl).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
string? contentType = response.Content.Headers.ContentType?.ToString();

if (response.IsSuccessStatusCode && contentType != null)
{
if (!contentType.Contains("text/plain"))
{
throw new System.Exception("Please use Response Type of Binary when downloading a render link.");
}
return await onSuccess(response);
}
else
Expand Down

0 comments on commit ee10476

Please sign in to comment.