-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathContentstack019_RoleTest.cs
More file actions
2891 lines (2564 loc) · 123 KB
/
Copy pathContentstack019_RoleTest.cs
File metadata and controls
2891 lines (2564 loc) · 123 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.Linq;
using System.Net;
using System.Threading.Tasks;
using Contentstack.Management.Core.Exceptions;
using Contentstack.Management.Core.Models;
using Contentstack.Management.Core.Tests.Helpers;
using Contentstack.Management.Core.Tests.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text.Json.Nodes;
namespace Contentstack.Management.Core.Tests.IntegrationTest
{
[TestClass]
[DoNotParallelize]
public class Contentstack019_RoleTest
{
/// <summary>
/// UID that should not exist on any stack (for negative-path tests).
/// </summary>
private const string NonExistentRoleUid = "blt0000000000000000";
private static ContentstackClient _client;
private Stack _stack;
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
_client = Contentstack.CreateAuthenticatedClient();
}
[ClassCleanup]
public static void ClassCleanup()
{
try { _client?.Logout(); } catch { }
_client = null;
}
[TestInitialize]
public void Initialize()
{
StackResponse response = StackResponse.getStack(_client.serializer);
_stack = _client.Stack(response.Stack.APIKey);
}
/// <summary>
/// Minimal role payload: branch rule on default branch "main".
/// </summary>
private static RoleModel BuildMinimalRoleModel(string uniqueName)
{
return new RoleModel
{
Name = uniqueName,
Description = "Integration test role",
DeployContent = true,
Rules = new List<Rule>
{
new BranchRules
{
Branches = new List<string> { "main" }
}
}
};
}
private static string ParseRoleUid(ContentstackResponse response)
{
var jo = response.OpenJsonObjectResponse();
return jo?["role"]?["uid"]?.ToString();
}
private void SafeDelete(string roleUid)
{
if (string.IsNullOrEmpty(roleUid))
{
return;
}
try
{
_stack.Role(roleUid).Delete();
}
catch
{
// Best-effort cleanup; ignore if already deleted or API error
}
}
private static bool RolesArrayContainsUid(JsonArray roles, string uid)
{
if (roles == null || string.IsNullOrEmpty(uid))
{
return false;
}
return roles.Any(r => r["uid"]?.ToString() == uid);
}
/// <summary>
/// Creates invalid role model for testing specific validation scenarios.
/// Uses scenario-based approach for systematic negative testing.
/// </summary>
private static RoleModel CreateInvalidRoleModel(string scenario)
{
switch (scenario)
{
case "null_name":
return new RoleModel
{
Name = null,
Description = "Test role with null name",
DeployContent = true,
Rules = new List<Rule>
{
new BranchRules { Branches = new List<string> { "main" } }
}
};
case "empty_name":
return new RoleModel
{
Name = "",
Description = "Test role with empty name",
DeployContent = true,
Rules = new List<Rule>
{
new BranchRules { Branches = new List<string> { "main" } }
}
};
case "whitespace_name":
return new RoleModel
{
Name = " ",
Description = "Test role with whitespace-only name",
DeployContent = true,
Rules = new List<Rule>
{
new BranchRules { Branches = new List<string> { "main" } }
}
};
case "long_name":
return new RoleModel
{
Name = new string('a', 1000),
Description = "Test role with extremely long name",
DeployContent = true,
Rules = new List<Rule>
{
new BranchRules { Branches = new List<string> { "main" } }
}
};
case "special_chars":
return new RoleModel
{
Name = "role<>test&name",
Description = "Test role with special characters in name",
DeployContent = true,
Rules = new List<Rule>
{
new BranchRules { Branches = new List<string> { "main" } }
}
};
case "null_rules":
return new RoleModel
{
Name = $"role_null_rules_{Guid.NewGuid():N}",
Description = "Test role with null rules",
DeployContent = true,
Rules = null
};
case "empty_rules":
return new RoleModel
{
Name = $"role_empty_rules_{Guid.NewGuid():N}",
Description = "Test role with empty rules list",
DeployContent = true,
Rules = new List<Rule>()
};
case "empty_branches":
return new RoleModel
{
Name = $"role_empty_branches_{Guid.NewGuid():N}",
Description = "Test role with empty branches",
DeployContent = true,
Rules = new List<Rule>
{
new BranchRules { Branches = new List<string>() }
}
};
case "nonexistent_branch":
return new RoleModel
{
Name = $"role_nonexistent_branch_{Guid.NewGuid():N}",
Description = "Test role with non-existent branch",
DeployContent = true,
Rules = new List<Rule>
{
new BranchRules { Branches = new List<string> { "blt_fake_branch_uid" } }
}
};
case "invalid_content_types":
return new RoleModel
{
Name = $"role_invalid_ct_{Guid.NewGuid():N}",
Description = "Test role with invalid content type rules",
DeployContent = true,
Rules = new List<Rule>
{
new ContentTypeRules { ContentTypes = new List<string> { "invalid_content_type_uid" } }
}
};
case "invalid_environments":
return new RoleModel
{
Name = $"role_invalid_env_{Guid.NewGuid():N}",
Description = "Test role with invalid environment rules",
DeployContent = true,
Rules = new List<Rule>
{
new EnvironmentRules { Environments = new List<string> { "invalid_environment_uid" } }
}
};
case "conflicting_rules":
return new RoleModel
{
Name = $"role_conflicting_{Guid.NewGuid():N}",
Description = "Test role with conflicting rule types",
DeployContent = true,
Rules = new List<Rule>
{
new BranchRules { Branches = new List<string> { "main" } },
new BranchRules { Branches = new List<string> { "develop" } }
}
};
default:
throw new ArgumentException($"Unknown scenario: {scenario}");
}
}
/// <summary>
/// Asserts that the HTTP status code indicates a validation error (4xx range).
/// </summary>
private static void AssertValidationError(HttpStatusCode statusCode, string assertionName)
{
AssertLogger.IsTrue(
(int)statusCode >= 400 && (int)statusCode < 500,
$"Expected 4xx status code for validation error, got {(int)statusCode} ({statusCode})",
assertionName);
}
/// <summary>
/// Asserts that the exception indicates an authentication/authorization error.
/// </summary>
private static void AssertAuthenticationError(Exception ex, string assertionName)
{
AssertLogger.IsNotNull(ex, assertionName);
if (ex is ContentstackErrorException cex)
{
AssertLogger.IsTrue(
cex.StatusCode == HttpStatusCode.Unauthorized || cex.StatusCode == HttpStatusCode.Forbidden,
$"Expected 401/403 for auth error, got {(int)cex.StatusCode} ({cex.StatusCode})",
assertionName);
}
else
{
AssertLogger.Fail($"Expected ContentstackErrorException for auth error, got {ex.GetType().Name}: {ex.Message}", assertionName);
}
}
/// <summary>
/// Provides detailed error information when operations fail unexpectedly.
/// </summary>
private static void FailWithError(string operation, Exception ex)
{
string errorDetails = "Unknown error";
if (ex is ContentstackErrorException cex)
{
errorDetails = $"HTTP {(int)cex.StatusCode} ({cex.StatusCode}). " +
$"ErrorCode: {cex.ErrorCode}. " +
$"Message: {cex.ErrorMessage}";
if (cex.Errors != null && cex.Errors.Count > 0)
{
var errors = string.Join(", ", cex.Errors.Select(kvp => $"{kvp.Key}: {kvp.Value}"));
errorDetails += $". Errors: {errors}";
}
}
else
{
errorDetails = $"{ex.GetType().Name}: {ex.Message}";
}
AssertLogger.Fail($"{operation} failed: {errorDetails}", "UnexpectedFailure");
}
#region A — Sync happy path
[TestMethod]
public void Test001_Should_Create_Role_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test001_Should_Create_Role_Sync");
string roleUid = null;
string name = $"role_sync_create_{Guid.NewGuid():N}";
try
{
var model = BuildMinimalRoleModel(name);
ContentstackResponse response = _stack.Role().Create(model);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "Create role should succeed", "CreateSyncSuccess");
roleUid = ParseRoleUid(response);
AssertLogger.IsNotNull(roleUid, "role uid");
var jo = response.OpenJsonObjectResponse();
AssertLogger.AreEqual(name, jo["role"]?["name"]?.ToString(), "Response name should match", "RoleName");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
public void Test002_Should_Fetch_Role_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test002_Should_Fetch_Role_Sync");
string roleUid = null;
string name = $"role_sync_fetch_{Guid.NewGuid():N}";
try
{
ContentstackResponse createResponse = _stack.Role().Create(BuildMinimalRoleModel(name));
AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, "Create should succeed", "CreateForFetch");
roleUid = ParseRoleUid(createResponse);
AssertLogger.IsNotNull(roleUid, "uid after create");
ContentstackResponse fetchResponse = _stack.Role(roleUid).Fetch();
AssertLogger.IsTrue(fetchResponse.IsSuccessStatusCode, "Fetch should succeed", "FetchSyncSuccess");
var role = fetchResponse.OpenJsonObjectResponse()?["role"];
AssertLogger.AreEqual(name, role?["name"]?.ToString(), "Fetched name should match", "FetchedName");
AssertLogger.AreEqual(roleUid, role?["uid"]?.ToString(), "Fetched uid should match", "FetchedUid");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
public void Test003_Should_Query_Roles_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test003_Should_Query_Roles_Sync");
string roleUid = null;
string name = $"role_sync_query_{Guid.NewGuid():N}";
try
{
ContentstackResponse createResponse = _stack.Role().Create(BuildMinimalRoleModel(name));
AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, "Create should succeed", "CreateForQuery");
roleUid = ParseRoleUid(createResponse);
AssertLogger.IsNotNull(roleUid, "uid after create");
ContentstackResponse queryResponse = _stack.Role().Query().Find();
AssertLogger.IsTrue(queryResponse.IsSuccessStatusCode, "Query Find should succeed", "QueryFindSuccess");
var roles = queryResponse.OpenJsonObjectResponse()?["roles"] as JsonArray;
AssertLogger.IsNotNull(roles, "roles array");
AssertLogger.IsTrue(
RolesArrayContainsUid(roles, roleUid),
"Query result should contain created role uid",
"ContainsUid");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
public void Test004_Should_Update_Role_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test004_Should_Update_Role_Sync");
string roleUid = null;
string originalName = $"role_sync_update_{Guid.NewGuid():N}";
string updatedName = $"{originalName}_updated";
try
{
ContentstackResponse createResponse = _stack.Role().Create(BuildMinimalRoleModel(originalName));
AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, "Create should succeed", "CreateForUpdate");
roleUid = ParseRoleUid(createResponse);
AssertLogger.IsNotNull(roleUid, "uid after create");
var updateModel = BuildMinimalRoleModel(updatedName);
ContentstackResponse updateResponse = _stack.Role(roleUid).Update(updateModel);
AssertLogger.IsTrue(updateResponse.IsSuccessStatusCode, "Update should succeed", "UpdateSyncSuccess");
ContentstackResponse fetchResponse = _stack.Role(roleUid).Fetch();
AssertLogger.IsTrue(fetchResponse.IsSuccessStatusCode, "Fetch after update should succeed", "FetchAfterUpdate");
var role = fetchResponse.OpenJsonObjectResponse()?["role"];
AssertLogger.AreEqual(updatedName, role?["name"]?.ToString(), "Name should reflect update", "UpdatedName");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
public void Test005_Should_Delete_Role_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test005_Should_Delete_Role_Sync");
string roleUid = null;
string name = $"role_sync_delete_{Guid.NewGuid():N}";
try
{
ContentstackResponse createResponse = _stack.Role().Create(BuildMinimalRoleModel(name));
AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, "Create should succeed", "CreateForDelete");
roleUid = ParseRoleUid(createResponse);
AssertLogger.IsNotNull(roleUid, "uid after create");
ContentstackResponse deleteResponse = _stack.Role(roleUid).Delete();
AssertLogger.IsTrue(deleteResponse.IsSuccessStatusCode, "Delete should succeed", "DeleteSyncSuccess");
AssertLogger.ThrowsContentstackError(
() => _stack.Role(roleUid).Fetch(),
"FetchAfterDelete",
HttpStatusCode.NotFound,
(HttpStatusCode)422);
roleUid = null;
}
finally
{
SafeDelete(roleUid);
}
}
#endregion
#region B — Async happy path
[TestMethod]
public async Task Test006_Should_Create_Role_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test006_Should_Create_Role_Async");
string roleUid = null;
string name = $"role_async_create_{Guid.NewGuid():N}";
try
{
var model = BuildMinimalRoleModel(name);
ContentstackResponse response = await _stack.Role().CreateAsync(model);
AssertLogger.IsTrue(response.IsSuccessStatusCode, "CreateAsync should succeed", "CreateAsyncSuccess");
roleUid = ParseRoleUid(response);
AssertLogger.IsNotNull(roleUid, "role uid");
var jo = response.OpenJsonObjectResponse();
AssertLogger.AreEqual(name, jo["role"]?["name"]?.ToString(), "Response name should match", "RoleName");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
public async Task Test007_Should_Fetch_Role_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test007_Should_Fetch_Role_Async");
string roleUid = null;
string name = $"role_async_fetch_{Guid.NewGuid():N}";
try
{
ContentstackResponse createResponse = await _stack.Role().CreateAsync(BuildMinimalRoleModel(name));
AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, "Create should succeed", "CreateForFetchAsync");
roleUid = ParseRoleUid(createResponse);
AssertLogger.IsNotNull(roleUid, "uid after create");
ContentstackResponse fetchResponse = await _stack.Role(roleUid).FetchAsync();
AssertLogger.IsTrue(fetchResponse.IsSuccessStatusCode, "FetchAsync should succeed", "FetchAsyncSuccess");
var role = fetchResponse.OpenJsonObjectResponse()?["role"];
AssertLogger.AreEqual(name, role?["name"]?.ToString(), "Fetched name should match", "FetchedName");
AssertLogger.AreEqual(roleUid, role?["uid"]?.ToString(), "Fetched uid should match", "FetchedUid");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
public async Task Test008_Should_Query_Roles_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test008_Should_Query_Roles_Async");
string roleUid = null;
string name = $"role_async_query_{Guid.NewGuid():N}";
try
{
ContentstackResponse createResponse = await _stack.Role().CreateAsync(BuildMinimalRoleModel(name));
AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, "Create should succeed", "CreateForQueryAsync");
roleUid = ParseRoleUid(createResponse);
AssertLogger.IsNotNull(roleUid, "uid after create");
ContentstackResponse queryResponse = await _stack.Role().Query().FindAsync();
AssertLogger.IsTrue(queryResponse.IsSuccessStatusCode, "Query FindAsync should succeed", "QueryFindAsyncSuccess");
var roles = queryResponse.OpenJsonObjectResponse()?["roles"] as JsonArray;
AssertLogger.IsNotNull(roles, "roles array");
AssertLogger.IsTrue(
RolesArrayContainsUid(roles, roleUid),
"Query result should contain created role uid",
"ContainsUid");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
public async Task Test009_Should_Update_Role_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test009_Should_Update_Role_Async");
string roleUid = null;
string originalName = $"role_async_update_{Guid.NewGuid():N}";
string updatedName = $"{originalName}_updated";
try
{
ContentstackResponse createResponse = await _stack.Role().CreateAsync(BuildMinimalRoleModel(originalName));
AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, "Create should succeed", "CreateForUpdateAsync");
roleUid = ParseRoleUid(createResponse);
AssertLogger.IsNotNull(roleUid, "uid after create");
var updateModel = BuildMinimalRoleModel(updatedName);
ContentstackResponse updateResponse = await _stack.Role(roleUid).UpdateAsync(updateModel);
AssertLogger.IsTrue(updateResponse.IsSuccessStatusCode, "UpdateAsync should succeed", "UpdateAsyncSuccess");
ContentstackResponse fetchResponse = await _stack.Role(roleUid).FetchAsync();
AssertLogger.IsTrue(fetchResponse.IsSuccessStatusCode, "FetchAsync after update should succeed", "FetchAsyncAfterUpdate");
var role = fetchResponse.OpenJsonObjectResponse()?["role"];
AssertLogger.AreEqual(updatedName, role?["name"]?.ToString(), "Name should reflect update", "UpdatedName");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
public async Task Test010_Should_Delete_Role_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test010_Should_Delete_Role_Async");
string roleUid = null;
string name = $"role_async_delete_{Guid.NewGuid():N}";
try
{
ContentstackResponse createResponse = await _stack.Role().CreateAsync(BuildMinimalRoleModel(name));
AssertLogger.IsTrue(createResponse.IsSuccessStatusCode, "Create should succeed", "CreateForDeleteAsync");
roleUid = ParseRoleUid(createResponse);
AssertLogger.IsNotNull(roleUid, "uid after create");
ContentstackResponse deleteResponse = await _stack.Role(roleUid).DeleteAsync();
AssertLogger.IsTrue(deleteResponse.IsSuccessStatusCode, "DeleteAsync should succeed", "DeleteAsyncSuccess");
await AssertLogger.ThrowsContentstackErrorAsync(
async () => await _stack.Role(roleUid).FetchAsync(),
"FetchAsyncAfterDelete",
HttpStatusCode.NotFound,
(HttpStatusCode)422);
roleUid = null;
}
finally
{
SafeDelete(roleUid);
}
}
#endregion
#region C — Sync negative path
[TestMethod]
public void Test011_Should_Fail_Fetch_NonExistent_Role_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test011_Should_Fail_Fetch_NonExistent_Role_Sync");
AssertLogger.ThrowsContentstackError(
() => _stack.Role(NonExistentRoleUid).Fetch(),
"FetchNonExistentSync",
HttpStatusCode.NotFound,
(HttpStatusCode)422);
}
[TestMethod]
public void Test012_Should_Fail_Update_NonExistent_Role_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test012_Should_Fail_Update_NonExistent_Role_Sync");
var model = BuildMinimalRoleModel($"role_nonexistent_update_{Guid.NewGuid():N}");
AssertLogger.ThrowsContentstackError(
() => _stack.Role(NonExistentRoleUid).Update(model),
"UpdateNonExistentSync",
HttpStatusCode.NotFound,
(HttpStatusCode)422);
}
[TestMethod]
public void Test013_Should_Fail_Delete_NonExistent_Role_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test013_Should_Fail_Delete_NonExistent_Role_Sync");
AssertLogger.ThrowsContentstackError(
() => _stack.Role(NonExistentRoleUid).Delete(),
"DeleteNonExistentSync",
HttpStatusCode.NotFound,
(HttpStatusCode)422);
}
#endregion
#region D — Async negative path
[TestMethod]
public async Task Test014_Should_Fail_Fetch_NonExistent_Role_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test014_Should_Fail_Fetch_NonExistent_Role_Async");
await AssertLogger.ThrowsContentstackErrorAsync(
async () => await _stack.Role(NonExistentRoleUid).FetchAsync(),
"FetchNonExistentAsync",
HttpStatusCode.NotFound,
(HttpStatusCode)422);
}
[TestMethod]
public async Task Test015_Should_Fail_Update_NonExistent_Role_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test015_Should_Fail_Update_NonExistent_Role_Async");
var model = BuildMinimalRoleModel($"role_nonexistent_update_async_{Guid.NewGuid():N}");
await AssertLogger.ThrowsContentstackErrorAsync(
async () => await _stack.Role(NonExistentRoleUid).UpdateAsync(model),
"UpdateNonExistentAsync",
HttpStatusCode.NotFound,
(HttpStatusCode)422);
}
[TestMethod]
public async Task Test016_Should_Fail_Delete_NonExistent_Role_Async()
{
TestOutputLogger.LogContext("TestScenario", "Test016_Should_Fail_Delete_NonExistent_Role_Async");
await AssertLogger.ThrowsContentstackErrorAsync(
async () => await _stack.Role(NonExistentRoleUid).DeleteAsync(),
"DeleteNonExistentAsync",
HttpStatusCode.NotFound,
(HttpStatusCode)422);
}
#endregion
#region E — Role Creation Validation Tests (Sync)
[TestMethod]
[DoNotParallelize]
public void Test017_Should_Fail_Create_Role_With_Null_Name_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test017_Should_Fail_Create_Role_With_Null_Name_Sync");
try
{
var model = CreateInvalidRoleModel("null_name");
ContentstackResponse response = _stack.Role().Create(model);
if (!response.IsSuccessStatusCode)
{
AssertValidationError(response.StatusCode, "CreateRoleWithNullName");
}
else
{
// If API accepts null name, clean up and document the behavior
var roleUid = ParseRoleUid(response);
SafeDelete(roleUid);
AssertLogger.Fail("Expected validation error for null name, but API accepted it", "NullNameAccepted");
}
}
catch (ContentstackErrorException cex)
{
AssertValidationError(cex.StatusCode, "CreateRoleWithNullNameException");
}
}
[TestMethod]
[DoNotParallelize]
public void Test018_Should_Fail_Create_Role_With_Empty_Name_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test018_Should_Fail_Create_Role_With_Empty_Name_Sync");
try
{
var model = CreateInvalidRoleModel("empty_name");
ContentstackResponse response = _stack.Role().Create(model);
if (!response.IsSuccessStatusCode)
{
AssertValidationError(response.StatusCode, "CreateRoleWithEmptyName");
}
else
{
var roleUid = ParseRoleUid(response);
SafeDelete(roleUid);
AssertLogger.Fail("Expected validation error for empty name, but API accepted it", "EmptyNameAccepted");
}
}
catch (ContentstackErrorException cex)
{
AssertValidationError(cex.StatusCode, "CreateRoleWithEmptyNameException");
}
}
[TestMethod]
[DoNotParallelize]
public void Test019_Should_Accept_Create_Role_With_Whitespace_Only_Name_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test019_Should_Accept_Create_Role_With_Whitespace_Only_Name_Sync");
string roleUid = null;
try
{
var model = CreateInvalidRoleModel("whitespace_name");
ContentstackResponse response = _stack.Role().Create(model);
// Test API permissiveness - document actual behavior
if (response.IsSuccessStatusCode)
{
roleUid = ParseRoleUid(response);
AssertLogger.IsNotNull(roleUid, "WhitespaceNameAccepted");
}
else
{
AssertValidationError(response.StatusCode, "CreateRoleWithWhitespaceName");
}
}
catch (ContentstackErrorException cex)
{
AssertValidationError(cex.StatusCode, "CreateRoleWithWhitespaceNameException");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
[DoNotParallelize]
public void Test020_Should_Fail_Create_Role_With_Extremely_Long_Name_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test020_Should_Fail_Create_Role_With_Extremely_Long_Name_Sync");
try
{
var model = CreateInvalidRoleModel("long_name");
ContentstackResponse response = _stack.Role().Create(model);
if (!response.IsSuccessStatusCode)
{
AssertValidationError(response.StatusCode, "CreateRoleWithLongName");
}
else
{
var roleUid = ParseRoleUid(response);
SafeDelete(roleUid);
AssertLogger.Fail("Expected validation error for extremely long name, but API accepted it", "LongNameAccepted");
}
}
catch (ContentstackErrorException cex)
{
AssertValidationError(cex.StatusCode, "CreateRoleWithLongNameException");
}
}
[TestMethod]
[DoNotParallelize]
public void Test021_Should_Accept_Create_Role_With_Special_Characters_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test021_Should_Accept_Create_Role_With_Special_Characters_Sync");
string roleUid = null;
try
{
var model = CreateInvalidRoleModel("special_chars");
ContentstackResponse response = _stack.Role().Create(model);
// Test API behavior with special characters
if (response.IsSuccessStatusCode)
{
roleUid = ParseRoleUid(response);
AssertLogger.IsNotNull(roleUid, "SpecialCharsAccepted");
}
else
{
AssertValidationError(response.StatusCode, "CreateRoleWithSpecialChars");
}
}
catch (ContentstackErrorException cex)
{
AssertValidationError(cex.StatusCode, "CreateRoleWithSpecialCharsException");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
[DoNotParallelize]
public void Test022_Should_Fail_Create_Role_With_Duplicate_Name_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test022_Should_Fail_Create_Role_With_Duplicate_Name_Sync");
string firstRoleUid = null;
string duplicateName = $"role_duplicate_test_{Guid.NewGuid():N}";
try
{
// Create first role with unique name
var firstModel = BuildMinimalRoleModel(duplicateName);
ContentstackResponse firstResponse = _stack.Role().Create(firstModel);
AssertLogger.IsTrue(firstResponse.IsSuccessStatusCode, "First role creation should succeed", "FirstRoleSuccess");
firstRoleUid = ParseRoleUid(firstResponse);
// Attempt to create second role with same name
var duplicateModel = BuildMinimalRoleModel(duplicateName);
ContentstackResponse duplicateResponse = _stack.Role().Create(duplicateModel);
if (!duplicateResponse.IsSuccessStatusCode)
{
AssertLogger.IsTrue(
duplicateResponse.StatusCode == HttpStatusCode.Conflict ||
duplicateResponse.StatusCode == (HttpStatusCode)422,
"Expected 409 Conflict or 422 for duplicate name",
"DuplicateNameRejected");
}
else
{
// If API allows duplicates, clean up both
var duplicateUid = ParseRoleUid(duplicateResponse);
SafeDelete(duplicateUid);
AssertLogger.Fail("Expected conflict error for duplicate name, but API accepted it", "DuplicateNameAccepted");
}
}
catch (ContentstackErrorException cex)
{
AssertLogger.IsTrue(
cex.StatusCode == HttpStatusCode.Conflict || cex.StatusCode == (HttpStatusCode)422,
"Expected 409 or 422 for duplicate name exception",
"DuplicateNameException");
}
finally
{
SafeDelete(firstRoleUid);
}
}
[TestMethod]
[DoNotParallelize]
public void Test023_Should_Accept_Create_Role_With_Null_Rules_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test023_Should_Accept_Create_Role_With_Null_Rules_Sync");
string roleUid = null;
try
{
var model = CreateInvalidRoleModel("null_rules");
ContentstackResponse response = _stack.Role().Create(model);
// API accepts null rules and adds default rules
if (response.IsSuccessStatusCode)
{
roleUid = ParseRoleUid(response);
AssertLogger.IsNotNull(roleUid, "NullRulesAccepted");
// Verify API accepted the request - detailed rule validation is optional
var responseContent = response.OpenJsonObjectResponse();
if (responseContent?["role"] != null)
{
var role = responseContent["role"];
var rules = role["rules"] as JsonArray;
if (rules != null && rules.Count > 0)
{
AssertLogger.IsTrue(true, "DefaultRulesAdded");
}
else
{
AssertLogger.IsTrue(true, "NullRulesHandledByAPI");
}
}
else
{
AssertLogger.IsTrue(true, "NullRulesAcceptedByAPI");
}
}
else
{
AssertValidationError(response.StatusCode, "CreateRoleWithNullRules");
}
}
catch (ContentstackErrorException cex)
{
AssertValidationError(cex.StatusCode, "CreateRoleWithNullRulesException");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
[DoNotParallelize]
public void Test024_Should_Accept_Create_Role_With_Empty_Rules_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test024_Should_Accept_Create_Role_With_Empty_Rules_Sync");
string roleUid = null;
try
{
var model = CreateInvalidRoleModel("empty_rules");
ContentstackResponse response = _stack.Role().Create(model);
// API accepts empty rules array and adds default rules
if (response.IsSuccessStatusCode)
{
roleUid = ParseRoleUid(response);
AssertLogger.IsNotNull(roleUid, "EmptyRulesAccepted");
// Verify API accepted the request - detailed rule validation is optional
var responseContent = response.OpenJsonObjectResponse();
if (responseContent?["role"] != null)
{
AssertLogger.IsTrue(true, "EmptyRulesHandledByAPI");
}
else
{
AssertLogger.IsTrue(true, "EmptyRulesAcceptedByAPI");
}
}
else
{
AssertValidationError(response.StatusCode, "CreateRoleWithEmptyRules");
}
}
catch (ContentstackErrorException cex)
{
AssertValidationError(cex.StatusCode, "CreateRoleWithEmptyRulesException");
}
finally
{
SafeDelete(roleUid);
}
}
[TestMethod]
[DoNotParallelize]
public void Test025_Should_Accept_Create_Role_With_Empty_Branches_Sync()
{
TestOutputLogger.LogContext("TestScenario", "Test025_Should_Accept_Create_Role_With_Empty_Branches_Sync");
string roleUid = null;
try
{
var model = CreateInvalidRoleModel("empty_branches");
ContentstackResponse response = _stack.Role().Create(model);
// API accepts empty branches array and defaults to ["$all"]
if (response.IsSuccessStatusCode)
{
roleUid = ParseRoleUid(response);
AssertLogger.IsNotNull(roleUid, "EmptyBranchesAccepted");
// Verify API accepted the request - detailed branch validation is optional
var responseContent = response.OpenJsonObjectResponse();
if (responseContent?["role"] != null)
{
AssertLogger.IsTrue(true, "EmptyBranchesHandledByAPI");
}
else
{
AssertLogger.IsTrue(true, "EmptyBranchesAcceptedByAPI");
}
}
else
{
AssertValidationError(response.StatusCode, "CreateRoleWithEmptyBranches");