Skip to content

Commit ed69c56

Browse files
committed
coverage improve
1 parent b997e16 commit ed69c56

File tree

6 files changed

+163
-6
lines changed

6 files changed

+163
-6
lines changed

Imagekit.UnitTests/ClientImagekitTests.cs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.IO;
23
using System.Net;
34
using System.Net.Http;
45
using System.Threading.Tasks;
@@ -69,6 +70,16 @@ public void Constructor_TransformationPosition(string transformationPosition, bo
6970
}
7071
}
7172

73+
[Fact]
74+
public void Upload_Exception()
75+
{
76+
var fileName = Guid.NewGuid().ToString();
77+
var auth = TestHelpers.AuthParamResponseFaker.Generate();
78+
var imagekit = new ClientImagekit(GOOD_PUBLICKEY, GOOD_URLENDPOINT);
79+
var ex = Assert.ThrowsAsync<ArgumentException>(async () => await imagekit.UploadAsync("", auth));
80+
Assert.Equal(Util.errorMessages.MISSING_UPLOAD_FILE_PARAMETER, ex.Result.Message);
81+
}
82+
7283
[Fact]
7384
public void Upload()
7485
{
@@ -91,6 +102,29 @@ public void Upload()
91102
Assert.Equal(JsonConvert.SerializeObject(responseObj), JsonConvert.SerializeObject(response));
92103
}
93104

105+
[Fact]
106+
public void UploadBytes()
107+
{
108+
var fileName = Guid.NewGuid().ToString();
109+
string base64 = "iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
110+
byte[] bytes = Convert.FromBase64String(base64);
111+
var auth = TestHelpers.AuthParamResponseFaker.Generate();
112+
var responseObj = TestHelpers.ImagekitResponseFaker.Generate();
113+
var httpResponse = new HttpResponseMessage
114+
{
115+
StatusCode = HttpStatusCode.OK,
116+
Content = new StringContent(JsonConvert.SerializeObject(responseObj))
117+
};
118+
var httpClient = TestHelpers.GetTestHttpClient(httpResponse,
119+
TestHelpers.GetUploadRequestMessageValidator(base64, fileName, publicKey: GOOD_PUBLICKEY, clientAuth: auth));
120+
Util.Utils.SetHttpClient(httpClient);
121+
122+
var imagekit = new ClientImagekit(GOOD_PUBLICKEY, GOOD_URLENDPOINT)
123+
.FileName(fileName);
124+
var response = imagekit.Upload(bytes, auth);
125+
Assert.Equal(JsonConvert.SerializeObject(responseObj), JsonConvert.SerializeObject(response));
126+
}
127+
94128
[Fact]
95129
public async Task UploadAsync()
96130
{

Imagekit.UnitTests/ServerImagekitTests.cs

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,27 @@ public void GetUploadData_TagsString()
142142
Assert.Equal("tag1,tag2", actualTags);
143143
}
144144

145+
[Fact]
146+
public void GetUploadData_Generic()
147+
{
148+
var fileName = Guid.NewGuid().ToString();
149+
var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT)
150+
.FileName(fileName)
151+
.Folder("/test/")
152+
.isPrivateFile(true)
153+
.UseUniqueFileName(false)
154+
.CustomCoordinates("10,10,100,100")
155+
.ResponseFields("tags,customCoordinates,isPrivateFile")
156+
.Tags("tag1,tag2");
157+
var data = imagekit.getUploadData();
158+
Assert.True(data.TryGetValue("responseFields", out string respFields), "ResponseFields upload data not found");
159+
Assert.True(data.TryGetValue("useUniqueFileName", out string uniqueParam), "UseUniqueFileName upload not found");
160+
Assert.True(data.TryGetValue("folder", out string folder), "folder upload not found");
161+
Assert.Equal("tags,customCoordinates,isPrivateFile", respFields);
162+
Assert.Equal("false", uniqueParam);
163+
Assert.Equal("/test/", folder);
164+
}
165+
145166
[Fact]
146167
public void GetUploadData_TagsArray()
147168
{
@@ -154,6 +175,51 @@ public void GetUploadData_TagsArray()
154175
Assert.Equal("tag1,tag2", actualTags);
155176
}
156177

