-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathContentstack015_BulkOperationTest.cs
More file actions
1804 lines (1646 loc) · 83.3 KB
/
Contentstack015_BulkOperationTest.cs
File metadata and controls
1804 lines (1646 loc) · 83.3 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.Models.Fields;
using Contentstack.Management.Core.Tests.Model;
using Contentstack.Management.Core.Abstractions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Contentstack.Management.Core.Tests.IntegrationTest
{
/// <summary>
/// Bulk operation integration tests. ClassInitialize ensures environment (find or create "bulk_test_env"), then finds or creates workflow "workflow_test" (2 stages: New stage 1, New stage 2) and publish rule (Stage 2) once.
/// Tests are independent. Four workflow-based tests assign entries to Stage 1/Stage 2 then run bulk unpublish/publish with/without version and params.
/// No cleanup so you can verify workflow, publish rules, and entry allotment in the UI.
/// </summary>
[TestClass]
public class Contentstack015_BulkOperationTest
{
private Stack _stack;
private string _contentTypeUid = "bulk_test_content_type";
private string _testEnvironmentUid = "bulk_test_environment";
private string _testReleaseUid = "bulk_test_release";
private List<EntryInfo> _createdEntries = new List<EntryInfo>();
// Workflow and publishing rule for bulk tests (static so one create/delete across all test instances)
private static string _bulkTestWorkflowUid;
private static string _bulkTestWorkflowStageUid; // Stage 2 (Complete) – used by publish rule and backward compat
private static string _bulkTestWorkflowStage1Uid; // Stage 1 (Review)
private static string _bulkTestWorkflowStage2Uid; // Stage 2 (Complete) – selected in publishing rule
private static string _bulkTestPublishRuleUid;
private static string _bulkTestEnvironmentUid; // Environment used for workflow/publish rule (ensured in ClassInitialize or Test000b/000c)
private static string _bulkTestWorkflowSetupError; // Reason workflow setup failed (so workflow_tests can show it)
/// <summary>
/// Fails the test with a clear message from ContentstackErrorException or generic exception.
/// </summary>
private static void FailWithError(string operation, Exception ex)
{
if (ex is ContentstackErrorException cex)
AssertLogger.Fail($"{operation} failed. HTTP {(int)cex.StatusCode} ({cex.StatusCode}). ErrorCode: {cex.ErrorCode}. Message: {cex.ErrorMessage ?? cex.Message}");
else
AssertLogger.Fail($"{operation} failed: {ex.Message}");
}
/// <summary>
/// Asserts that the workflow and both stages were created in ClassInitialize. Call at the start of workflow-based tests so they fail clearly when setup failed.
/// </summary>
private static void AssertWorkflowCreated()
{
string reason = string.IsNullOrEmpty(_bulkTestWorkflowSetupError) ? "Check auth and stack permissions for workflow create." : _bulkTestWorkflowSetupError;
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestWorkflowUid), "Workflow was not created in ClassInitialize. " + reason, "WorkflowUid");
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestWorkflowStage1Uid), "Workflow Stage 1 (New stage 1) was not set. " + reason, "WorkflowStage1Uid");
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestWorkflowStage2Uid), "Workflow Stage 2 (New stage 2) was not set. " + reason, "WorkflowStage2Uid");
}
private static ContentstackClient _client;
/// <summary>
/// Returns a Stack instance for the test run (used by ClassInitialize/ClassCleanup).
/// </summary>
private static Stack GetStack()
{
StackResponse response = StackResponse.getStack(_client.serializer);
return _client.Stack(response.Stack.APIKey);
}
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
_client = Contentstack.CreateAuthenticatedClient();
try
{
Stack stack = GetStack();
EnsureBulkTestWorkflowAndPublishingRuleAsync(stack).GetAwaiter().GetResult();
}
catch (Exception)
{
// Workflow/publish rule setup failed (e.g. auth, plan limits); tests can still run without them
}
}
[ClassCleanup]
public static void ClassCleanup()
{
// Intentionally no cleanup: workflow, publish rules, and entries are left so you can verify them in the UI.
try { _client?.Logout(); } catch { }
_client = null;
}
[TestInitialize]
public async Task Initialize()
{
StackResponse response = StackResponse.getStack(_client.serializer);
_stack = _client.Stack(response.Stack.APIKey);
// Create test environment and release for bulk operations (for new stack)
try
{
await CreateTestEnvironment();
}
catch (ContentstackErrorException ex)
{
// Environment may already exist on this stack; no action needed
Console.WriteLine($"[Initialize] CreateTestEnvironment skipped: HTTP {(int)ex.StatusCode} ({ex.StatusCode}). ErrorCode: {ex.ErrorCode}. Message: {ex.ErrorMessage ?? ex.Message}");
}
try
{
await CreateTestRelease();
}
catch (ContentstackErrorException ex)
{
// Release may already exist on this stack; no action needed
Console.WriteLine($"[Initialize] CreateTestRelease skipped: HTTP {(int)ex.StatusCode} ({ex.StatusCode}). ErrorCode: {ex.ErrorCode}. Message: {ex.ErrorMessage ?? ex.Message}");
}
// Ensure workflow (and bulk env) is initialized when running on a new stack
if (string.IsNullOrEmpty(_bulkTestWorkflowUid))
{
try
{
EnsureBulkTestWorkflowAndPublishingRuleAsync(_stack).GetAwaiter().GetResult();
}
catch (Exception ex)
{
// Workflow setup failed (e.g. auth, plan limits); record the reason so workflow-based tests can surface it
_bulkTestWorkflowSetupError = ex is ContentstackErrorException cex
? $"HTTP {(int)cex.StatusCode} ({cex.StatusCode}). ErrorCode: {cex.ErrorCode}. Message: {cex.ErrorMessage ?? cex.Message}"
: ex.Message;
Console.WriteLine($"[Initialize] Workflow setup failed: {_bulkTestWorkflowSetupError}");
}
}
}
[TestMethod]
[DoNotParallelize]
public void Test000a_Should_Create_Workflow_With_Two_Stages()
{
TestOutputLogger.LogContext("TestScenario", "CreateWorkflowWithTwoStages");
try
{
const string workflowName = "workflow_test";
// Check if a workflow with the same name already exists (e.g. from a previous test run)
try
{
ContentstackResponse listResponse = _stack.Workflow().FindAll();
if (listResponse.IsSuccessStatusCode)
{
var listJson = listResponse.OpenJObjectResponse();
var existing = (listJson["workflows"] as JArray) ?? (listJson["workflow"] as JArray);
if (existing != null)
{
foreach (var wf in existing)
{
if (wf["name"]?.ToString() == workflowName && wf["uid"] != null)
{
_bulkTestWorkflowUid = wf["uid"].ToString();
var existingStages = wf["workflow_stages"] as JArray;
if (existingStages != null && existingStages.Count >= 2)
{
_bulkTestWorkflowStage1Uid = existingStages[0]["uid"]?.ToString();
_bulkTestWorkflowStage2Uid = existingStages[1]["uid"]?.ToString();
_bulkTestWorkflowStageUid = _bulkTestWorkflowStage2Uid;
AssertLogger.IsNotNull(_bulkTestWorkflowStage1Uid, "Stage1Uid");
AssertLogger.IsNotNull(_bulkTestWorkflowStage2Uid, "Stage2Uid");
return; // Already exists with stages – nothing more to do
}
}
}
}
}
}
catch { /* If listing fails, proceed to create */ }
var sysAcl = new Dictionary<string, object>
{
["roles"] = new Dictionary<string, object> { ["uids"] = new List<string>() },
["users"] = new Dictionary<string, object> { ["uids"] = new List<string> { "$all" } },
["others"] = new Dictionary<string, object>()
};
var workflowModel = new WorkflowModel
{
Name = workflowName,
Enabled = true,
Branches = new List<string> { "main" },
ContentTypes = new List<string> { "$all" },
AdminUsers = new Dictionary<string, object> { ["users"] = new List<object>() },
WorkflowStages = new List<WorkflowStage>
{
new WorkflowStage
{
Name = "New stage 1",
Color = "#fe5cfb",
SystemACL = sysAcl,
NextAvailableStages = new List<string> { "$all" },
AllStages = true,
AllUsers = true,
SpecificStages = false,
SpecificUsers = false,
EntryLock = "$none"
},
new WorkflowStage
{
Name = "New stage 2",
Color = "#3688bf",
SystemACL = new Dictionary<string, object>
{
["roles"] = new Dictionary<string, object> { ["uids"] = new List<string>() },
["users"] = new Dictionary<string, object> { ["uids"] = new List<string> { "$all" } },
["others"] = new Dictionary<string, object>()
},
NextAvailableStages = new List<string> { "$all" },
AllStages = true,
AllUsers = true,
SpecificStages = false,
SpecificUsers = false,
EntryLock = "$none"
}
}
};
// Print what we are sending so failures show the exact request JSON
string sentJson = JsonConvert.SerializeObject(new { workflow = workflowModel }, Formatting.Indented);
ContentstackResponse response = _stack.Workflow().Create(workflowModel);
string responseBody = null;
try { responseBody = response.OpenResponse(); } catch { }
AssertLogger.IsNotNull(response, "workflowCreateResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode,
$"Workflow create failed: HTTP {(int)response.StatusCode}.\n--- REQUEST BODY ---\n{sentJson}\n--- RESPONSE BODY ---\n{responseBody}", "workflowCreateSuccess");
var responseJson = JObject.Parse(responseBody ?? "{}");
var workflowObj = responseJson["workflow"];
AssertLogger.IsNotNull(workflowObj, "workflowObj");
AssertLogger.IsFalse(string.IsNullOrEmpty(workflowObj["uid"]?.ToString()), "Workflow UID is empty.", "workflowUid");
_bulkTestWorkflowUid = workflowObj["uid"].ToString();
TestOutputLogger.LogContext("WorkflowUid", _bulkTestWorkflowUid);
var stages = workflowObj["workflow_stages"] as JArray;
AssertLogger.IsNotNull(stages, "workflow_stages");
AssertLogger.IsTrue(stages.Count >= 2, $"Expected at least 2 stages, got {stages.Count}.", "stagesCount");
_bulkTestWorkflowStage1Uid = stages[0]["uid"].ToString(); // New stage 1
_bulkTestWorkflowStage2Uid = stages[1]["uid"].ToString(); // New stage 2
_bulkTestWorkflowStageUid = _bulkTestWorkflowStage2Uid;
}
catch (Exception ex)
{
FailWithError("Create workflow with two stages", ex);
}
}
[TestMethod]
[DoNotParallelize]
public void Test000b_Should_Create_Publishing_Rule_For_Workflow_Stage2()
{
TestOutputLogger.LogContext("TestScenario", "CreatePublishingRuleForWorkflowStage2");
try
{
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestWorkflowUid), "Workflow UID not set. Run Test000a first.", "WorkflowUid");
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestWorkflowStage2Uid), "Workflow Stage 2 UID not set. Run Test000a first.", "WorkflowStage2Uid");
if (string.IsNullOrEmpty(_bulkTestEnvironmentUid))
EnsureBulkTestEnvironment(_stack);
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestEnvironmentUid), "No environment. Run Test000c or ensure ClassInitialize ran (ensure environment failed).", "EnvironmentUid");
TestOutputLogger.LogContext("WorkflowUid", _bulkTestWorkflowUid ?? "");
TestOutputLogger.LogContext("EnvironmentUid", _bulkTestEnvironmentUid ?? "");
// Find existing publish rule for this workflow + stage + environment (e.g. from a previous run)
try
{
ContentstackResponse listResponse = _stack.Workflow().PublishRule().FindAll();
if (listResponse.IsSuccessStatusCode)
{
var listJson = listResponse.OpenJObjectResponse();
var rules = (listJson["publishing_rules"] as JArray) ?? (listJson["publishing_rule"] as JArray);
if (rules != null)
{
foreach (var rule in rules)
{
if (rule["workflow"]?.ToString() == _bulkTestWorkflowUid
&& rule["workflow_stage"]?.ToString() == _bulkTestWorkflowStage2Uid
&& rule["environment"]?.ToString() == _bulkTestEnvironmentUid
&& rule["uid"] != null)
{
_bulkTestPublishRuleUid = rule["uid"].ToString();
return; // Already exists
}
}
}
}
}
catch { /* If listing fails, proceed to create */ }
var publishRuleModel = new PublishRuleModel
{
WorkflowUid = _bulkTestWorkflowUid,
WorkflowStageUid = _bulkTestWorkflowStage2Uid,
Environment = _bulkTestEnvironmentUid,
Branches = new List<string> { "main" },
ContentTypes = new List<string> { "$all" },
Locales = new List<string> { "en-us" },
Actions = new List<string>(),
Approvers = new Approvals { Users = new List<string>(), Roles = new List<string>() },
DisableApproval = false
};
string sentJson = JsonConvert.SerializeObject(new { publishing_rule = publishRuleModel }, Formatting.Indented);
ContentstackResponse response = _stack.Workflow().PublishRule().Create(publishRuleModel);
string responseBody = null;
try { responseBody = response.OpenResponse(); } catch { }
AssertLogger.IsNotNull(response, "publishRuleResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode,
$"Publish rule create failed: HTTP {(int)response.StatusCode}.\n--- REQUEST BODY ---\n{sentJson}\n--- RESPONSE BODY ---\n{responseBody}", "publishRuleCreateSuccess");
var responseJson = JObject.Parse(responseBody ?? "{}");
var ruleObj = responseJson["publishing_rule"];
AssertLogger.IsNotNull(ruleObj, "publishing_rule");
AssertLogger.IsFalse(string.IsNullOrEmpty(ruleObj["uid"]?.ToString()), "Publishing rule UID is empty.", "publishRuleUid");
_bulkTestPublishRuleUid = ruleObj["uid"].ToString();
}
catch (Exception ex)
{
FailWithError("Create publishing rule for workflow stage 2", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test001_Should_Create_Content_Type_With_Title_Field()
{
TestOutputLogger.LogContext("TestScenario", "CreateContentTypeWithTitleField");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
try { await CreateTestEnvironment(); } catch (ContentstackErrorException) { /* optional */ }
try { await CreateTestRelease(); } catch (ContentstackErrorException) { /* optional */ }
// Create a content type with only a title field
var contentModelling = new ContentModelling
{
Title = "bulk_test_content_type",
Uid = _contentTypeUid,
Schema = new List<Field>
{
new TextboxField
{
DisplayName = "Title",
Uid = "title",
DataType = "text",
Mandatory = true,
Unique = false,
Multiple = false
}
}
};
// Create the content type
ContentstackResponse response = _stack.ContentType().Create(contentModelling);
var responseJson = response.OpenJObjectResponse();
AssertLogger.IsNotNull(response, "createContentTypeResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode, "contentTypeCreateSuccess");
AssertLogger.IsNotNull(responseJson["content_type"], "content_type");
AssertLogger.AreEqual(_contentTypeUid, responseJson["content_type"]["uid"].ToString(), "contentTypeUid");
}
catch (Exception ex)
{
FailWithError("Create content type with title field", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test002_Should_Create_Five_Entries()
{
TestOutputLogger.LogContext("TestScenario", "CreateFiveEntries");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
AssertWorkflowCreated();
// Ensure content type exists (fetch or create)
bool contentTypeExists = false;
try
{
ContentstackResponse ctResponse = _stack.ContentType(_contentTypeUid).Fetch();
contentTypeExists = ctResponse.IsSuccessStatusCode;
}
catch { /* not found */ }
if (!contentTypeExists)
{
var contentModelling = new ContentModelling
{
Title = "bulk_test_content_type",
Uid = _contentTypeUid,
Schema = new List<Field>
{
new TextboxField
{
DisplayName = "Title",
Uid = "title",
DataType = "text",
Mandatory = true,
Unique = false,
Multiple = false
}
}
};
_stack.ContentType().Create(contentModelling);
}
_createdEntries.Clear();
var entryTitles = new[] { "First Entry", "Second Entry", "Third Entry", "Fourth Entry", "Fifth Entry" };
foreach (var title in entryTitles)
{
var entry = new SimpleEntry { Title = title };
ContentstackResponse response = _stack.ContentType(_contentTypeUid).Entry().Create(entry);
var responseJson = response.OpenJObjectResponse();
AssertLogger.IsNotNull(response, "createEntryResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode, "entryCreateSuccess");
AssertLogger.IsNotNull(responseJson["entry"], "entry");
AssertLogger.IsNotNull(responseJson["entry"]["uid"], "entryUid");
int version = responseJson["entry"]["_version"] != null ? (int)responseJson["entry"]["_version"] : 1;
_createdEntries.Add(new EntryInfo
{
Uid = responseJson["entry"]["uid"].ToString(),
Title = responseJson["entry"]["title"]?.ToString() ?? title,
Version = version
});
}
AssertLogger.AreEqual(5, _createdEntries.Count, "Should have created exactly 5 entries", "createdEntriesCount");
await AssignEntriesToWorkflowStagesAsync(_createdEntries);
}
catch (Exception ex)
{
FailWithError("Create five entries", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test003_Should_Perform_Bulk_Publish_Operation()
{
TestOutputLogger.LogContext("TestScenario", "BulkPublishOperation");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
// Fetch existing entries from the content type
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation", "availableEntriesCount");
// Get available environments or use empty list if none available
List<string> availableEnvironments = await GetAvailableEnvironments();
// Create bulk publish details
var publishDetails = new BulkPublishDetails
{
Entries = availableEntries.Select(e => new BulkPublishEntry
{
Uid = e.Uid,
ContentType = _contentTypeUid,
Version = 1,
Locale = "en-us"
}).ToList(),
Locales = new List<string> { "en-us" },
Environments = availableEnvironments
};
// Perform bulk publish; skipWorkflowStage=true bypasses publish rules enforced by workflow stages
ContentstackResponse response = _stack.BulkOperation().Publish(publishDetails, skipWorkflowStage: true, approvals: true);
var responseJson = response.OpenJObjectResponse();
AssertLogger.IsNotNull(response, "bulkPublishResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode, "bulkPublishSuccess");
}
catch (ContentstackErrorException cex) when ((int)cex.StatusCode == 422)
{
// 422 means entries do not satisfy publish rules (workflow stage restriction); acceptable in integration tests
Console.WriteLine($"[Test003] Bulk publish skipped due to publish rules: HTTP {(int)cex.StatusCode}. ErrorCode: {cex.ErrorCode}. Message: {cex.ErrorMessage ?? cex.Message}");
}
catch (Exception ex)
{
FailWithError("Bulk publish", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test004_Should_Perform_Bulk_Unpublish_Operation()
{
TestOutputLogger.LogContext("TestScenario", "BulkUnpublishOperation");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
// Fetch existing entries from the content type
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation", "availableEntriesCount");
// Get available environments
List<string> availableEnvironments = await GetAvailableEnvironments();
// Create bulk unpublish details
var unpublishDetails = new BulkPublishDetails
{
Entries = availableEntries.Select(e => new BulkPublishEntry
{
Uid = e.Uid,
ContentType = _contentTypeUid,
Version = 1,
Locale = "en-us"
}).ToList(),
Locales = new List<string> { "en-us" },
Environments = availableEnvironments
};
// Perform bulk unpublish; skipWorkflowStage=true bypasses publish rules enforced by workflow stages
ContentstackResponse response = _stack.BulkOperation().Unpublish(unpublishDetails, skipWorkflowStage: true, approvals: true);
var responseJson = response.OpenJObjectResponse();
AssertLogger.IsNotNull(response, "bulkUnpublishResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode, "bulkUnpublishSuccess");
}
catch (ContentstackErrorException cex) when ((int)cex.StatusCode == 422)
{
// 422 means entries do not satisfy publish rules (workflow stage restriction); acceptable in integration tests
Console.WriteLine($"[Test004] Bulk unpublish skipped due to publish rules: HTTP {(int)cex.StatusCode}. ErrorCode: {cex.ErrorCode}. Message: {cex.ErrorMessage ?? cex.Message}");
}
catch (Exception ex)
{
FailWithError("Bulk unpublish", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test003a_Should_Perform_Bulk_Publish_With_SkipWorkflowStage_And_Approvals()
{
TestOutputLogger.LogContext("TestScenario", "BulkPublishWithSkipWorkflowStageAndApprovals");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
if (string.IsNullOrEmpty(_bulkTestEnvironmentUid))
await EnsureBulkTestEnvironmentAsync(_stack);
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestEnvironmentUid), "No environment. Ensure Test000c or ClassInitialize ran.", "EnvironmentUid");
TestOutputLogger.LogContext("EnvironmentUid", _bulkTestEnvironmentUid ?? "");
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation. Run Test002 first.", "availableEntriesCount");
var publishDetails = new BulkPublishDetails
{
Entries = availableEntries.Select(e => new BulkPublishEntry
{
Uid = e.Uid,
ContentType = _contentTypeUid,
Version = e.Version,
Locale = "en-us"
}).ToList(),
Locales = new List<string> { "en-us" },
Environments = new List<string> { _bulkTestEnvironmentUid },
PublishWithReference = true
};
ContentstackResponse response = _stack.BulkOperation().Publish(publishDetails, skipWorkflowStage: true, approvals: true);
AssertLogger.IsNotNull(response, "bulkPublishResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Bulk publish failed with status {(int)response.StatusCode} ({response.StatusCode}).", "bulkPublishSuccess");
AssertLogger.AreEqual(HttpStatusCode.OK, response.StatusCode, $"Expected 200 OK, got {(int)response.StatusCode}.", "statusCode");
var responseJson = response.OpenJObjectResponse();
AssertLogger.IsNotNull(responseJson, "responseJson");
}
catch (Exception ex)
{
if (ex is ContentstackErrorException cex)
{
string errorsJson = cex.Errors != null && cex.Errors.Count > 0
? JsonConvert.SerializeObject(cex.Errors, Formatting.Indented)
: "(none)";
string failMessage = string.Format(
"Bulk publish with skipWorkflowStage and approvals failed. HTTP {0} ({1}). ErrorCode: {2}. Message: {3}. Errors: {4}",
(int)cex.StatusCode, cex.StatusCode, cex.ErrorCode, cex.ErrorMessage ?? cex.Message, errorsJson);
if ((int)cex.StatusCode == 422 && cex.ErrorCode == 141)
{
Console.WriteLine(failMessage);
AssertLogger.AreEqual(422, (int)cex.StatusCode, "Expected 422 Unprocessable Entity.", "statusCode");
AssertLogger.AreEqual(141, cex.ErrorCode, "Expected ErrorCode 141 (entries do not satisfy publish rules).", "errorCode");
return;
}
AssertLogger.Fail(failMessage);
}
else
{
FailWithError("Bulk publish with skipWorkflowStage and approvals", ex);
}
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test004a_Should_Perform_Bulk_UnPublish_With_SkipWorkflowStage_And_Approvals()
{
TestOutputLogger.LogContext("TestScenario", "BulkUnpublishWithSkipWorkflowStageAndApprovals");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
if (string.IsNullOrEmpty(_bulkTestEnvironmentUid))
await EnsureBulkTestEnvironmentAsync(_stack);
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestEnvironmentUid), "No environment. Ensure Test000c or ClassInitialize ran.", "EnvironmentUid");
TestOutputLogger.LogContext("EnvironmentUid", _bulkTestEnvironmentUid ?? "");
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation. Run Test002 first.", "availableEntriesCount");
var publishDetails = new BulkPublishDetails
{
Entries = availableEntries.Select(e => new BulkPublishEntry
{
Uid = e.Uid,
ContentType = _contentTypeUid,
Version = e.Version,
Locale = "en-us"
}).ToList(),
Locales = new List<string> { "en-us" },
Environments = new List<string> { _bulkTestEnvironmentUid },
PublishWithReference = true
};
ContentstackResponse response = _stack.BulkOperation().Unpublish(publishDetails, skipWorkflowStage: false, approvals: true);
AssertLogger.IsNotNull(response, "bulkUnpublishResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Bulk publish failed with status {(int)response.StatusCode} ({response.StatusCode}).", "bulkUnpublishSuccess");
AssertLogger.AreEqual(HttpStatusCode.OK, response.StatusCode, $"Expected 200 OK, got {(int)response.StatusCode}.", "statusCode");
var responseJson = response.OpenJObjectResponse();
AssertLogger.IsNotNull(responseJson, "responseJson");
}
catch (Exception ex)
{
if (ex is ContentstackErrorException cex)
{
string errorsJson = cex.Errors != null && cex.Errors.Count > 0
? JsonConvert.SerializeObject(cex.Errors, Formatting.Indented)
: "(none)";
string failMessage = string.Format(
"Bulk unpublish with skipWorkflowStage and approvals failed. HTTP {0} ({1}). ErrorCode: {2}. Message: {3}. Errors: {4}",
(int)cex.StatusCode, cex.StatusCode, cex.ErrorCode, cex.ErrorMessage ?? cex.Message, errorsJson);
if ((int)cex.StatusCode == 422 && (cex.ErrorCode == 141 || cex.ErrorCode == 0))
{
Console.WriteLine(failMessage);
AssertLogger.AreEqual(422, (int)cex.StatusCode, "Expected 422 Unprocessable Entity.", "statusCode");
AssertLogger.IsTrue(cex.ErrorCode == 141 || cex.ErrorCode == 0, "Expected ErrorCode 141 or 0 (entries do not satisfy publish rules).", "errorCode");
return;
}
AssertLogger.Fail(failMessage);
}
else
{
FailWithError("Bulk unpublish with skipWorkflowStage and approvals", ex);
}
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test003b_Should_Perform_Bulk_Publish_With_ApiVersion_3_2_With_SkipWorkflowStage_And_Approvals()
{
TestOutputLogger.LogContext("TestScenario", "BulkPublishApiVersion32WithSkipWorkflowStageAndApprovals");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
if (string.IsNullOrEmpty(_bulkTestEnvironmentUid))
await EnsureBulkTestEnvironmentAsync(_stack);
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestEnvironmentUid), "No environment. Ensure Test000c or ClassInitialize ran.", "EnvironmentUid");
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation. Run Test002 first.", "availableEntriesCount");
var publishDetails = new BulkPublishDetails
{
Entries = availableEntries.Select(e => new BulkPublishEntry
{
Uid = e.Uid,
ContentType = _contentTypeUid,
Version = e.Version,
Locale = "en-us"
}).ToList(),
Locales = new List<string> { "en-us" },
Environments = new List<string> { _bulkTestEnvironmentUid },
PublishWithReference = true
};
ContentstackResponse response = _stack.BulkOperation().Publish(publishDetails, skipWorkflowStage: true, approvals: true, apiVersion: "3.2");
AssertLogger.IsNotNull(response, "bulkPublishResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Bulk publish with api_version 3.2 failed with status {(int)response.StatusCode} ({response.StatusCode}).", "bulkPublishSuccess");
AssertLogger.AreEqual(HttpStatusCode.OK, response.StatusCode, $"Expected 200 OK, got {(int)response.StatusCode}.", "statusCode");
var responseJson = response.OpenJObjectResponse();
AssertLogger.IsNotNull(responseJson, "responseJson");
}
catch (Exception ex)
{
FailWithError("Bulk publish with api_version 3.2", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test004b_Should_Perform_Bulk_UnPublish_With_ApiVersion_3_2_With_SkipWorkflowStage_And_Approvals()
{
TestOutputLogger.LogContext("TestScenario", "BulkUnpublishApiVersion32WithSkipWorkflowStageAndApprovals");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
if (string.IsNullOrEmpty(_bulkTestEnvironmentUid))
await EnsureBulkTestEnvironmentAsync(_stack);
AssertLogger.IsFalse(string.IsNullOrEmpty(_bulkTestEnvironmentUid), "No environment. Ensure Test000c or ClassInitialize ran.", "EnvironmentUid");
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation. Run Test002 first.", "availableEntriesCount");
var publishDetails = new BulkPublishDetails
{
Entries = availableEntries.Select(e => new BulkPublishEntry
{
Uid = e.Uid,
ContentType = _contentTypeUid,
Version = e.Version,
Locale = "en-us"
}).ToList(),
Locales = new List<string> { "en-us" },
Environments = new List<string> { _bulkTestEnvironmentUid },
PublishWithReference = true
};
ContentstackResponse response = _stack.BulkOperation().Unpublish(publishDetails, skipWorkflowStage: true, approvals: true, apiVersion: "3.2");
AssertLogger.IsNotNull(response, "bulkUnpublishResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode, $"Bulk unpublish with api_version 3.2 failed with status {(int)response.StatusCode} ({response.StatusCode}).", "bulkUnpublishSuccess");
AssertLogger.AreEqual(HttpStatusCode.OK, response.StatusCode, $"Expected 200 OK, got {(int)response.StatusCode}.", "statusCode");
var responseJson = response.OpenJObjectResponse();
AssertLogger.IsNotNull(responseJson, "responseJson");
}
catch (Exception ex)
{
FailWithError("Bulk unpublish with api_version 3.2", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test005_Should_Perform_Bulk_Release_Operations()
{
TestOutputLogger.LogContext("TestScenario", "BulkReleaseOperations");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
// Fetch existing entries from the content type
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation", "availableEntriesCount");
// Fetch an available release
string availableReleaseUid = await FetchAvailableRelease();
AssertLogger.IsFalse(string.IsNullOrEmpty(availableReleaseUid), "No release available for bulk operations", "availableReleaseUid");
if (!string.IsNullOrEmpty(availableReleaseUid))
TestOutputLogger.LogContext("ReleaseUid", availableReleaseUid);
// First, add items to the release
var addItemsData = new BulkAddItemsData
{
Items = availableEntries.Select(e => new BulkAddItem
{
Uid = e.Uid,
ContentType = _contentTypeUid
}).ToList()
};
// Now perform bulk release operations using AddItems in deployment mode (only 4 entries)
var releaseData = new BulkAddItemsData
{
Release = availableReleaseUid,
Action = "publish",
Locale = new List<string> { "en-us" },
Reference = false,
Items = availableEntries.Take(4).Select(e => new BulkAddItem
{
Uid = e.Uid,
ContentType = _contentTypeUid,
ContentTypeUid = _contentTypeUid,
Version = e.Version,
Locale = "en-us",
Title = e.Title
}).ToList()
};
// Perform bulk release using AddItems in deployment mode
ContentstackResponse releaseResponse = _stack.BulkOperation().AddItems(releaseData, "2.0");
var releaseResponseJson = releaseResponse.OpenJObjectResponse();
AssertLogger.IsNotNull(releaseResponse, "releaseResponse");
AssertLogger.IsTrue(releaseResponse.IsSuccessStatusCode, "releaseAddItemsSuccess");
// Check if job was created
AssertLogger.IsNotNull(releaseResponseJson["job_id"], "job_id");
string jobId = releaseResponseJson["job_id"].ToString();
// Wait a bit and check job status
await Task.Delay(2000);
await CheckBulkJobStatus(jobId,"2.0");
}
catch (Exception ex)
{
FailWithError("Bulk release operations", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test006_Should_Update_Items_In_Release()
{
TestOutputLogger.LogContext("TestScenario", "UpdateItemsInRelease");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
// Fetch existing entries from the content type
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation", "availableEntriesCount");
// Fetch an available release
string availableReleaseUid = await FetchAvailableRelease();
AssertLogger.IsFalse(string.IsNullOrEmpty(availableReleaseUid), "No release available for bulk operations", "availableReleaseUid");
if (!string.IsNullOrEmpty(availableReleaseUid))
TestOutputLogger.LogContext("ReleaseUid", availableReleaseUid);
// Alternative: Test bulk update items with version 2.0 for release items
var releaseData = new BulkAddItemsData
{
Release = availableReleaseUid,
Action = "publish",
Locale = new List<string> { "en-us" },
Reference = false,
Items = availableEntries.Skip(4).Take(1).Select(e => new BulkAddItem
{
Uid = e.Uid,
ContentType = _contentTypeUid,
ContentTypeUid = _contentTypeUid,
Version = e.Version,
Locale = "en-us",
Title = e.Title
}).ToList()
};
ContentstackResponse bulkUpdateResponse = _stack.BulkOperation().UpdateItems(releaseData, "2.0");
var bulkUpdateResponseJson = bulkUpdateResponse.OpenJObjectResponse();
AssertLogger.IsNotNull(bulkUpdateResponse, "bulkUpdateResponse");
AssertLogger.IsTrue(bulkUpdateResponse.IsSuccessStatusCode, "bulkUpdateSuccess");
if (bulkUpdateResponseJson["job_id"] != null)
{
string bulkJobId = bulkUpdateResponseJson["job_id"].ToString();
// Check job status
await Task.Delay(2000);
await CheckBulkJobStatus(bulkJobId, "2.0");
}
}
catch (Exception ex)
{
FailWithError("Update items in release", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test007_Should_Perform_Bulk_Delete_Operation()
{
TestOutputLogger.LogContext("TestScenario", "BulkDeleteOperation");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation", "availableEntriesCount");
var deleteDetails = new BulkDeleteDetails
{
Entries = availableEntries.Select(e => new BulkDeleteEntry
{
Uid = e.Uid,
ContentType = _contentTypeUid,
Locale = "en-us"
}).ToList()
};
// Skip actual delete so entries remain for UI verification. SDK usage is validated by building the payload.
AssertLogger.IsNotNull(deleteDetails, "deleteDetails");
AssertLogger.IsTrue(deleteDetails.Entries.Count > 0, "deleteDetailsEntriesCount");
}
catch (Exception ex)
{
FailWithError("Bulk delete", ex);
}
}
[TestMethod]
[DoNotParallelize]
public async Task Test008_Should_Perform_Bulk_Workflow_Operations()
{
TestOutputLogger.LogContext("TestScenario", "BulkWorkflowOperations");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
// Fetch existing entries from the content type
List<EntryInfo> availableEntries = await FetchExistingEntries();
AssertLogger.IsTrue(availableEntries.Count > 0, "No entries available for bulk operation", "availableEntriesCount");
// Test bulk workflow update operations (use real stage UID from EnsureBulkTestWorkflowAndPublishingRuleAsync when available)
string workflowStageUid = !string.IsNullOrEmpty(_bulkTestWorkflowStageUid) ? _bulkTestWorkflowStageUid : "workflow_stage_uid";
var workflowUpdateBody = new BulkWorkflowUpdateBody
{
Entries = availableEntries.Select(e => new BulkWorkflowEntry
{
Uid = e.Uid,
ContentType = _contentTypeUid,
Locale = "en-us"
}).ToList(),
Workflow = new BulkWorkflowStage
{
Comment = "Bulk workflow update test",
DueDate = DateTime.Now.AddDays(7).ToString("ddd MMM dd yyyy"),
Notify = false,
Uid = workflowStageUid
}
};
ContentstackResponse response = _stack.BulkOperation().Update(workflowUpdateBody);
var responseJson = response.OpenJObjectResponse();
AssertLogger.IsNotNull(response, "bulkWorkflowResponse");
AssertLogger.IsTrue(response.IsSuccessStatusCode, "bulkWorkflowSuccess");
AssertLogger.IsNotNull(responseJson["job_id"], "job_id");
string jobId = responseJson["job_id"].ToString();
await CheckBulkJobStatus(jobId);
}
catch (ContentstackErrorException ex) when (ex.StatusCode == (HttpStatusCode)412 && ex.ErrorCode == 366)
{
// Stage Update Request Failed (412/366) – acceptable when workflow/entry state does not allow the transition
}
catch (Exception ex)
{
FailWithError("Bulk workflow operations", ex);
}
}
[TestMethod]
[DoNotParallelize]
public void Test009_Should_Cleanup_Test_Resources()
{
TestOutputLogger.LogContext("TestScenario", "CleanupTestResources");
TestOutputLogger.LogContext("ContentType", _contentTypeUid);
try
{
// 1. Delete all entries created during the test run
if (_createdEntries != null)
{
foreach (var entry in _createdEntries)
{
try
{
_stack.ContentType(_contentTypeUid).Entry(entry.Uid).Delete();
Console.WriteLine($"[Cleanup] Deleted entry: {entry.Uid}");
}
catch (Exception ex)
{
Console.WriteLine($"[Cleanup] Failed to delete entry {entry.Uid}: {ex.Message}");
}
}
_createdEntries.Clear();