Skip to content

Commit 999b55d

Browse files
committed
refactor(BulkOperationTest): improve test lifecycle, sync helpers, and cleanup
Improve the test lifecycle, initialization, and teardown of Contentstack015_BulkOperationTest. Test method signature changes: - Convert Test000a_Should_Create_Workflow_With_Two_Stages from async Task to void (no awaits were present; async keyword was unnecessary). - Convert Test000b_Should_Create_Publishing_Rule_For_Workflow_Stage2 from async Task to void; replace await EnsureBulkTestEnvironmentAsync with the new sync helper. New synchronous helpers: - Add GetAvailableEnvironments(Stack) — sync version of GetAvailableEnvironmentsAsync, used by the new EnsureBulkTestEnvironment helper. - Add EnsureBulkTestEnvironment(Stack) — sync version of EnsureBulkTestEnvironmentAsync, finds or creates bulk_test_env without blocking on a Task. TestInitialize improvements: - Uncomment and add CreateTestEnvironment() and CreateTestRelease() calls so a new stack gets test environment and release set up before each test. - Add workflow initialization in TestInitialize: if _bulkTestWorkflowUid is not set (e.g. ClassInitialize failed or new stack), call EnsureBulkTestWorkflowAndPublishingRuleAsync to ensure workflow and publish rule are available. - Add full explicit try/catch blocks for each setup step with Console.WriteLine logging and meaningful comments; workflow catch records the failure reason in _bulkTestWorkflowSetupError so workflow-based tests surface it via AssertWorkflowCreated(). New cleanup test: - Add Test009_Should_Cleanup_Test_Resources (void, DoNotParallelize) that deletes all resources created during the test run in the correct order: 1. All entries in _createdEntries 2. Content type (bulk_test_content_type) 3. Workflow and publishing rule (via CleanupBulkTestWorkflowAndPublishingRule) 4. Test release 5. Test environment Each step has its own try/catch with Console.WriteLine so one failed delete does not stop the remaining cleanup.
1 parent 1161371 commit 999b55d

File tree

1 file changed

+182
-3
lines changed

1 file changed

+182
-3
lines changed

Contentstack.Management.Core.Tests/IntegrationTest/Contentstack015_BulkOperationTest.cs

Lines changed: 182 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -93,11 +93,49 @@ public async Task Initialize()
9393
{
9494
StackResponse response = StackResponse.getStack(Contentstack.Client.serializer);
9595
_stack = Contentstack.Client.Stack(response.Stack.APIKey);
96+
97+
// Create test environment and release for bulk operations (for new stack)
98+
try
99+
{
100+
await CreateTestEnvironment();
101+
}
102+
catch (ContentstackErrorException ex)
103+
{
104+
// Environment may already exist on this stack; no action needed
105+
Console.WriteLine($"[Initialize] CreateTestEnvironment skipped: HTTP {(int)ex.StatusCode} ({ex.StatusCode}). ErrorCode: {ex.ErrorCode}. Message: {ex.ErrorMessage ?? ex.Message}");
106+
}
107+
108+
try
109+
{
110+
await CreateTestRelease();
111+
}
112+
catch (ContentstackErrorException ex)
113+
{
114+
// Release may already exist on this stack; no action needed
115+
Console.WriteLine($"[Initialize] CreateTestRelease skipped: HTTP {(int)ex.StatusCode} ({ex.StatusCode}). ErrorCode: {ex.ErrorCode}. Message: {ex.ErrorMessage ?? ex.Message}");
116+
}
117+
118+
// Ensure workflow (and bulk env) is initialized when running on a new stack
119+
if (string.IsNullOrEmpty(_bulkTestWorkflowUid))
120+
{
121+
try
122+
{
123+
EnsureBulkTestWorkflowAndPublishingRuleAsync(_stack).GetAwaiter().GetResult();
124+
}
125+
catch (Exception ex)
126+
{
127+
// Workflow setup failed (e.g. auth, plan limits); record the reason so workflow-based tests can surface it
128+
_bulkTestWorkflowSetupError = ex is ContentstackErrorException cex
129+
? $"HTTP {(int)cex.StatusCode} ({cex.StatusCode}). ErrorCode: {cex.ErrorCode}. Message: {cex.ErrorMessage ?? cex.Message}"
130+
: ex.Message;
131+
Console.WriteLine($"[Initialize] Workflow setup failed: {_bulkTestWorkflowSetupError}");
132+
}
133+
}
96134
}
97135