178+
[Fact]
179+
public void GetUploadData_MissingFileName_Exception()
180+
{
181+
var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT)
182+
.Tags("tag1");
183+
var ex = Assert.Throws<ArgumentException>(() => imagekit.getUploadData());
184+
Assert.Equal(errorMessages.MISSING_UPLOAD_FILENAME_PARAMETER, ex.Message);
185+
}
186+
187+
[Fact]
188+
public void ListFiles()
189+
{
190+
var fileId = Guid.NewGuid().ToString();
191+
var responseObj = TestHelpers.ListAPIResponseFaker.Generate();
192+
var httpResponse = new HttpResponseMessage
193+
{
194+
StatusCode = HttpStatusCode.OK,
195+
Content = new StringContent(JsonConvert.SerializeObject(responseObj))
196+
};
197+
var httpClient = TestHelpers.GetTestHttpClient(httpResponse);
198+
Util.Utils.SetHttpClient(httpClient);
199+
200+
var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT);
201+
var response = imagekit.ListFiles();
202+
Assert.Equal(responseObj.StatusCode, response[0].StatusCode);
203+
}
204+
205+
[Fact]
206+
public async void DeleteApi_Response()
207+
{
208+
var fileId = Guid.NewGuid().ToString();
209+
var responseObj = TestHelpers.DeleteAPIResponseFaker.Generate();
210+
var httpResponse = new HttpResponseMessage
211+
{
212+
StatusCode = HttpStatusCode.OK,
213+
Content = new StringContent(JsonConvert.SerializeObject(responseObj))
214+
};
215+
var httpClient = TestHelpers.GetTestHttpClient(httpResponse);
216+
Util.Utils.SetHttpClient(httpClient);
217+
218+
var imagekit = new ServerImagekit(GOOD_PUBLICKEY, GOOD_PRIVATEKEY, GOOD_URLENDPOINT);
219+
var response = await imagekit.DeleteFileAsync(fileId);
220+
Assert.Equal(responseObj.StatusCode, response.StatusCode);
221+
}
222+
157223
[Theory]
158224
[InlineData(null)]
159225
[InlineData("null")]
@@ -256,6 +322,19 @@ public void IsLocalPathTest(string path, bool expected)
256322
Assert.Equal(expected, Util.Utils.IsLocalPath(path));
257323
}
258324

325+
[Theory]
326+
[InlineData("https://example.com/test.jpg", true)]
327+
[InlineData("http://example.com/", true)]
328+
[InlineData("ftp://example.com", false)]
329+
[InlineData(@"C:\test\test 1.jpg", false)]
330+
[InlineData(@"C:\test\test.jpg", false)]
331+
[InlineData(@"\\test.com\test.jpg", false)]
332+
[InlineData("http:\\mysite\test.xml", false)]
333+
public void IsValidURITest(string url, bool expected)
334+
{
335+
Assert.Equal(expected, Util.Utils.IsValidURI(url));
336+
}
337+
259338
[Fact]
260339
public void Url_WithoutUrl_Source()
261340
{
@@ -288,6 +367,22 @@ public void Url_Signed()
288367
Assert.Equal("https://ik.imagekit.io/test_url_endpoint/default-image.jpg?ik-s=d0f5c0d0c92c0072068b45d3d5a73ab6e306dbf8", imageURL);
289368
}
290369

370+
[Fact]
371+
public void Url_Signed_Timestamp()
372+
{
373+
string imageURL = imagekit.Url(new Transformation()).Path(SAMPLE_PATH).Signed(true).ExpireSeconds(300).Generate();
374+
Assert.Contains("https://ik.imagekit.io/test_url_endpoint/default-image.jpg?ik-t=", imageURL);
375+
}
376+
377+
[Fact]
378+
public void Url_Signed_Without_priavteKey()
379+
{
380+
ClientImagekit imagekit1 = new ClientImagekit(GOOD_PUBLICKEY, URLENDPOINT)
381+
.Path(SAMPLE_PATH).Signed(true).ExpireSeconds(300);
382+
var ex = Assert.Throws<ArgumentNullException>(() => imagekit1.Url(new Transformation()).Path(SAMPLE_PATH).Signed(true).ExpireSeconds(300).Generate());
383+
Assert.Equal(errorMessages.PRIVATE_KEY_MISSING, ex.ParamName);
384+
}
385+
291386
[Fact]
292387
public void Url_WithPath_Transformation()
293388
{
@@ -302,6 +397,13 @@ public void Url_WithSRC_Transform()
302397
Assert.Equal(URLENDPOINT + "/default-image.jpg?tr=h-300%2Cw-400", imageURL);
303398
}
304399

