-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathContentstack013_AssetTest.cs
More file actions
4167 lines (3695 loc) · 176 KB
/
Copy pathContentstack013_AssetTest.cs
File metadata and controls
4167 lines (3695 loc) · 176 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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.Threading;
using System.Threading.Tasks;
using System.Text;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.CustomExtension;
using Contentstack.Management.Core.Tests.Helpers;
using Contentstack.Management.Core.Tests.Model;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Queryable;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Contentstack.Management.Core.Tests.IntegrationTest
{
[TestClass]
public class Contentstack006_AssetTest
{
private static ContentstackClient _client;
private Stack _stack;
private static List<string> _testAssetUIDs = new List<string>();
private static List<string> _testFolderUIDs = new List<string>();
private static List<string> _testTemporaryFiles = new List<string>();
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
_client = Contentstack.CreateAuthenticatedClient();
}
[ClassCleanup]
public static void ClassCleanup()
{
CleanupTestAssets(_testAssetUIDs);
CleanupTemporaryFiles();
try { _client?.Logout(); } catch { }
_client = null;
}
[TestInitialize]
public void Initialize()
{
StackResponse response = StackResponse.getStack(_client.serializer);
_stack = _client.Stack(response.Stack.APIKey);
}
#region Helper Methods
/// <summary>
/// Validates that a response has expected file validation error status codes
/// </summary>
private static void AssertFileValidationError(Exception ex, string assertionName)
{
if (ex is ContentstackErrorException cex)
{
AssertLogger.IsTrue(
cex.StatusCode == HttpStatusCode.BadRequest ||
cex.StatusCode == (HttpStatusCode)422 ||
cex.StatusCode == HttpStatusCode.UnsupportedMediaType ||
cex.StatusCode == (HttpStatusCode)413 ||
cex.StatusCode == HttpStatusCode.NotFound,
$"Expected 400/413/415/422/404 for file validation error, got {(int)cex.StatusCode} ({cex.StatusCode})",
assertionName);
}
else if (ex is ArgumentException || ex is InvalidOperationException || ex is FileNotFoundException)
{
AssertLogger.IsTrue(true, "SDK validation caught file validation error as expected", assertionName);
}
else
{
AssertLogger.Fail($"Unexpected exception type for file validation: {ex.GetType().Name}", assertionName);
}
}
/// <summary>
/// Validates that a response has expected authentication/authorization error status codes
/// </summary>
private static void AssertAuthenticationError(Exception ex, string assertionName)
{
if (ex is ContentstackErrorException cex)
{
AssertLogger.IsTrue(
cex.StatusCode == HttpStatusCode.Unauthorized ||
cex.StatusCode == HttpStatusCode.Forbidden ||
cex.StatusCode == HttpStatusCode.PreconditionFailed, // API returns 412 for invalid API keys
$"Expected 401/403/412 for auth error, got {(int)cex.StatusCode} ({cex.StatusCode})",
assertionName);
}
else if (ex is InvalidOperationException && ex.Message.Contains("not logged in"))
{
AssertLogger.IsTrue(true, "SDK validation threw InvalidOperationException for auth as expected", assertionName);
}
else
{
AssertLogger.Fail($"Unexpected exception type for auth error: {ex.GetType().Name}", assertionName);
}
}
/// <summary>
/// Validates that a response has expected network error status codes or exceptions
/// </summary>
private static void AssertNetworkError(Exception ex, string assertionName)
{
if (ex is ContentstackErrorException cex)
{
AssertLogger.IsTrue(
cex.StatusCode == HttpStatusCode.ServiceUnavailable ||
cex.StatusCode == HttpStatusCode.RequestTimeout ||
cex.StatusCode == (HttpStatusCode)429 || // Too Many Requests
cex.StatusCode == HttpStatusCode.BadGateway,
$"Expected network error status code, got {(int)cex.StatusCode} ({cex.StatusCode})",
assertionName);
}
else if (ex is TaskCanceledException || ex is OperationCanceledException || ex is TimeoutException)
{
AssertLogger.IsTrue(true, "Network timeout properly handled", assertionName);
}
else
{
AssertLogger.Fail($"Unexpected exception type for network error: {ex.GetType().Name}", assertionName);
}
}
/// <summary>
/// Validates that a response has expected security error status codes
/// </summary>
private static void AssertAssetSecurityError(Exception ex, string assertionName)
{
if (ex is ContentstackErrorException cex)
{
AssertLogger.IsTrue(
cex.StatusCode == HttpStatusCode.BadRequest ||
cex.StatusCode == (HttpStatusCode)422 ||
cex.StatusCode == HttpStatusCode.UnsupportedMediaType ||
cex.StatusCode == HttpStatusCode.Forbidden ||
cex.StatusCode == HttpStatusCode.NotFound, // API treats malicious UIDs as non-existent
$"Expected security error status code, got {(int)cex.StatusCode} ({cex.StatusCode})",
assertionName);
}
else if (ex is ArgumentException || ex is InvalidOperationException)
{
AssertLogger.IsTrue(true, "SDK security validation caught error as expected", assertionName);
}
else
{
AssertLogger.Fail($"Unexpected exception type for security error: {ex.GetType().Name}", assertionName);
}
}
/// <summary>
/// Creates invalid asset models for various test scenarios
/// </summary>
private static AssetModel CreateInvalidAssetModel(string scenario)
{
var mockFilePath = Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/contentTypeSchema.json");
switch (scenario)
{
case "null_filename":
return new AssetModel(null, mockFilePath, "application/json", title: "Test Asset", description: "test", parentUID: null, tags: "test");
case "empty_filename":
return new AssetModel("", mockFilePath, "application/json", title: "Test Asset", description: "test", parentUID: null, tags: "test");
case "sql_injection_filename":
return new AssetModel("'; DROP TABLE assets; --.json", mockFilePath, "application/json", title: "Malicious Asset", description: "test", parentUID: null, tags: "test");
case "xss_title":
return new AssetModel("test.json", mockFilePath, "application/json", title: "<script>alert('xss')</script>", description: "test", parentUID: null, tags: "test");
case "extremely_long_title":
var longTitle = new string('a', 10000);
return new AssetModel("test.json", mockFilePath, "application/json", title: longTitle, description: "test", parentUID: null, tags: "test");
case "invalid_mime_type":
return new AssetModel("test.json", mockFilePath, "application/x-executable", title: "Test Asset", description: "test", parentUID: null, tags: "test");
case "executable_file":
var execPath = CreateTemporaryMaliciousFile("malicious.exe", "MZ"); // DOS header
return new AssetModel("malicious.exe", execPath, "application/octet-stream", title: "Executable", description: "test", parentUID: null, tags: "test");
default:
return new AssetModel("invalid_asset.json", mockFilePath, "application/json", title: "Invalid Asset", description: "test", parentUID: null, tags: "test");
}
}
/// <summary>
/// Creates malicious filenames for security testing
/// </summary>
private static string CreateMaliciousFileName(string scenario)
{
switch (scenario)
{
case "path_traversal":
return "../../etc/passwd";
case "null_byte_injection":
return "innocent.txt\0malicious.exe";
case "unicode_bypass":
return "test\u202e.txt\u202dexe.bat"; // Right-to-Left Override
case "long_extension":
return "test." + new string('a', 1000);
case "no_extension":
return "noextension";
case "double_extension":
return "image.jpg.exe";
default:
return "malicious_file.txt";
}
}
/// <summary>
/// Creates corrupted file content for testing
/// </summary>
private static byte[] CreateCorruptedFileContent(string scenario)
{
switch (scenario)
{
case "invalid_header":
return Encoding.UTF8.GetBytes("CORRUPTED_HEADER" + new string('x', 1000));
case "zero_bytes":
return new byte[0];
case "null_bytes":
return new byte[1000]; // All zeros
case "random_binary":
var random = new Random();
var bytes = new byte[1000];
random.NextBytes(bytes);
return bytes;
default:
return Encoding.UTF8.GetBytes("corrupted content");
}
}
/// <summary>
/// Validates asset response for various operations
/// </summary>
private static void ValidateAssetResponse(ContentstackResponse response, string operation)
{
AssertLogger.IsNotNull(response, $"{operation}_Response");
if (response.IsSuccessStatusCode)
{
var expectedStatusCode = operation.ToLower().Contains("create") ? HttpStatusCode.Created : HttpStatusCode.OK;
AssertLogger.AreEqual(expectedStatusCode, response.StatusCode, $"{operation}_StatusCode");
}
}
/// <summary>
/// Simulates network latency for testing timeout scenarios
/// </summary>
private static async Task SimulateNetworkLatency(int milliseconds)
{
await Task.Delay(milliseconds);
}
/// <summary>
/// Creates temporary malicious files for testing
/// </summary>
private static string CreateTemporaryMaliciousFile(string fileName, string content)
{
var tempDir = Path.GetTempPath();
var filePath = Path.Combine(tempDir, $"test_{Guid.NewGuid()}_{fileName}");
try
{
File.WriteAllText(filePath, content);
_testTemporaryFiles.Add(filePath);
return filePath;
}
catch
{
return Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/contentTypeSchema.json");
}
}
/// <summary>
/// Creates temporary binary files with specific content
/// </summary>
private static string CreateTemporaryBinaryFile(string fileName, byte[] content)
{
var tempDir = Path.GetTempPath();
var filePath = Path.Combine(tempDir, $"test_{Guid.NewGuid()}_{fileName}");
try
{
File.WriteAllBytes(filePath, content);
_testTemporaryFiles.Add(filePath);
return filePath;
}
catch
{
return Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/contentTypeSchema.json");
}
}
/// <summary>
/// Cleans up test assets to avoid polluting the stack
/// </summary>
private static void CleanupTestAssets(List<string> assetUIDs)
{
if (_client == null) return;
try
{
var stack = _client.Stack(StackResponse.getStack(_client.serializer).Stack.APIKey);
foreach (var uid in assetUIDs)
{
try
{
stack.Asset(uid).Delete();
}
catch
{
// Ignore cleanup failures
}
}
}
catch
{
// Ignore cleanup failures
}
}
/// <summary>
/// Cleans up temporary test files
/// </summary>
private static void CleanupTemporaryFiles()
{
foreach (var filePath in _testTemporaryFiles)
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
catch
{
// Ignore cleanup failures
}
}
_testTemporaryFiles.Clear();
}
/// <summary>
/// Creates an invalid asset UID for testing
/// </summary>
private static string CreateInvalidAssetUID(string scenario)
{
switch (scenario)
{
case "null":
return null;
case "empty":
return "";
case "whitespace":
return " ";
case "sql_injection":
return "'; DROP TABLE assets; --";
case "xss_attempt":
return "<script>alert('xss')</script>";
case "extremely_long":
return new string('a', 5000);
case "special_chars":
return "asset@uid#with$special%chars";
case "unicode":
return "asset_uid_中文_😀";
default:
return "invalid_asset_uid_12345";
}
}
#endregion
[TestMethod]
[DoNotParallelize]
public async Task Test001_Should_Create_Asset()
{
TestOutputLogger.LogContext("TestScenario", "CreateAsset");
var path = Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/contentTypeSchema.json");
try
{
AssetModel asset = new AssetModel("contentTypeSchema.json", path, "application/json", title:"New.json", description:"new test desc", parentUID: null, tags:"one,two");
ContentstackResponse response = _stack.Asset().Create(asset);
TestOutputLogger.LogContext("StackAPIKey", _stack?.APIKey ?? "null");
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.Created, response.StatusCode, "CreateAsset_StatusCode");
}
else
{
// Don't fail the test if API returns an error - this might be expected behavior
}
}
catch (Exception e)
{
AssertLogger.Fail("Asset Creation Failed ", e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test002_Should_Create_Dashboard()
{
TestOutputLogger.LogContext("TestScenario", "CreateDashboardWidget");
var path = Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/extension.html");
try
{
DashboardWidgetModel dashboard = new DashboardWidgetModel(
path, "text/html", "Integration Test Dashboard",
isEnable: true, defaultWidth: "half", tags: "dashboard,test");
ContentstackResponse response = await _stack.Extension().UploadAsync(dashboard);
TestOutputLogger.LogContext("StackAPIKey", _stack?.APIKey ?? "null");
if (response.IsSuccessStatusCode)
{
AssertLogger.IsNotNull(response.OpenJsonObjectResponse()["extension"], "CreateDashboard_ResponseContainsExtension");
}
else
{
AssertLogger.Fail("Dashboard Widget Creation Failed", response.OpenResponse());
}
}
catch (Exception e)
{
AssertLogger.Fail("Dashboard Widget Creation Failed", e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test003_Should_Create_Custom_Widget()
{
TestOutputLogger.LogContext("TestScenario", "CreateCustomWidget");
var path = Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/extension.html");
try
{
var scope = new ExtensionScope { ContentTypes = new List<string> { "$all" } };
CustomWidgetModel widget = new CustomWidgetModel(
path, "text/html", "Integration Test Widget",
tags: "widget,test", scope: scope);
ContentstackResponse response = await _stack.Extension().UploadAsync(widget);
TestOutputLogger.LogContext("StackAPIKey", _stack?.APIKey ?? "null");
if (response.IsSuccessStatusCode)
{
AssertLogger.IsNotNull(response.OpenJsonObjectResponse()["extension"], "CreateCustomWidget_ResponseContainsExtension");
}
else
{
AssertLogger.Fail("Custom Widget Creation Failed", response.OpenResponse());
}
}
catch (Exception e)
{
AssertLogger.Fail("Custom Widget Creation Failed", e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test004_Should_Create_Custom_field()
{
TestOutputLogger.LogContext("TestScenario", "CreateCustomField");
var path = Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/extension.html");
try
{
CustomFieldModel field = new CustomFieldModel(
path, "text/html", "Integration Test Field",
dataType: "text", isMultiple: false, tags: "field,test");
ContentstackResponse response = await _stack.Extension().UploadAsync(field);
TestOutputLogger.LogContext("StackAPIKey", _stack?.APIKey ?? "null");
if (response.IsSuccessStatusCode)
{
AssertLogger.IsNotNull(response.OpenJsonObjectResponse()["extension"], "CreateCustomField_ResponseContainsExtension");
}
else
{
AssertLogger.Fail("Custom Field Creation Failed", response.OpenResponse());
}
}
catch (Exception e)
{
AssertLogger.Fail("Custom Field Creation Failed", e.Message);
}
}
private string _testAssetUid;
[TestMethod]
[DoNotParallelize]
public async Task Test005_Should_Create_Asset_Async()
{
TestOutputLogger.LogContext("TestScenario", "CreateAssetAsync");
var path = Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/contentTypeSchema.json");
try
{
AssetModel asset = new AssetModel("async_asset.json", path, "application/json", title:"Async Asset", description:"async test asset", parentUID: null, tags:"async,test");
ContentstackResponse response = _stack.Asset().CreateAsync(asset).Result;
TestOutputLogger.LogContext("StackAPIKey", _stack?.APIKey ?? "null");
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.Created, response.StatusCode, "CreateAssetAsync_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
if (responseObject["asset"] != null)
{
_testAssetUid = responseObject["asset"]["uid"]?.ToString();
TestOutputLogger.LogContext("AssetUID", _testAssetUid ?? "null");
}
}
else
{
AssertLogger.Fail("Asset Creation Async Failed");
}
}
catch (Exception ex)
{
AssertLogger.Fail("Asset Creation Async Failed ",ex.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test006_Should_Fetch_Asset()
{
TestOutputLogger.LogContext("TestScenario", "FetchAsset");
try
{
if (string.IsNullOrEmpty(_testAssetUid))
{
await Test005_Should_Create_Asset_Async();
}
if (!string.IsNullOrEmpty(_testAssetUid))
{
TestOutputLogger.LogContext("AssetUID", _testAssetUid);
ContentstackResponse response = _stack.Asset(_testAssetUid).Fetch();
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode, "FetchAsset_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["asset"], "FetchAsset_ResponseContainsAsset");
}
else
{
AssertLogger.Fail("The Asset is Not Getting Created");
}
}
}
catch (Exception e)
{
AssertLogger.Fail("Asset Fetch Failed ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test007_Should_Fetch_Asset_Async()
{
TestOutputLogger.LogContext("TestScenario", "FetchAssetAsync");
try
{
if (string.IsNullOrEmpty(_testAssetUid))
{
await Test005_Should_Create_Asset_Async();
}
if (!string.IsNullOrEmpty(_testAssetUid))
{
TestOutputLogger.LogContext("AssetUID", _testAssetUid);
ContentstackResponse response = _stack.Asset(_testAssetUid).FetchAsync().Result;
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode, "FetchAssetAsync_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["asset"], "FetchAssetAsync_ResponseContainsAsset");
}
else
{
AssertLogger.Fail("Asset Fetch Async Failed");
}
}
}
catch (Exception e)
{
AssertLogger.Fail("Asset Fetch Async Failed ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test008_Should_Update_Asset()
{
TestOutputLogger.LogContext("TestScenario", "UpdateAsset");
try
{
if (string.IsNullOrEmpty(_testAssetUid))
{
await Test005_Should_Create_Asset_Async();
}
if (!string.IsNullOrEmpty(_testAssetUid))
{
TestOutputLogger.LogContext("AssetUID", _testAssetUid);
var path = Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/contentTypeSchema.json");
AssetModel updatedAsset = new AssetModel("updated_asset.json", path, "application/json", title:"Updated Asset", description:"updated test asset", parentUID: null, tags:"updated,test");
ContentstackResponse response = _stack.Asset(_testAssetUid).Update(updatedAsset);
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode, "UpdateAsset_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["asset"], "UpdateAsset_ResponseContainsAsset");
}
else
{
AssertLogger.Fail("Asset update Failed");
}
}
}
catch (Exception e)
{
AssertLogger.Fail("Asset Update Failed ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test009_Should_Update_Asset_Async()
{
TestOutputLogger.LogContext("TestScenario", "UpdateAssetAsync");
try
{
if (string.IsNullOrEmpty(_testAssetUid))
{
await Test005_Should_Create_Asset_Async();
}
if (!string.IsNullOrEmpty(_testAssetUid))
{
TestOutputLogger.LogContext("AssetUID", _testAssetUid);
var path = Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/contentTypeSchema.json");
AssetModel updatedAsset = new AssetModel("async_updated_asset.json", path, "application/json", title:"Async Updated Asset", description:"async updated test asset", parentUID: null, tags:"async,updated,test");
ContentstackResponse response = _stack.Asset(_testAssetUid).UpdateAsync(updatedAsset).Result;
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode, "UpdateAssetAsync_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["asset"], "UpdateAssetAsync_ResponseContainsAsset");
}
else
{
AssertLogger.Fail("Asset Update Async Failed");
}
}
}
catch (Exception e)
{
AssertLogger.Fail("Asset Update Async Failed ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test010_Should_Query_Assets()
{
TestOutputLogger.LogContext("TestScenario", "QueryAssets");
try
{
TestOutputLogger.LogContext("StackAPIKey", _stack?.APIKey ?? "null");
ContentstackResponse response = _stack.Asset().Query().Find();
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode, "QueryAssets_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["assets"], "QueryAssets_ResponseContainsAssets");
}
else
{
AssertLogger.Fail("Querying the Asset Failed");
}
}
catch (ContentstackErrorException ex)
{
AssertLogger.Fail("Querying the Asset Failed ",ex.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test011_Should_Query_Assets_With_Parameters()
{
TestOutputLogger.LogContext("TestScenario", "QueryAssetsWithParameters");
try
{
TestOutputLogger.LogContext("StackAPIKey", _stack?.APIKey ?? "null");
var query = _stack.Asset().Query();
query.Limit(5);
query.Skip(0);
ContentstackResponse response = query.Find();
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode, "QueryAssetsWithParams_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["assets"], "QueryAssetsWithParams_ResponseContainsAssets");
}
else
{
AssertLogger.Fail("Querying the Asset Failed");
}
}
catch (Exception e)
{
AssertLogger.Fail("Querying the Asset Failed ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test012_Should_Delete_Asset()
{
TestOutputLogger.LogContext("TestScenario", "DeleteAsset");
try
{
if (string.IsNullOrEmpty(_testAssetUid))
{
await Test005_Should_Create_Asset_Async();
}
if (!string.IsNullOrEmpty(_testAssetUid))
{
TestOutputLogger.LogContext("AssetUID", _testAssetUid);
ContentstackResponse response = _stack.Asset(_testAssetUid).Delete();
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode, "DeleteAsset_StatusCode");
_testAssetUid = null; // Clear the UID since asset is deleted
}
else
{
AssertLogger.Fail("Deleting the Asset Failed");
}
}
}
catch (Exception e)
{
AssertLogger.Fail("Deleting the Asset Failed ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test013_Should_Delete_Asset_Async()
{
TestOutputLogger.LogContext("TestScenario", "DeleteAssetAsync");
try
{
TestOutputLogger.LogContext("StackAPIKey", _stack?.APIKey ?? "null");
var path = Path.Combine(System.Environment.CurrentDirectory, "../../../Mock/contentTypeSchema.json");
AssetModel asset = new AssetModel("delete_asset.json", path, "application/json", title:"Delete Asset", description:"asset for deletion", parentUID: null, tags:"delete,test");
ContentstackResponse createResponse = _stack.Asset().CreateAsync(asset).Result;
if (createResponse.IsSuccessStatusCode)
{
var responseObject = createResponse.OpenJsonObjectResponse();
string assetUid = responseObject["asset"]["uid"]?.ToString();
TestOutputLogger.LogContext("AssetUID", assetUid ?? "null");
if (!string.IsNullOrEmpty(assetUid))
{
ContentstackResponse deleteResponse = _stack.Asset(assetUid).DeleteAsync().Result;
if (deleteResponse.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, deleteResponse.StatusCode, "DeleteAssetAsync_StatusCode");
}
else
{
AssertLogger.Fail("Deleting Asset Async Failed");
}
}
}
else
{
AssertLogger.Fail("Deleting Asset Async Failed");
}
}
catch (Exception e)
{
AssertLogger.Fail("Deleting Asset Async Failed ",e.Message);
}
}
private string _testFolderUid;
[TestMethod]
[DoNotParallelize]
public async Task Test014_Should_Create_Folder()
{
TestOutputLogger.LogContext("TestScenario", "CreateFolder");
try
{
TestOutputLogger.LogContext("StackAPIKey", _stack?.APIKey ?? "null");
ContentstackResponse response = _stack.Asset().Folder().Create("Test Folder", null);
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.Created, response.StatusCode, "CreateFolder_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
if (responseObject["asset"] != null)
{
_testFolderUid = responseObject["asset"]["uid"]?.ToString();
TestOutputLogger.LogContext("FolderUID", _testFolderUid ?? "null");
}
}
else
{
AssertLogger.Fail("Folder Creation Failed");
}
}
catch (Exception e)
{
AssertLogger.Fail("Folder Creation Failed ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test015_Should_Create_Subfolder()
{
TestOutputLogger.LogContext("TestScenario", "CreateSubfolder");
try
{
if (string.IsNullOrEmpty(_testFolderUid))
{
await Test014_Should_Create_Folder();
}
if (!string.IsNullOrEmpty(_testFolderUid))
{
TestOutputLogger.LogContext("FolderUID", _testFolderUid);
ContentstackResponse response = _stack.Asset().Folder().Create("Test Subfolder", _testFolderUid);
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.Created, response.StatusCode, "CreateSubfolder_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["asset"], "CreateSubfolder_ResponseContainsFolder");
}
else
{
AssertLogger.Fail("SubFolder Creation Failed");
}
}
}
catch (Exception e)
{
AssertLogger.Fail("SubFolder Fetch Failed ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test016_Should_Fetch_Folder()
{
TestOutputLogger.LogContext("TestScenario", "FetchFolder");
try
{
if (string.IsNullOrEmpty(_testFolderUid))
{
await Test014_Should_Create_Folder();
}
if (!string.IsNullOrEmpty(_testFolderUid))
{
TestOutputLogger.LogContext("FolderUID", _testFolderUid);
ContentstackResponse response = _stack.Asset().Folder(_testFolderUid).Fetch();
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode, "FetchFolder_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["asset"], "FetchFolder_ResponseContainsFolder");
}
else
{
AssertLogger.Fail("Fetch Failed for Folder");
}
}
}
catch (Exception e)
{
AssertLogger.Fail("Fetch Async Failed for Folder ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test017_Should_Fetch_Folder_Async()
{
TestOutputLogger.LogContext("TestScenario", "FetchFolderAsync");
try
{
if (string.IsNullOrEmpty(_testFolderUid))
{
await Test014_Should_Create_Folder();
}
if (!string.IsNullOrEmpty(_testFolderUid))
{
TestOutputLogger.LogContext("FolderUID", _testFolderUid);
ContentstackResponse response = _stack.Asset().Folder(_testFolderUid).FetchAsync().Result;
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode, "FetchFolderAsync_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["asset"], "FetchFolderAsync_ResponseContainsFolder");
}
else
{
AssertLogger.Fail("Fetch Async Failed");
}
}
}
catch (Exception e)
{
AssertLogger.Fail("Fetch Async Failed for Folder ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test018_Should_Update_Folder()
{
TestOutputLogger.LogContext("TestScenario", "UpdateFolder");
try
{
if (string.IsNullOrEmpty(_testFolderUid))
{
await Test014_Should_Create_Folder();
}
if (!string.IsNullOrEmpty(_testFolderUid))
{
TestOutputLogger.LogContext("FolderUID", _testFolderUid);
ContentstackResponse response = _stack.Asset().Folder(_testFolderUid).Update("Updated Test Folder", null);
if (response.IsSuccessStatusCode)
{
AssertLogger.AreEqual(System.Net.HttpStatusCode.Created, response.StatusCode, "UpdateFolder_StatusCode");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["asset"], "UpdateFolder_ResponseContainsFolder");
}
else
{
AssertLogger.Fail("Folder update Failed");
}
}
}
catch (Exception e)
{
AssertLogger.Fail("Folder Update Async Failed ",e.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test019_Should_Update_Folder_Async()
{
TestOutputLogger.LogContext("TestScenario", "UpdateFolderAsync");
try
{
// First create a folder if we don't have one
if (string.IsNullOrEmpty(_testFolderUid))
{
await Test014_Should_Create_Folder();
}
if (!string.IsNullOrEmpty(_testFolderUid))
{