-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathContentstack016_DeliveryTokenTest.cs
More file actions
2710 lines (2409 loc) · 115 KB
/
Copy pathContentstack016_DeliveryTokenTest.cs
File metadata and controls
2710 lines (2409 loc) · 115 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.Threading.Tasks;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Models.Token;
using Contentstack.Management.Core.Tests.Helpers;
using Contentstack.Management.Core.Tests.Model;
using Contentstack.Management.Core.Queryable;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Security.Cryptography;
using System.Net;
using Contentstack.Management.Core.Exceptions;
using System.Threading;
using System.Linq;
namespace Contentstack.Management.Core.Tests.IntegrationTest
{
[TestClass]
public class Contentstack016_DeliveryTokenTest
{
private static ContentstackClient _client;
private Stack _stack;
private string _deliveryTokenUid;
private string _testEnvironmentUid = "test_delivery_environment";
private DeliveryTokenModel _testTokenModel;
// Constants for error testing
private const string NonExistentTokenUid = "blt00000000000000000000";
private const string InvalidTokenUid = "invalid-uid-format";
private const string MalformedTokenUid = "!@#$%^&*()";
private const string NonExistentEnvironmentUid = "non_existent_environment";
private const string ExtremelyLongName = "This_is_an_extremely_long_delivery_token_name_that_exceeds_the_maximum_allowed_length_for_delivery_token_names_in_the_Contentstack_API_and_should_cause_a_validation_error_when_attempting_to_create_or_update_a_delivery_token_with_this_name_because_it_is_way_too_long_to_be_accepted_by_the_system_validation_rules_that_are_in_place_to_ensure_reasonable_naming_conventions_are_followed_across_all_resources_in_the_platform";
private const string InvalidCharactersName = "<script>alert('XSS')</script>";
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
_client = Contentstack.CreateAuthenticatedClient();
}
[ClassCleanup]
public static void ClassCleanup()
{
try { _client?.Logout(); } catch { }
_client = null;
}
[TestInitialize]
public async Task Initialize()
{
try
{
StackResponse response = StackResponse.getStack(_client.serializer);
_stack = _client.Stack(response.Stack.APIKey);
// Cleanup existing test resources first
await CleanupTestResources();
// Create unique environment name with timestamp
_testEnvironmentUid = $"test_delivery_environment_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}";
await CreateTestEnvironment();
_testTokenModel = new DeliveryTokenModel
{
Name = "Test Delivery Token",
Description = "Integration test delivery token",
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "environment",
Environments = new List<string> { _testEnvironmentUid },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
},
new DeliveryTokenScope
{
Module = "branch",
Branches = new List<string> { "main" },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
}
}
};
}
catch (Exception ex)
{
AssertLogger.Fail($"Initialize failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test001_Should_Create_Delivery_Token()
{
TestOutputLogger.LogContext("TestScenario", "Test001_Should_Create_Delivery_Token");
try
{
ContentstackResponse response = _stack.DeliveryToken().Create(_testTokenModel);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Create delivery token failed", "CreateDeliveryTokenSuccess");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["token"], "Response should contain token object");
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.IsNotNull(tokenData["uid"], "Token should have UID");
AssertLogger.AreEqual(_testTokenModel.Name, tokenData["name"]?.ToString(), "Token name should match", "TokenName");
AssertLogger.AreEqual(_testTokenModel.Description, tokenData["description"]?.ToString(), "Token description should match", "TokenDescription");
_deliveryTokenUid = tokenData["uid"]?.ToString();
AssertLogger.IsNotNull(_deliveryTokenUid, "Delivery token UID should not be null");
TestOutputLogger.LogContext("DeliveryTokenUid", _deliveryTokenUid ?? "");
Console.WriteLine($"Created delivery token with UID: {_deliveryTokenUid}");
}
catch (Exception ex)
{
AssertLogger.Fail("Create delivery token test failed", ex.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test002_Should_Create_Delivery_Token_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test002_Should_Create_Delivery_Token_Async");
try
{
var asyncTokenModel = new DeliveryTokenModel
{
Name = "Async Test Delivery Token",
Description = "Async integration test delivery token",
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "environment",
Environments = new List<string> { _testEnvironmentUid },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
},
new DeliveryTokenScope
{
Module = "branch",
Branches = new List<string> { "main" },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
}
}
};
ContentstackResponse response = await _stack.DeliveryToken().CreateAsync(asyncTokenModel);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Async create delivery token failed", "AsyncCreateSuccess");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["token"], "Response should contain token object");
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.IsNotNull(tokenData["uid"], "Token should have UID");
AssertLogger.AreEqual(asyncTokenModel.Name, tokenData["name"]?.ToString(), "Token name should match", "AsyncTokenName");
string asyncTokenUid = tokenData["uid"]?.ToString();
TestOutputLogger.LogContext("AsyncCreatedTokenUid", asyncTokenUid ?? "");
if (!string.IsNullOrEmpty(asyncTokenUid))
{
await _stack.DeliveryToken(asyncTokenUid).DeleteAsync();
}
}
catch (Exception ex)
{
AssertLogger.Fail("Async create delivery token test failed", ex.Message);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test003_Should_Fetch_Delivery_Token()
{
TestOutputLogger.LogContext("TestScenario", "Test003_Should_Fetch_Delivery_Token");
try
{
if (string.IsNullOrEmpty(_deliveryTokenUid))
{
await Test001_Should_Create_Delivery_Token();
}
TestOutputLogger.LogContext("DeliveryTokenUid", _deliveryTokenUid ?? "");
ContentstackResponse response = _stack.DeliveryToken(_deliveryTokenUid).Fetch();
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Fetch delivery token failed", "FetchSuccess");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["token"], "Response should contain token object");
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.AreEqual(_deliveryTokenUid, tokenData["uid"]?.ToString(), "Token UID should match", "TokenUid");
AssertLogger.AreEqual(_testTokenModel.Name, tokenData["name"]?.ToString(), "Token name should match", "TokenName");
AssertLogger.IsNotNull(tokenData["token"], "Token should have access token");
}
catch (Exception ex)
{
AssertLogger.Fail($"Fetch delivery token test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test004_Should_Fetch_Delivery_Token_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test004_Should_Fetch_Delivery_Token_Async");
try
{
if (string.IsNullOrEmpty(_deliveryTokenUid))
{
await Test001_Should_Create_Delivery_Token();
}
TestOutputLogger.LogContext("DeliveryTokenUid", _deliveryTokenUid ?? "");
ContentstackResponse response = await _stack.DeliveryToken(_deliveryTokenUid).FetchAsync();
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Async fetch delivery token failed", "AsyncFetchSuccess");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["token"], "Response should contain token object");
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.AreEqual(_deliveryTokenUid, tokenData["uid"]?.ToString(), "Token UID should match", "TokenUid");
AssertLogger.IsNotNull(tokenData["token"], "Token should have access token");
}
catch (Exception ex)
{
AssertLogger.Fail($"Async fetch delivery token test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test005_Should_Update_Delivery_Token()
{
TestOutputLogger.LogContext("TestScenario", "Test005_Should_Update_Delivery_Token");
try
{
if (string.IsNullOrEmpty(_deliveryTokenUid))
{
await Test001_Should_Create_Delivery_Token();
}
TestOutputLogger.LogContext("DeliveryTokenUid", _deliveryTokenUid ?? "");
var updateModel = new DeliveryTokenModel
{
Name = "Updated Test Delivery Token",
Description = "Updated integration test delivery token",
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "environment",
Environments = new List<string> { _testEnvironmentUid },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
},
new DeliveryTokenScope
{
Module = "branch",
Branches = new List<string> { "main" },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
}
}
};
ContentstackResponse response = _stack.DeliveryToken(_deliveryTokenUid).Update(updateModel);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Update delivery token failed", "UpdateSuccess");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["token"], "Response should contain token object");
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.AreEqual(_deliveryTokenUid, tokenData["uid"]?.ToString(), "Token UID should match", "TokenUid");
AssertLogger.AreEqual(updateModel.Name, tokenData["name"]?.ToString(), "Updated token name should match", "UpdatedTokenName");
AssertLogger.AreEqual(updateModel.Description, tokenData["description"]?.ToString(), "Updated token description should match", "UpdatedTokenDescription");
}
catch (Exception ex)
{
AssertLogger.Fail($"Update delivery token test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test006_Should_Update_Delivery_Token_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test006_Should_Update_Delivery_Token_Async");
try
{
if (string.IsNullOrEmpty(_deliveryTokenUid))
{
await Test001_Should_Create_Delivery_Token();
}
TestOutputLogger.LogContext("DeliveryTokenUid", _deliveryTokenUid ?? "");
var updateModel = new DeliveryTokenModel
{
Name = "Async Updated Test Delivery Token",
Description = "Async updated integration test delivery token",
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "environment",
Environments = new List<string> { _testEnvironmentUid },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
},
new DeliveryTokenScope
{
Module = "branch",
Branches = new List<string> { "main" },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
}
}
};
ContentstackResponse response = await _stack.DeliveryToken(_deliveryTokenUid).UpdateAsync(updateModel);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Async update delivery token failed", "AsyncUpdateSuccess");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["token"], "Response should contain token object");
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.AreEqual(_deliveryTokenUid, tokenData["uid"]?.ToString(), "Token UID should match", "TokenUid");
AssertLogger.AreEqual(updateModel.Name, tokenData["name"]?.ToString(), "Updated token name should match", "UpdatedTokenName");
}
catch (Exception ex)
{
AssertLogger.Fail($"Async update delivery token test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test007_Should_Query_All_Delivery_Tokens()
{
TestOutputLogger.LogContext("TestScenario", "Test007_Should_Query_All_Delivery_Tokens");
try
{
if (string.IsNullOrEmpty(_deliveryTokenUid))
{
await Test001_Should_Create_Delivery_Token();
}
TestOutputLogger.LogContext("DeliveryTokenUid", _deliveryTokenUid ?? "");
ContentstackResponse response = _stack.DeliveryToken().Query().Find();
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Query delivery tokens failed", "QuerySuccess");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["tokens"], "Response should contain tokens array");
var tokens = responseObject["tokens"] as JsonArray;
AssertLogger.IsTrue(tokens.Count > 0, "Should have at least one delivery token", "TokensCountGreaterThanZero");
bool foundTestToken = false;
foreach (var token in tokens)
{
if (token["uid"]?.ToString() == _deliveryTokenUid)
{
foundTestToken = true;
break;
}
}
AssertLogger.IsTrue(foundTestToken, "Test token should be found in query results", "TestTokenFoundInQuery");
}
catch (Exception ex)
{
AssertLogger.Fail($"Query delivery tokens test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test008_Should_Query_Delivery_Tokens_With_Parameters()
{
TestOutputLogger.LogContext("TestScenario", "Test008_Should_Query_Delivery_Tokens_With_Parameters");
try
{
if (string.IsNullOrEmpty(_deliveryTokenUid))
{
await Test001_Should_Create_Delivery_Token();
}
TestOutputLogger.LogContext("DeliveryTokenUid", _deliveryTokenUid ?? "");
var parameters = new ParameterCollection();
parameters.Add("limit", "5");
parameters.Add("skip", "0");
ContentstackResponse response = _stack.DeliveryToken().Query().Limit(5).Skip(0).Find();
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Query delivery tokens with parameters failed", "QueryWithParamsSuccess");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["tokens"], "Response should contain tokens array");
var tokens = responseObject["tokens"] as JsonArray;
AssertLogger.IsTrue(tokens.Count <= 5, "Should respect limit parameter", "RespectLimitParam");
}
catch (Exception ex)
{
AssertLogger.Fail($"Query delivery tokens with parameters test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test009_Should_Create_Token_With_Multiple_Environments()
{
TestOutputLogger.LogContext("TestScenario", "Test009_Should_Create_Token_With_Multiple_Environments");
try
{
string secondEnvironmentUid = $"test_delivery_environment_2_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}";
await CreateTestEnvironment(secondEnvironmentUid);
TestOutputLogger.LogContext("SecondEnvironmentUid", secondEnvironmentUid);
var multiEnvTokenModel = new DeliveryTokenModel
{
Name = "Multi Environment Delivery Token",
Description = "Token with multiple environment access",
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "environment",
Environments = new List<string> { _testEnvironmentUid, secondEnvironmentUid },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
},
new DeliveryTokenScope
{
Module = "branch",
Branches = new List<string> { "main" },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
}
}
};
ContentstackResponse response = _stack.DeliveryToken().Create(multiEnvTokenModel);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Create multi-environment delivery token failed", "MultiEnvCreateSuccess");
var responseObject = response.OpenJsonObjectResponse();
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.IsNotNull(tokenData["uid"], "Token should have UID");
string multiEnvTokenUid = tokenData["uid"]?.ToString();
TestOutputLogger.LogContext("MultiEnvTokenUid", multiEnvTokenUid ?? "");
var scope = tokenData["scope"] as JsonArray;
AssertLogger.IsNotNull(scope, "Token should have scope");
AssertLogger.IsTrue(scope.Count > 0, "Token should have at least one scope", "ScopeCount");
if (!string.IsNullOrEmpty(multiEnvTokenUid))
{
await _stack.DeliveryToken(multiEnvTokenUid).DeleteAsync();
}
await CleanupTestEnvironment(secondEnvironmentUid);
}
catch (Exception ex)
{
AssertLogger.Fail($"Multi-environment delivery token test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test011_Should_Create_Token_With_Complex_Scope()
{
TestOutputLogger.LogContext("TestScenario", "Test011_Should_Create_Token_With_Complex_Scope");
try
{
var complexScopeTokenModel = new DeliveryTokenModel
{
Name = "Complex Scope Delivery Token",
Description = "Token with complex scope configuration",
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "environment",
Environments = new List<string> { _testEnvironmentUid },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
},
new DeliveryTokenScope
{
Module = "branch",
Branches = new List<string> { "main" },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
}
}
};
ContentstackResponse response = _stack.DeliveryToken().Create(complexScopeTokenModel);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Create complex scope delivery token failed", "ComplexScopeCreateSuccess");
var responseObject = response.OpenJsonObjectResponse();
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.IsNotNull(tokenData["uid"], "Token should have UID");
string complexScopeTokenUid = tokenData["uid"]?.ToString();
TestOutputLogger.LogContext("ComplexScopeTokenUid", complexScopeTokenUid ?? "");
// Verify multiple scopes
var scope = tokenData["scope"] as JsonArray;
AssertLogger.IsNotNull(scope, "Token should have scope");
AssertLogger.IsTrue(scope.Count >= 2, "Token should have multiple scopes", "ScopeCountMultiple");
// Clean up the complex scope token
if (!string.IsNullOrEmpty(complexScopeTokenUid))
{
await _stack.DeliveryToken(complexScopeTokenUid).DeleteAsync();
}
}
catch (Exception ex)
{
AssertLogger.Fail($"Complex scope delivery token test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test012_Should_Create_Token_With_UI_Structure()
{
TestOutputLogger.LogContext("TestScenario", "Test012_Should_Create_Token_With_UI_Structure");
try
{
// Test with the exact structure from UI as provided by user
var uiStructureTokenModel = new DeliveryTokenModel
{
Name = "UI Structure Test Token",
Description = "", // Empty description as in UI example
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "environment",
ACL = new Dictionary<string, string>
{
{ "read", "true" }
},
Environments = new List<string> { _testEnvironmentUid }
},
new DeliveryTokenScope
{
Module = "branch",
ACL = new Dictionary<string, string>
{
{ "read", "true" }
},
Branches = new List<string> { "main" }
}
}
};
ContentstackResponse response = _stack.DeliveryToken().Create(uiStructureTokenModel);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Create UI structure delivery token failed", "UIStructureCreateSuccess");
var responseObject = response.OpenJsonObjectResponse();
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.IsNotNull(tokenData["uid"], "Token should have UID");
AssertLogger.AreEqual(uiStructureTokenModel.Name, tokenData["name"]?.ToString(), "Token name should match", "UITokenName");
// Verify the scope structure matches UI format
var scope = tokenData["scope"] as JsonArray;
AssertLogger.IsNotNull(scope, "Token should have scope");
AssertLogger.IsTrue(scope.Count == 2, "Token should have 2 scope modules (environment and branch)", "UIScopeCount");
string uiTokenUid = tokenData["uid"]?.ToString();
TestOutputLogger.LogContext("UITokenUid", uiTokenUid ?? "");
// Clean up the UI structure token
if (!string.IsNullOrEmpty(uiTokenUid))
{
await _stack.DeliveryToken(uiTokenUid).DeleteAsync();
}
}
catch (Exception ex)
{
AssertLogger.Fail($"UI structure delivery token test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test015_Should_Query_Delivery_Tokens_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test015_Should_Query_Delivery_Tokens_Async");
try
{
// Ensure we have at least one token
if (string.IsNullOrEmpty(_deliveryTokenUid))
{
await Test001_Should_Create_Delivery_Token();
}
TestOutputLogger.LogContext("DeliveryTokenUid", _deliveryTokenUid ?? "");
ContentstackResponse response = await _stack.DeliveryToken().Query().FindAsync();
AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Async query delivery tokens failed: {response.OpenResponse()}", "AsyncQuerySuccess");
var responseObject = response.OpenJsonObjectResponse();
AssertLogger.IsNotNull(responseObject["tokens"], "Response should contain tokens array");
var tokens = responseObject["tokens"] as JsonArray;
AssertLogger.IsTrue(tokens.Count > 0, "Should have at least one delivery token", "AsyncTokensCount");
bool foundTestToken = false;
foreach (var token in tokens)
{
if (token["uid"]?.ToString() == _deliveryTokenUid)
{
foundTestToken = true;
break;
}
}
AssertLogger.IsTrue(foundTestToken, "Test token should be found in async query results", "TestTokenFoundInAsyncQuery");
}
catch (Exception ex)
{
AssertLogger.Fail($"Async query delivery tokens test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test016_Should_Create_Token_With_Empty_Description()
{
TestOutputLogger.LogContext("TestScenario", "Test016_Should_Create_Token_With_Empty_Description");
try
{
var emptyDescTokenModel = new DeliveryTokenModel
{
Name = "Empty Description Token",
Description = "", // Empty description
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "environment",
Environments = new List<string> { _testEnvironmentUid },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
},
new DeliveryTokenScope
{
Module = "branch",
Branches = new List<string> { "main" },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
}
}
};
ContentstackResponse response = _stack.DeliveryToken().Create(emptyDescTokenModel);
AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Create token with empty description failed: {response.OpenResponse()}", "EmptyDescCreateSuccess");
var responseObject = response.OpenJsonObjectResponse();
var tokenData = responseObject["token"] as JsonObject;
AssertLogger.IsNotNull(tokenData["uid"], "Token should have UID");
AssertLogger.AreEqual(emptyDescTokenModel.Name, tokenData["name"]?.ToString(), "Token name should match", "EmptyDescTokenName");
string emptyDescTokenUid = tokenData["uid"]?.ToString();
TestOutputLogger.LogContext("EmptyDescTokenUid", emptyDescTokenUid ?? "");
// Clean up the empty description token
if (!string.IsNullOrEmpty(emptyDescTokenUid))
{
await _stack.DeliveryToken(emptyDescTokenUid).DeleteAsync();
}
}
catch (Exception ex)
{
AssertLogger.Fail($"Empty description token test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test017_Should_Validate_Environment_Scope_Requirement()
{
TestOutputLogger.LogContext("TestScenario", "Test017_Should_Validate_Environment_Scope_Requirement");
try
{
// Test that environment-only scope is rejected by API
var envOnlyTokenModel = new DeliveryTokenModel
{
Name = "Environment Only Token",
Description = "Token with only environment scope - should fail",
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "environment",
Environments = new List<string> { _testEnvironmentUid },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
}
}
};
ContentstackResponse response;
try
{
response = _stack.DeliveryToken().Create(envOnlyTokenModel);
}
catch (Exception ex)
{
// If an exception is thrown, that's also acceptable - the API rejected the request
Console.WriteLine($"Environment-only token creation threw exception (expected): {ex.Message}");
return; // Test passes if exception is thrown
}
// If no exception was thrown, check the response status
AssertLogger.IsFalse(response.IsSuccessStatusCode, "Environment-only token should be rejected by API", "EnvOnlyRejected");
AssertLogger.IsTrue(response.StatusCode == System.Net.HttpStatusCode.BadRequest ||
response.StatusCode == System.Net.HttpStatusCode.UnprocessableEntity,
$"Expected 400 or 422 for environment-only token, got {response.StatusCode}", "Expected400Or422");
}
catch (Exception ex)
{
AssertLogger.Fail($"Environment scope validation test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test018_Should_Validate_Branch_Scope_Requirement()
{
TestOutputLogger.LogContext("TestScenario", "Test018_Should_Validate_Branch_Scope_Requirement");
try
{
// Test that branch-only scope is rejected by API
var branchOnlyTokenModel = new DeliveryTokenModel
{
Name = "Branch Only Token",
Description = "Token with only branch scope - should fail",
Scope = new List<DeliveryTokenScope>
{
new DeliveryTokenScope
{
Module = "branch",
Branches = new List<string> { "main" },
ACL = new Dictionary<string, string>
{
{ "read", "true" }
}
}
}
};
ContentstackResponse response;
try
{
response = _stack.DeliveryToken().Create(branchOnlyTokenModel);
}
catch (Exception ex)
{
// If an exception is thrown, that's also acceptable - the API rejected the request
Console.WriteLine($"Branch-only token creation threw exception (expected): {ex.Message}");
return; // Test passes if exception is thrown
}
// If no exception was thrown, check the response status
AssertLogger.IsFalse(response.IsSuccessStatusCode, "Branch-only token should be rejected by API", "BranchOnlyRejected");
AssertLogger.IsTrue(response.StatusCode == System.Net.HttpStatusCode.BadRequest ||
response.StatusCode == System.Net.HttpStatusCode.UnprocessableEntity,
$"Expected 400 or 422 for branch-only token, got {response.StatusCode}", "Expected400Or422");
}
catch (Exception ex)
{
AssertLogger.Fail($"Branch scope validation test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test019_Should_Delete_Delivery_Token()
{
TestOutputLogger.LogContext("TestScenario", "Test019_Should_Delete_Delivery_Token");
try
{
// Ensure we have a token to delete
if (string.IsNullOrEmpty(_deliveryTokenUid))
{
await Test001_Should_Create_Delivery_Token();
}
string tokenUidToDelete = _deliveryTokenUid;
AssertLogger.IsNotNull(tokenUidToDelete, "Should have a valid token UID to delete");
TestOutputLogger.LogContext("TokenUidToDelete", tokenUidToDelete ?? "");
// Test synchronous delete
ContentstackResponse response = _stack.DeliveryToken(tokenUidToDelete).Delete();
AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Delete delivery token failed: {response.OpenResponse()}", "DeleteSuccess");
// Verify token is deleted by trying to fetch it
try
{
ContentstackResponse fetchResponse = _stack.DeliveryToken(tokenUidToDelete).Fetch();
AssertLogger.IsFalse(fetchResponse.IsSuccessStatusCode, "Deleted token should not be fetchable", "DeletedTokenNotFetchable");
// Verify the response indicates the token was not found
AssertLogger.IsTrue(fetchResponse.StatusCode == System.Net.HttpStatusCode.NotFound ||
fetchResponse.StatusCode == System.Net.HttpStatusCode.UnprocessableEntity ||
fetchResponse.StatusCode == System.Net.HttpStatusCode.BadRequest,
$"Expected 404, 422, or 400 for deleted token fetch, got {fetchResponse.StatusCode}", "Expected404Or422Or400");
}
catch (Exception ex)
{
// Expected behavior - deleted token should throw exception when fetched
Console.WriteLine($"Expected exception when fetching deleted token: {ex.Message}");
}
_deliveryTokenUid = null;
}
catch (Exception ex)
{
AssertLogger.Fail("Delete delivery token test failed", ex.Message);
}
}
#region A — Create Operation Error Tests (Test020-Test039)
[TestMethod]
[DoNotParallelize]
public void Test020_Should_Fail_Create_With_Null_Model()
{
TestOutputLogger.LogContext("TestScenario", "Test020_Should_Fail_Create_With_Null_Model");
AssertLogger.ThrowsException<ArgumentNullException>(
() => _stack.DeliveryToken().Create(null),
"CreateWithNullModel");
}
[TestMethod]
[DoNotParallelize]
public void Test021_Should_Fail_Create_With_Null_Name()
{
TestOutputLogger.LogContext("TestScenario", "Test021_Should_Fail_Create_With_Null_Name");
var model = BuildInvalidTokenModel("null_name");
AssertLogger.ThrowsContentstackError(
() => _stack.DeliveryToken().Create(model),
"CreateWithNullName",
HttpStatusCode.BadRequest,
(HttpStatusCode)422);
}
[TestMethod]
[DoNotParallelize]
public void Test022_Should_Fail_Create_With_Empty_Name()
{
TestOutputLogger.LogContext("TestScenario", "Test022_Should_Fail_Create_With_Empty_Name");
var model = BuildInvalidTokenModel("empty_name");
AssertLogger.ThrowsContentstackError(
() => _stack.DeliveryToken().Create(model),
"CreateWithEmptyName",
HttpStatusCode.BadRequest,
(HttpStatusCode)422);
}
[TestMethod]
[DoNotParallelize]
public void Test023_Should_Accept_Create_With_Whitespace_Only_Name()
{
TestOutputLogger.LogContext("TestScenario", "Test023_Should_Accept_Create_With_Whitespace_Only_Name");
try
{
// Use dynamic whitespace name to avoid conflicts
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var model = new DeliveryTokenModel
{
Name = $" \t\r\n {timestamp} \t\r\n ", // Whitespace + unique identifier
Description = "Test token with whitespace name",
Scope = BuildValidScope(_testEnvironmentUid)
};
ContentstackResponse response = _stack.DeliveryToken().Create(model);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Should accept token with whitespace name");
// Get token UID for cleanup
var responseObject = response.OpenJsonObjectResponse();
var tokenData = responseObject["token"] as JsonObject;
string createdTokenUid = tokenData["uid"]?.ToString();
// Verify name contains whitespace
AssertLogger.IsTrue(model.Name.Trim() != model.Name, "Name should contain whitespace");
// Clean up
if (!string.IsNullOrEmpty(createdTokenUid))
{
try { _stack.DeliveryToken(createdTokenUid).Delete(); } catch { }
}
}
catch (Exception ex)
{
AssertLogger.Fail($"Test failed: {ex.Message}");
}
}
[TestMethod]
[DoNotParallelize]
public void Test024_Should_Fail_Create_With_Extremely_Long_Name()
{
TestOutputLogger.LogContext("TestScenario", "Test024_Should_Fail_Create_With_Extremely_Long_Name");
var model = BuildInvalidTokenModel("long_name");
AssertLogger.ThrowsContentstackError(
() => _stack.DeliveryToken().Create(model),
"CreateWithExtremelyLongName",
HttpStatusCode.BadRequest,
(HttpStatusCode)422);
}
[TestMethod]
[DoNotParallelize]
public void Test025_Should_Accept_Create_With_Invalid_Name_Characters()
{
TestOutputLogger.LogContext("TestScenario", "Test025_Should_Accept_Create_With_Invalid_Name_Characters");
try
{
// Use dynamic name with special characters to avoid conflicts
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var model = new DeliveryTokenModel
{
Name = $"<script>alert('{timestamp}')</script>", // XSS + unique identifier
Description = "Test token with invalid characters in name",
Scope = BuildValidScope(_testEnvironmentUid)
};
ContentstackResponse response = _stack.DeliveryToken().Create(model);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Should accept token with special characters");