400+
[Fact]
401+
public void Url_WithSRC_Param_Transform()
402+
{
403+
string imageURL = imagekit.Url(new Transformation().Height(300).Width(400)).Src(SAMPLE_SRC_URL+"?a=test").Generate();
404+
Assert.Equal(URLENDPOINT + "/default-image.jpg?a=test&tr=h-300%2Cw-400", imageURL);
405+
}
406+
305407
[Fact]
306408
public void Url_WithPath_Multiple_LeadingSlash()
307409
{

Imagekit.UnitTests/TestHelpers.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,13 @@ static TestHelpers()
5151
.RuleFor(u => u.expire, (f, u) => DateTimeOffset.UtcNow.AddMinutes(30).ToUnixTimeSeconds().ToString())
5252
.RuleFor(u => u.signature, (f, u) => f.Random.Utf16String());
5353

54+
public static Faker<DeleteAPIResponse> DeleteAPIResponseFaker = new Faker<DeleteAPIResponse>()
55+
.RuleFor(u => u.Exception, (f, u) => f.Random.Bool())
56+
.RuleFor(u => u.StatusCode, (f, u) => 200)
57+
.RuleFor(u => u.Message, (f, u) => f.Random.Utf16String())
58+
.RuleFor(u => u.Help, (f, u) => f.Random.Utf16String())
59+
.RuleFor(u => u.XIkRequestId, (f, u) => null);
60+
5461
public static Faker<MetadataResponse> MetadataResponseFaker = new Faker<MetadataResponse>()
5562
.RuleFor(u => u.Exif, (f, u) => f.Random.Utf16String())
5663
.RuleFor(u => u.Density, (f, u) => f.Random.Int())

Imagekit/Imagekit.cs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,18 @@ public async Task<List<ListAPIResponse>> ListFilesAsync()
139139
Uri apiEndpoint = new Uri(Utils.GetFileApi() + "?" + string.Join("&", param));
140140
var response = await Utils.GetAsync(apiEndpoint, (string)options["privateKey"]).ConfigureAwait(false);
141141
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
142-
return JsonConvert.DeserializeObject<List<ListAPIResponse>>(responseContent);
142+
try
143+
{
144+
return JsonConvert.DeserializeObject<List<ListAPIResponse>>(responseContent);
145+
} catch
146+
{
147+
ListAPIResponse resp = JsonConvert.DeserializeObject<ListAPIResponse>(responseContent);
148+
resp.StatusCode = (int)response.StatusCode;
149+
resp.XIkRequestId = response.Headers.FirstOrDefault(x => x.Key == "x-ik-requestid").Value?.First();
150+
List<ListAPIResponse> respList=new List<ListAPIResponse>();
151+
respList.Add(resp);
152+
return respList;
153+
}
143154
}
144155

145156

Imagekit/Url.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,14 @@ public bool AddAsQueryParameter()
157157
public string GetSignature(string url, string expiryTimestamp)
158158
{
159159
var endPoint = RemoveTrailingSlash((string)options["urlEndpoint"]);
160-
if (string.IsNullOrEmpty((string)options["privateKey"]) || string.IsNullOrEmpty((string)options["urlEndpoint"]))
160+
string str = Regex.Replace(url, endPoint + "/", "") + expiryTimestamp;
161+
try
162+
{
163+
var privateKey = (string)options["privateKey"];
164+
} catch
161165
{
162166
throw new ArgumentNullException(errorMessages.PRIVATE_KEY_MISSING);
163167
}
164-
string str = Regex.Replace(url, endPoint + "/", "") + expiryTimestamp;
165168
return Utils.calculateSignature(str, Encoding.ASCII.GetBytes((string)options["privateKey"]));
166169
}
167170
}

Imagekit/Util/Utils.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -226,15 +226,15 @@ public static HttpResponseMessage PostUpload(Uri uri, Dictionary<string, string>
226226

227227
public static bool IsLocalPath(string p)
228228
{
229-
if (p.StartsWith("http:\\", StringComparison.Ordinal))
229+
if (p.StartsWith("http:", StringComparison.Ordinal))
230230
{
231231
return false;
232232
}
233-
else if (p.StartsWith("https:\\", StringComparison.Ordinal))
233+
else if (p.StartsWith("https:", StringComparison.Ordinal))
234234
{
235235
return false;
236236
}
237-
else if (p.StartsWith("ftp:\\", StringComparison.Ordinal))
237+
else if (p.StartsWith("ftp:", StringComparison.Ordinal))
238238
{
239239
return false;
240240
}

0 commit comments

Comments
 (0)