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

Split Cloudinary.cs into separate APIs #290

Open
wants to merge 4 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
37 changes: 33 additions & 4 deletions CloudinaryDotNet.IntegrationTests/IntegrationTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ public partial class IntegrationTestBase

protected Account m_account;
protected Cloudinary m_cloudinary;
internal CloudinaryUpload m_cloudinaryUpload;
internal CloudinaryAdmin m_cloudinaryAdmin;

protected Dictionary<StorageType, List<string>> m_publicIdsToClear;
protected List<object> m_transformationsToClear;
Expand All @@ -108,6 +110,8 @@ public virtual void Initialize()

m_account = GetAccountInstance();
m_cloudinary = GetCloudinaryInstance(m_account);
m_cloudinaryAdmin = GetCloudinaryAdminInstance(m_account);
m_cloudinaryUpload = GetCloudinaryUploadInstance(m_account);

SaveTestResources(assembly);

Expand Down Expand Up @@ -358,17 +362,42 @@ private Account GetAccountInstance()
return account;
}

/// <summary>
/// A convenient method for initialization of new Cloudinary Admin instance with necessary checks
/// </summary>
/// <param name="account">Instance of Account</param>
/// <returns>New Cloudinary Admin instance</returns>
internal CloudinaryAdmin GetCloudinaryAdminInstance(Account account)
{
var cloudinaryAdmin = new CloudinaryAdmin(account);
if(!string.IsNullOrWhiteSpace(m_apiBaseAddress))
cloudinaryAdmin.Api.ApiBaseAddress = m_apiBaseAddress;

return cloudinaryAdmin;
}

/// <summary>
/// A convenient method for initialization of new Cloudinary Upload instance with necessary checks
/// </summary>
/// <param name="account">Instance of Account</param>
/// <returns>New Cloudinary Upload instance</returns>
internal CloudinaryUpload GetCloudinaryUploadInstance(Account account)
{
var cloudinaryUpload = new CloudinaryUpload(account);
if(!string.IsNullOrWhiteSpace(m_apiBaseAddress))
cloudinaryUpload.Api.ApiBaseAddress = m_apiBaseAddress;

return cloudinaryUpload;
}