98136
[TestMethod]
99137
[DoNotParallelize]
100-
public async Task Test000a_Should_Create_Workflow_With_Two_Stages()
138+
public void Test000a_Should_Create_Workflow_With_Two_Stages()
101139
{
102140
try
103141
{
@@ -215,15 +253,15 @@ public async Task Test000a_Should_Create_Workflow_With_Two_Stages()
215253

216254
[TestMethod]
217255
[DoNotParallelize]
218-
public async Task Test000b_Should_Create_Publishing_Rule_For_Workflow_Stage2()
256+
public void Test000b_Should_Create_Publishing_Rule_For_Workflow_Stage2()
219257
{
220258
try
221259
{
222260
Assert.IsFalse(string.IsNullOrEmpty(_bulkTestWorkflowUid), "Workflow UID not set. Run Test000a first.");
223261
Assert.IsFalse(string.IsNullOrEmpty(_bulkTestWorkflowStage2Uid), "Workflow Stage 2 UID not set. Run Test000a first.");
224262

225263
if (string.IsNullOrEmpty(_bulkTestEnvironmentUid))
226-
await EnsureBulkTestEnvironmentAsync(_stack);
264+
EnsureBulkTestEnvironment(_stack);
227265
Assert.IsFalse(string.IsNullOrEmpty(_bulkTestEnvironmentUid), "No environment. Run Test000c or ensure ClassInitialize ran (ensure environment failed).");
228266

229267
// Find existing publish rule for this workflow + stage + environment (e.g. from a previous run)
@@ -885,6 +923,84 @@ public async Task Test008_Should_Perform_Bulk_Workflow_Operations()
885923
}
886924
}
887925

926+
[TestMethod]
927+
[DoNotParallelize]
928+
public void Test009_Should_Cleanup_Test_Resources()
929+
{
930+
try
931+
{
932+
// 1. Delete all entries created during the test run
933+
if (_createdEntries != null)
934+
{
935+
foreach (var entry in _createdEntries)
936+
{
937+
try
938+
{
939+
_stack.ContentType(_contentTypeUid).Entry(entry.Uid).Delete();
940+
Console.WriteLine($"[Cleanup] Deleted entry: {entry.Uid}");
941+
}
942+
catch (Exception ex)
943+
{
944+
Console.WriteLine($"[Cleanup] Failed to delete entry {entry.Uid}: {ex.Message}");
945+
}
946+
}
947+
_createdEntries.Clear();
948+
}
949+
950+
// 2. Delete the content type
951+
if (!string.IsNullOrEmpty(_contentTypeUid))
952+
{
953+
try
954+
{
955+
_stack.ContentType(_contentTypeUid).Delete();
956+
Console.WriteLine($"[Cleanup] Deleted content type: {_contentTypeUid}");
957+
}
958+
catch (Exception ex)
959+
{
960+
Console.WriteLine($"[Cleanup] Failed to delete content type {_contentTypeUid}: {ex.Message}");
961+
}
962+
}
963+
964+
// 3. Delete the workflow and publishing rule
965+
CleanupBulkTestWorkflowAndPublishingRule(_stack);
966+
Console.WriteLine("[Cleanup] Workflow and publishing rule cleanup done.");
967+
968+
// 4. Delete the test release
969+
if (!string.IsNullOrEmpty(_testReleaseUid))
970+
{
971+
try
972+
{
973+
_stack.Release(_testReleaseUid).Delete();
974+
Console.WriteLine($"[Cleanup] Deleted release: {_testReleaseUid}");
975+
_testReleaseUid = null;
976+
}
977+
catch (Exception ex)
978+
{
979+
Console.WriteLine($"[Cleanup] Failed to delete release {_testReleaseUid}: {ex.Message}");
980+
}
981+
}
982+
983+
// 5. Delete the test environment
984+
if (!string.IsNullOrEmpty(_testEnvironmentUid))
985+
{
986+
try
987+
{
988+
_stack.Environment(_testEnvironmentUid).Delete();
989+
Console.WriteLine($"[Cleanup] Deleted environment: {_testEnvironmentUid}");
990+
_testEnvironmentUid = null;
991+
}
992+
catch (Exception ex)
993+
{
994+
Console.WriteLine($"[Cleanup] Failed to delete environment {_testEnvironmentUid}: {ex.Message}");
995+
}
996+
}
997+
}
998+
catch (Exception ex)
999+
{
1000+
FailWithError("Cleanup test resources", ex);
1001+
}
1002+
}
1003+
8881004
private async Task CheckBulkJobStatus(string jobId, string bulkVersion = null)
8891005
{
8901006
try
@@ -1084,6 +1200,34 @@ private async Task EnsureBulkTestContentTypeAndEntriesAsync()
10841200
}
10851201
}
10861202

1203+
/// <summary>
1204+
/// Returns available environment UIDs for the given stack (synchronous).
1205+
/// </summary>
1206+
private static List<string> GetAvailableEnvironments(Stack stack)
1207+
{
1208+
try
1209+
{
1210+
ContentstackResponse response = stack.Environment().Query().Find();
1211+
var responseJson = response.OpenJObjectResponse();
1212+
if (response.IsSuccessStatusCode && responseJson["environments"] != null)
1213+
{
1214+
var environments = responseJson["environments"] as JArray;
1215+
if (environments != null && environments.Count > 0)
1216+
{
1217+
var uids = new List<string>();
1218+
foreach (var env in environments)
1219+
{
1220+
if (env["uid"] != null)
1221+
uids.Add(env["uid"].ToString());
1222+
}
1223+
return uids;
1224+
}
1225+
}
1226+
}
1227+
catch { }
1228+
return new List<string>();
1229+
}
1230+
10871231
/// <summary>
10881232
/// Returns available environment UIDs for the given stack (used by workflow setup).
10891233
/// </summary>
@@ -1112,6 +1256,41 @@ private static async Task<List<string>> GetAvailableEnvironmentsAsync(Stack stac
11121256
return new List<string>();
11131257
}
11141258

1259+
/// <summary>
1260+
/// Ensures an environment exists for workflow/publish rule tests: lists existing envs and uses the first, or creates "bulk_test_env" if none exist. Sets _bulkTestEnvironmentUid. Synchronous.
1261+
/// </summary>
1262+
private static void EnsureBulkTestEnvironment(Stack stack)
1263+
{
1264+
try
1265+
{
1266+
List<string> envs = GetAvailableEnvironments(stack);
1267+
if (envs != null && envs.Count > 0)
1268+
{
1269+
_bulkTestEnvironmentUid = envs[0];
1270+
return;
1271+
}
1272+
1273+
var environmentModel = new EnvironmentModel
1274+
{
1275+
Name = "bulk_test_env",
1276+
Urls = new List<LocalesUrl>
1277+
{
1278+
new LocalesUrl
1279+
{
1280+
Url = "https://bulk-test-environment.example.com",
1281+
Locale = "en-us"
1282+
}
1283+
}
1284+
};
1285+
1286+
ContentstackResponse response = stack.Environment().Create(environmentModel);
1287+
var responseJson = response.OpenJObjectResponse();
1288+
if (response.IsSuccessStatusCode && responseJson["environment"]?["uid"] != null)
1289+
_bulkTestEnvironmentUid = responseJson["environment"]["uid"].ToString();
1290+
}
1291+
catch { /* Leave _bulkTestEnvironmentUid null */ }
1292+
}
1293+
11151294
/// <summary>
11161295
/// Ensures an environment exists for workflow/publish rule tests: lists existing envs and uses the first, or creates "bulk_test_env" if none exist. Sets _bulkTestEnvironmentUid.
11171296
/// </summary>

0 commit comments

Comments
 (0)