/// <summary>
/// A convenient method for initialization of new Cloudinary instance with necessary checks
/// </summary>
/// <param name="account">Instance of Account</param>
/// <returns>New Cloudinary instance</returns>
protected Cloudinary GetCloudinaryInstance(Account account)
{
Cloudinary cloudinary = new Cloudinary(account);
if(!string.IsNullOrWhiteSpace(m_apiBaseAddress))
cloudinary.Api.ApiBaseAddress = m_apiBaseAddress;

var cloudinary = new Cloudinary(account);
return cloudinary;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public void TestDownloadMulti()
var paramsFromUrl = new MultiParams(new List<string> {url1, url2});
var urlFromUrls = m_cloudinary.DownloadMulti(paramsFromUrl);

var expectedUrl = "https://api.cloudinary.com/v1_1/" + m_cloudinary.Api.Account.Cloud + "/image/multi";
var expectedUrl = "https://api.cloudinary.com/v1_1/" + m_cloudinaryUpload.Api.Account.Cloud + "/image/multi";
var uriFromTag = new Uri(urlFromTag);
var uriFromUrls = new Uri(urlFromUrls);
Assert.True(uriFromTag.ToString().StartsWith(expectedUrl));
Expand All @@ -122,10 +122,10 @@ public void TestDownloadMulti()
private void AssertMultiResult(MultiResult result, string transformation, string fileFormat)
{
if (!string.IsNullOrEmpty(transformation))
Assert.True(result.Url.AbsoluteUri.Contains(transformation));
Assert.True(result.Url?.AbsoluteUri.Contains(transformation), result.Error?.Message);

if (!string.IsNullOrEmpty(fileFormat))
Assert.True(result.Url.AbsoluteUri.EndsWith($".{fileFormat}"));
Assert.True(result.Url?.AbsoluteUri.EndsWith($".{fileFormat}"), result.Error?.Message);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public void TestDownloadSprite()
var paramsFromUrl = new SpriteParams(new List<string> { url1, url2 });
var urlFromUrls = m_cloudinary.DownloadSprite(paramsFromUrl);

var expectedUrl = "https://api.cloudinary.com/v1_1/" + m_cloudinary.Api.Account.Cloud + "/image/sprite";
var expectedUrl = "https://api.cloudinary.com/v1_1/" + m_cloudinaryUpload.Api.Account.Cloud + "/image/sprite";
var uriFromTag = new Uri(urlFromTag);
var uriFromUrls = new Uri(urlFromUrls);
Assert.True(uriFromTag.ToString().StartsWith(expectedUrl));
Expand Down
14 changes: 7 additions & 7 deletions CloudinaryDotNet.IntegrationTests/UploadApi/UploadMethodsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,27 +169,27 @@ public void TestUploadLocalImageTimeout()
};

// Save original values
var origAddr = m_cloudinary.Api.ApiBaseAddress;
var origTimeout = m_cloudinary.Api.Timeout;
var origAddr = m_cloudinaryUpload.Api.ApiBaseAddress;
var origTimeout = m_cloudinaryUpload.Api.Timeout;

var stopWatch = new Stopwatch();

try
{
m_cloudinary.Api.ApiBaseAddress = "https://10.255.255.1";
m_cloudinary.Api.Timeout = TIMEOUT;
m_cloudinaryUpload.Api.ApiBaseAddress = "https://10.255.255.1";
m_cloudinaryUpload.Api.Timeout = TIMEOUT;

stopWatch.Start();
m_cloudinary.Upload(uploadParams);
m_cloudinaryUpload.Upload(uploadParams);
}
catch (Exception)
{
stopWatch.Stop();
}
finally
{
m_cloudinary.Api.ApiBaseAddress = origAddr;
m_cloudinary.Api.Timeout = origTimeout;
m_cloudinaryUpload.Api.ApiBaseAddress = origAddr;
m_cloudinaryUpload.Api.Timeout = origTimeout;
stopWatch.Stop();
}

Expand Down
2 changes: 1 addition & 1 deletion CloudinaryDotNet.Tests/Asset/UrlBuilderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ public void TestSecureDistributionFromUrl()
{
// should take secure distribution from url if secure=TRUE

var cloudinary = new CloudinaryDotNet.Cloudinary("cloudinary://a:b@test123/config.secure.distribution.com");
var cloudinary = new CloudinaryDotNet.CloudinaryUpload("cloudinary://a:b@test123/config.secure.distribution.com");
string url = cloudinary.Api.UrlImgUp.BuildUrl("test");

Assert.AreEqual("https://config.secure.distribution.com/image/upload/test", url);
Expand Down
6 changes: 3 additions & 3 deletions CloudinaryDotNet.Tests/MetaDataTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ public class MetaDataTest
private const string externalIdEnum = "metadata_external_id_enum";
private const string externalIdDelete = "metadata_deletion";
private const string datasourceEntryExternalId = "metadata_datasource_entry_external_id";
private MockedCloudinary mockedCloudinary;
private MockedCloudinaryAdmin mockedCloudinary;

[SetUp]
public void SetUp()
{
mockedCloudinary = new MockedCloudinary();
mockedCloudinary = new MockedCloudinaryAdmin();
}

/// <summary>
Expand Down Expand Up @@ -132,7 +132,7 @@ public void TestDeleteMetadataField()
/// <param name="type"> The type of value that can be assigned to the metadata field.</param>
/// <param name="externalId">A unique identification string for the metadata field.</param>
/// <param name="dataSourceEntry">(Optional) Data source for a given field.</param>
private static void AssertEncodedRequestFields(MockedCloudinary mockedCloudinary, string type, string externalId,
private static void AssertEncodedRequestFields(MockedCloudinaryAdmin mockedCloudinary, string type, string externalId,
EntryParams dataSourceEntry = null)
{
var requestJson = JToken.Parse(mockedCloudinary.HttpRequestContent);
Expand Down
63 changes: 45 additions & 18 deletions CloudinaryDotNet.Tests/MockedCloudinary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,21 @@

namespace CloudinaryDotNet.Tests
{
public class MockedCloudinary : Cloudinary
public static class MockHelpers
{
public Mock<HttpMessageHandler> HandlerMock;
public string HttpRequestContent;
private const string cloudName = "test_cloud";

public MockedCloudinary(string responseStr = "{}") : base("cloudinary://a:b@test_cloud")
public static Mock<HttpMessageHandler> SetupMock(this IMockedApi mockedApi, string responseStr)
{
HandlerMock = new Mock<HttpMessageHandler>();
HandlerMock.Protected()
var mock = new Mock<HttpMessageHandler>();
mock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.Callback<HttpRequestMessage, CancellationToken>(
(httpRequestMessage, cancellationToken) =>
{
HttpRequestContent = httpRequestMessage.Content?
mockedApi.HttpRequestContent = httpRequestMessage.Content?
.ReadAsStringAsync()
.GetAwaiter()
.GetResult();
Expand All @@ -34,26 +31,56 @@ public MockedCloudinary(string responseStr = "{}") : base("cloudinary://a:b@test
StatusCode = HttpStatusCode.OK,
Content = new StringContent(responseStr)
});
Api.Client = new HttpClient(HandlerMock.Object);
return mock;
}

/// <summary>
/// <para>Asserts that a given HTTP call was sent with expected parameters.</para>
/// </summary>
/// <param name="httpMethod">Expected HTTP method type.</param>
/// <param name="localPath">Expected local part of the called Uri.</param>
public void AssertHttpCall(System.Net.Http.HttpMethod httpMethod, string localPath)
public static void AssertHttpCall(
this IMockedApi mockedApi,
System.Net.Http.HttpMethod httpMethod,
string localPath
)
{
HandlerMock.Protected().Verify(
mockedApi.HandlerMock.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req =>
req.Method == httpMethod &&
req.RequestUri.LocalPath == $"/v1_1/{cloudName}/{localPath}" &&
req.RequestUri.LocalPath == $"/v1_1/{CloudName}/{localPath}" &&
req.Properties.Count == 0
),
ItExpr.IsAny<CancellationToken>()
);
}
public const string CloudName = "test_cloud";
}

public interface IMockedApi
{
Mock<HttpMessageHandler> HandlerMock { get; set; }
string HttpRequestContent { set; }
}

internal class MockedCloudinaryAdmin : CloudinaryAdmin, IMockedApi
{
public Mock<HttpMessageHandler> HandlerMock { get; set; }
public string HttpRequestContent { get; set; }

public MockedCloudinaryAdmin(string responseStr = "{}") : base($"cloudinary://a:b@{MockHelpers.CloudName}")
{
HandlerMock = this.SetupMock(responseStr);
Api.Client = new HttpClient(HandlerMock.Object);
}
}

internal class MockedCloudinaryUpload : CloudinaryUpload, IMockedApi
{
public Mock<HttpMessageHandler> HandlerMock { get; set; }
public string HttpRequestContent { get; set; }

public MockedCloudinaryUpload(string responseStr = "{}") : base($"cloudinary://a:b@{MockHelpers.CloudName}")
{
HandlerMock = this.SetupMock(responseStr);
Api.Client = new HttpClient(HandlerMock.Object);
}
}
}
2 changes: 1 addition & 1 deletion CloudinaryDotNet.Tests/SearchTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace CloudinaryDotNet.Tests
{
public class SearchTest
{
private MockedCloudinary m_cloudinary = new MockedCloudinary();
private MockedCloudinaryAdmin m_cloudinary = new MockedCloudinaryAdmin();

[Test]
public void TestShouldNotDuplicateValues()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public class CreateSlideshowMethodsTest
[Test]
public void TestCreateSlideshowFromManifestTransformation()
{
var cloudinary = new MockedCloudinary();
var cloudinary = new MockedCloudinaryUpload();

const string slideshowManifest = "w_352;h_240;du_5;fps_30;vars_(slides_((media_s64:aHR0cHM6Ly9y" +
"ZXMuY2xvdWRpbmFyeS5jb20vZGVtby9pbWFnZS91cGxvYWQvY291cGxl);(media_s64:aH" +
Expand Down Expand Up @@ -42,7 +42,7 @@ public void TestCreateSlideshowFromManifestTransformation()
[Test]
public void TestCreateSlideshowFromManifestJson()
{
var cloudinary = new MockedCloudinary();
var cloudinary = new MockedCloudinaryUpload();

const string expectedManifestJson =
@"{""w"":848,""h"":480,""du"":6,""fps"":30,""vars"":{""sdur"":500,""tdur"":500,""slides"":"+
Expand Down
8 changes: 4 additions & 4 deletions CloudinaryDotNet.Tests/UploadPresetsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,18 @@ public class UploadPresetsTest
private const string evalStr = "if (resource_info['width'] > 450) " +
"{ upload_options['quality_analysis'] = true }; " +
"upload_options['context'] = 'width = ' + resource_info['width']";
private MockedCloudinary mockedCloudinary;
private MockedCloudinaryAdmin mockedCloudinary;

[SetUp]
public void SetUp()
{
mockedCloudinary = new MockedCloudinary();
mockedCloudinary = new MockedCloudinaryAdmin();
}

[Test]
public void TestListUploadPresets()
{
var localCloudinaryMock = new MockedCloudinary("{presets: [{eval: 'some value'}]}");
var localCloudinaryMock = new MockedCloudinaryAdmin("{presets: [{eval: 'some value'}]}");

var result = localCloudinaryMock.ListUploadPresets();

Expand All @@ -36,7 +36,7 @@ public void TestListUploadPresets()
[Test]
public void TestGetUploadPreset()
{
var localCloudinaryMock = new MockedCloudinary("{eval: 'some value'}");
var localCloudinaryMock = new MockedCloudinaryAdmin("{eval: 'some value'}");

var result = localCloudinaryMock.GetUploadPreset(apiTestPreset);

Expand Down
Loading