diff --git a/CHANGELOG.md b/CHANGELOG.md index fcccf60..0abd0ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [v1.2.0](https://github.com/contentstack/contentstack-management-dotnet/tree/v1.2.0)(2026-11-12) + + - **New** + - **Branch create: optional environment list**: `BranchModel.PublishConfig` (`BranchPublishConfigModel`, with `Environments` as a list of environment names, not UIDs) lets `Branch.Create` / `CreateAsync` clone only the listed environments. `[]` clones none; leaving `PublishConfig` unset clones all environments, as before. The list is sent unchanged; an unknown name or a mix rejects with the API's 422 error (`ContentstackErrorException`, message, error code and errors unchanged) and no branch is created. + - **Branch fetch**: a fetched `BranchModel` carries `PublishConfig.Environments` as the API returns it; it is `null` when the API omits it. + - **Test** + - Unit tests for the branch create body with two names, `[]` and unset (through `Create` and `CreateAsync`), a mocked 422 rejection, and fetched branch deserialization. + - Integration tests for create with two names, `[]`, an unknown name and a mix. The test class now creates two uniquely named environments on the stack and deletes them afterwards, because the `development` and `staging` names it used before do not exist on the stack the suite creates, so the two-name case failed with a 422. Run live against the NA prod API, the four environment-list cases pass. + ## [v1.1.1](https://github.com/contentstack/contentstack-management-dotnet/tree/v1.1.1)(2026-07-30) - **Fix** diff --git a/Contentstack.Management.Core.Tests/Helpers/AssertLogger.cs b/Contentstack.Management.Core.Tests/Helpers/AssertLogger.cs index 54f9e47..9d34584 100644 --- a/Contentstack.Management.Core.Tests/Helpers/AssertLogger.cs +++ b/Contentstack.Management.Core.Tests/Helpers/AssertLogger.cs @@ -138,7 +138,9 @@ public static void Fail(string message) public static void Fail(string message, params object[] parameters) { TestOutputLogger.LogAssertion("Fail", "N/A", message ?? "", false); - Assert.Fail(message, parameters); + // MSTest 4 removed Assert.Fail(string, params object[]); it formatted the message + // with the parameters, so format here to preserve that behaviour. + Assert.Fail(parameters is { Length: > 0 } ? string.Format(message, parameters) : message); } public static void Inconclusive(string message) diff --git a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack003_StackTest.cs b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack003_StackTest.cs index 186e582..d4965e8 100644 --- a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack003_StackTest.cs +++ b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack003_StackTest.cs @@ -410,7 +410,7 @@ public void Test014_Should_Fail_When_Not_Logged_In_Stack_GetAll() { Host = "api.contentstack.io" }); - var ex = Assert.ThrowsException(() => + var ex = Assert.ThrowsExactly(() => unauthenticatedClient.Stack().GetAll()); AssertLogger.IsTrue( ex.Message.IndexOf("not logged in", StringComparison.OrdinalIgnoreCase) >= 0, @@ -444,7 +444,7 @@ public void Test015_Should_Fail_With_Invalid_Auth_Token_Stack_GetAll() public void Test016_Should_Throw_When_GetAll_With_Stack_Api_Key_Set() { TestOutputLogger.LogContext("TestScenario", "Stack_GetAll_InvalidApiKeyContext"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack(SdkNonEmptyApiKey).GetAll()); } @@ -453,7 +453,7 @@ public void Test016_Should_Throw_When_GetAll_With_Stack_Api_Key_Set() public async Task Test017_Should_Throw_When_GetAllAsync_With_Stack_Api_Key_Set() { TestOutputLogger.LogContext("TestScenario", "Stack_GetAllAsync_InvalidApiKeyContext"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack(SdkNonEmptyApiKey).GetAllAsync()); } @@ -462,7 +462,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test018_Should_Throw_When_Create_With_Stack_Api_Key_Set() { TestOutputLogger.LogContext("TestScenario", "Stack_Create_InvalidApiKeyContext"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack(SdkNonEmptyApiKey).Create(_stackName, _locale, _org.Uid)); } @@ -471,7 +471,7 @@ public void Test018_Should_Throw_When_Create_With_Stack_Api_Key_Set() public async Task Test019_Should_Throw_When_CreateAsync_With_Stack_Api_Key_Set() { TestOutputLogger.LogContext("TestScenario", "Stack_CreateAsync_InvalidApiKeyContext"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack(SdkNonEmptyApiKey).CreateAsync(_stackName, _locale, _org.Uid)); } @@ -482,7 +482,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test020_Should_Throw_When_Create_With_Invalid_Name_Sync(string invalidName) { TestOutputLogger.LogContext("TestScenario", "Stack_Create_InvalidName_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack().Create(invalidName, _locale, _org.Uid)); } @@ -493,7 +493,7 @@ public void Test020_Should_Throw_When_Create_With_Invalid_Name_Sync(string inval public async Task Test021_Should_Throw_When_CreateAsync_With_Invalid_Name(string invalidName) { TestOutputLogger.LogContext("TestScenario", "Stack_Create_InvalidName_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack().CreateAsync(invalidName, _locale, _org.Uid)); } @@ -504,7 +504,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test020b_Should_Throw_When_Create_With_Invalid_Locale_Sync(string invalidLocale) { TestOutputLogger.LogContext("TestScenario", "Stack_Create_InvalidLocale_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack().Create(_stackName, invalidLocale, _org.Uid)); } @@ -515,7 +515,7 @@ public void Test020b_Should_Throw_When_Create_With_Invalid_Locale_Sync(string in public async Task Test021b_Should_Throw_When_CreateAsync_With_Invalid_Locale(string invalidLocale) { TestOutputLogger.LogContext("TestScenario", "Stack_Create_InvalidLocale_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack().CreateAsync(_stackName, invalidLocale, _org.Uid)); } @@ -526,7 +526,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test020c_Should_Throw_When_Create_With_Invalid_OrgUid_Sync(string invalidOrg) { TestOutputLogger.LogContext("TestScenario", "Stack_Create_InvalidOrg_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack().Create(_stackName, _locale, invalidOrg)); } @@ -537,7 +537,7 @@ public void Test020c_Should_Throw_When_Create_With_Invalid_OrgUid_Sync(string in public async Task Test021c_Should_Throw_When_CreateAsync_With_Invalid_OrgUid(string invalidOrg) { TestOutputLogger.LogContext("TestScenario", "Stack_Create_InvalidOrg_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack().CreateAsync(_stackName, _locale, invalidOrg)); } @@ -546,7 +546,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test022_Should_Throw_When_Fetch_Without_Api_Key_Sync() { TestOutputLogger.LogContext("TestScenario", "Stack_Fetch_MissingApiKey_Sync"); - Assert.ThrowsException(() => _client.Stack().Fetch()); + Assert.ThrowsExactly(() => _client.Stack().Fetch()); } [TestMethod] @@ -554,7 +554,7 @@ public void Test022_Should_Throw_When_Fetch_Without_Api_Key_Sync() public async Task Test023_Should_Throw_When_FetchAsync_Without_Api_Key() { TestOutputLogger.LogContext("TestScenario", "Stack_Fetch_MissingApiKey_Async"); - await Assert.ThrowsExceptionAsync(() => _client.Stack().FetchAsync()); + await Assert.ThrowsExactlyAsync(() => _client.Stack().FetchAsync()); } [TestMethod] @@ -562,7 +562,7 @@ public async Task Test023_Should_Throw_When_FetchAsync_Without_Api_Key() public void Test024_Should_Throw_When_Update_Without_Api_Key_Sync() { TestOutputLogger.LogContext("TestScenario", "Stack_Update_MissingApiKey_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack().Update(_updatestackName)); } @@ -571,7 +571,7 @@ public void Test024_Should_Throw_When_Update_Without_Api_Key_Sync() public async Task Test025_Should_Throw_When_UpdateAsync_Without_Api_Key() { TestOutputLogger.LogContext("TestScenario", "Stack_Update_MissingApiKey_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack().UpdateAsync(_updatestackName)); } @@ -582,7 +582,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test026_Should_Throw_When_Update_With_Invalid_Name_Sync(string invalidName) { TestOutputLogger.LogContext("TestScenario", "Stack_Update_InvalidName_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack(SdkNonEmptyApiKey).Update(invalidName)); } @@ -593,7 +593,7 @@ public void Test026_Should_Throw_When_Update_With_Invalid_Name_Sync(string inval public async Task Test027_Should_Throw_When_UpdateAsync_With_Invalid_Name(string invalidName) { TestOutputLogger.LogContext("TestScenario", "Stack_Update_InvalidName_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack(SdkNonEmptyApiKey).UpdateAsync(invalidName)); } @@ -602,7 +602,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test028_Should_Throw_When_Settings_Without_Api_Key() { TestOutputLogger.LogContext("TestScenario", "Stack_Settings_MissingApiKey_Sync"); - Assert.ThrowsException(() => _client.Stack().Settings()); + Assert.ThrowsExactly(() => _client.Stack().Settings()); } [TestMethod] @@ -610,7 +610,7 @@ public void Test028_Should_Throw_When_Settings_Without_Api_Key() public async Task Test029_Should_Throw_When_SettingsAsync_Without_Api_Key() { TestOutputLogger.LogContext("TestScenario", "Stack_Settings_MissingApiKey_Async"); - await Assert.ThrowsExceptionAsync(() => _client.Stack().SettingsAsync()); + await Assert.ThrowsExactlyAsync(() => _client.Stack().SettingsAsync()); } [TestMethod] @@ -618,7 +618,7 @@ public async Task Test029_Should_Throw_When_SettingsAsync_Without_Api_Key() public void Test030_Should_Throw_When_ResetSettings_Without_Api_Key_Sync() { TestOutputLogger.LogContext("TestScenario", "Stack_ResetSettings_MissingApiKey_Sync"); - Assert.ThrowsException(() => _client.Stack().ResetSettings()); + Assert.ThrowsExactly(() => _client.Stack().ResetSettings()); } [TestMethod] @@ -626,7 +626,7 @@ public void Test030_Should_Throw_When_ResetSettings_Without_Api_Key_Sync() public async Task Test031_Should_Throw_When_ResetSettingsAsync_Without_Api_Key() { TestOutputLogger.LogContext("TestScenario", "Stack_ResetSettings_MissingApiKey_Async"); - await Assert.ThrowsExceptionAsync(() => _client.Stack().ResetSettingsAsync()); + await Assert.ThrowsExactlyAsync(() => _client.Stack().ResetSettingsAsync()); } [TestMethod] @@ -634,7 +634,7 @@ public async Task Test031_Should_Throw_When_ResetSettingsAsync_Without_Api_Key() public void Test032_Should_Throw_When_AddSettings_Null_Sync() { TestOutputLogger.LogContext("TestScenario", "Stack_AddSettings_Null_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack(SdkNonEmptyApiKey).AddSettings(null)); } @@ -643,7 +643,7 @@ public void Test032_Should_Throw_When_AddSettings_Null_Sync() public async Task Test033_Should_Throw_When_AddSettingsAsync_Null() { TestOutputLogger.LogContext("TestScenario", "Stack_AddSettings_Null_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack(SdkNonEmptyApiKey).AddSettingsAsync(null)); } @@ -836,7 +836,7 @@ public void Test044_Should_Fail_Create_With_Bogus_Organization_Uid() public void Test045_Should_Throw_When_Share_Invitations_Null_Sync() { TestOutputLogger.LogContext("TestScenario", "Stack_Share_NullInvitations_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack(SdkNonEmptyApiKey).Share(null)); } @@ -845,7 +845,7 @@ public void Test045_Should_Throw_When_Share_Invitations_Null_Sync() public async Task Test046_Should_Throw_When_ShareAsync_Invitations_Null() { TestOutputLogger.LogContext("TestScenario", "Stack_Share_NullInvitations_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack(SdkNonEmptyApiKey).ShareAsync(null)); } @@ -854,7 +854,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test047_Should_Throw_When_UnShare_Email_Null_Sync() { TestOutputLogger.LogContext("TestScenario", "Stack_UnShare_NullEmail_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack(SdkNonEmptyApiKey).UnShare(null)); } @@ -863,7 +863,7 @@ public void Test047_Should_Throw_When_UnShare_Email_Null_Sync() public async Task Test048_Should_Throw_When_UnShareAsync_Email_Null() { TestOutputLogger.LogContext("TestScenario", "Stack_UnShare_NullEmail_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack(SdkNonEmptyApiKey).UnShareAsync(null)); } @@ -956,7 +956,7 @@ public async Task Test052_Should_Fail_UnShareAsync_Malformed_Email() public void Test053_Should_Throw_When_UpdateUserRole_Null_List_Sync() { TestOutputLogger.LogContext("TestScenario", "Stack_UpdateUserRole_Null_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack(SdkNonEmptyApiKey).UpdateUserRole(null)); } @@ -965,7 +965,7 @@ public void Test053_Should_Throw_When_UpdateUserRole_Null_List_Sync() public async Task Test054_Should_Throw_When_UpdateUserRoleAsync_Null_List() { TestOutputLogger.LogContext("TestScenario", "Stack_UpdateUserRole_Null_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack(SdkNonEmptyApiKey).UpdateUserRoleAsync(null)); } @@ -1074,7 +1074,7 @@ public void Test058_Should_Throw_When_UpdateUserRole_Null_User_Uid_In_List() public void Test059_Should_Throw_When_TransferOwnership_Email_Null_Sync() { TestOutputLogger.LogContext("TestScenario", "Stack_TransferOwnership_NullEmail_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack(SdkNonEmptyApiKey).TransferOwnership(null)); } @@ -1083,7 +1083,7 @@ public void Test059_Should_Throw_When_TransferOwnership_Email_Null_Sync() public async Task Test060_Should_Throw_When_TransferOwnershipAsync_Email_Null() { TestOutputLogger.LogContext("TestScenario", "Stack_TransferOwnership_NullEmail_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack(SdkNonEmptyApiKey).TransferOwnershipAsync(null)); } @@ -1092,7 +1092,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test061_Should_Throw_When_TransferOwnership_Email_Empty_Sync() { TestOutputLogger.LogContext("TestScenario", "Stack_TransferOwnership_EmptyEmail_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _client.Stack(SdkNonEmptyApiKey).TransferOwnership(string.Empty)); } @@ -1101,7 +1101,7 @@ public void Test061_Should_Throw_When_TransferOwnership_Email_Empty_Sync() public async Task Test062_Should_Throw_When_TransferOwnershipAsync_Email_Empty() { TestOutputLogger.LogContext("TestScenario", "Stack_TransferOwnership_EmptyEmail_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _client.Stack(SdkNonEmptyApiKey).TransferOwnershipAsync(string.Empty)); } diff --git a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack004_ReleaseTest.cs b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack004_ReleaseTest.cs index 3ffb898..4c7d0d5 100644 --- a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack004_ReleaseTest.cs +++ b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack004_ReleaseTest.cs @@ -1292,7 +1292,7 @@ public void Test031_Should_Throw_When_Clone_With_Null_Name() try { releaseUid = CreateTestRelease(); - Assert.ThrowsException(() => _stack.Release(releaseUid).Clone(null, _testReleaseDescription)); + Assert.ThrowsExactly(() => _stack.Release(releaseUid).Clone(null, _testReleaseDescription)); } finally { @@ -1311,7 +1311,7 @@ public async Task Test032_Should_Throw_When_Clone_With_Null_Name_Async() try { releaseUid = await CreateTestReleaseAsync(); - await Assert.ThrowsExceptionAsync(() => _stack.Release(releaseUid).CloneAsync(null, _testReleaseDescription)); + await Assert.ThrowsExactlyAsync(() => _stack.Release(releaseUid).CloneAsync(null, _testReleaseDescription)); } finally { diff --git a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack005_BranchTest.cs b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack005_BranchTest.cs index 430dbe5..5ba0e99 100644 --- a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack005_BranchTest.cs +++ b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack005_BranchTest.cs @@ -1,5 +1,8 @@ using System; +using System.Collections.Generic; +using System.Linq; using System.Net; +using System.Text.Json.Nodes; using System.Threading.Tasks; using Contentstack.Management.Core.Exceptions; using Contentstack.Management.Core.Models; @@ -24,6 +27,18 @@ public class Contentstack005_BranchTest private const string TestBranchUidAsync = "dotnet_int_br_a"; // max 15 chars, alphanumeric+underscore private const string NonExistentBranchUid = "dotnet_no_br"; + // publish_config.environments: names (not UIDs) that must exist on the test stack. + // Set these to two real environment names on the stack before running the live suite. + private static readonly string EnvironmentOne = "dotnet_brenv_" + Guid.NewGuid().ToString("N").Substring(0,6); + private static string _envOneUid; + private static readonly string EnvironmentTwo = "dotnet_brenv_" + Guid.NewGuid().ToString("N").Substring(0,6); + private static string _envTwoUid; + private const string UnknownEnvironment = "dotnet_no_env_99999"; + private const string EnvTwoBranchUid = "dotnet_env_two"; // max 15 chars, alphanumeric+underscore + private const string EnvNoneBranchUid = "dotnet_env_none"; // max 15 chars, alphanumeric+underscore + private const string EnvUnknownBranchUid = "dotnet_env_unk"; // max 15 chars, alphanumeric+underscore + private const string EnvMixBranchUid = "dotnet_env_mix"; // max 15 chars, alphanumeric+underscore + [ClassInitialize] public static void ClassInitialize(TestContext context) { @@ -31,9 +46,16 @@ public static void ClassInitialize(TestContext context) StackResponse response = StackResponse.getStack(_client.serializer); _stack = _client.Stack(response.Stack.APIKey); + _envOneUid = CreateTestEnvironment(EnvironmentOne); + _envTwoUid = CreateTestEnvironment(EnvironmentTwo); + // Best-effort cleanup of any branches left over from a previous test run TryDeleteBranch(TestBranchUid); TryDeleteBranch(TestBranchUidAsync); + TryDeleteBranch(EnvTwoBranchUid); + TryDeleteBranch(EnvNoneBranchUid); + TryDeleteBranch(EnvUnknownBranchUid); + TryDeleteBranch(EnvMixBranchUid); } [ClassCleanup] @@ -41,11 +63,29 @@ public static void ClassCleanup() { TryDeleteBranch(_createdBranchUid); TryDeleteBranch(_createdBranchUidAsync); + TryDeleteBranch(EnvTwoBranchUid); + TryDeleteBranch(EnvNoneBranchUid); + TryDeleteBranch(EnvUnknownBranchUid); + TryDeleteBranch(EnvMixBranchUid); + + try { if (_envOneUid != null) _stack.Environment(_envOneUid).Delete(); } catch { } + try { if (_envTwoUid != null) _stack.Environment(_envTwoUid).Delete(); } catch { } try { _client?.Logout(); } catch { } _client = null; } + private static string CreateTestEnvironment(string name) + { + var model = new EnvironmentModel + { + Name = name, + Urls = new List { new LocalesUrl { Locale = "en-us", Url = "https://example.com" } } + }; + ContentstackResponse r = _stack.Environment().Create(model); + return r.IsSuccessStatusCode ? r.OpenJsonObjectResponse()["environment"]?["uid"]?.ToString() : null; + } + private static void TryDeleteBranch(string uid) { if (string.IsNullOrEmpty(uid)) return; @@ -320,7 +360,7 @@ private static async Task RetryOnBranchProvisioningAsync(F public void Test012_Should_Throw_When_Query_Called_With_Uid() { TestOutputLogger.LogContext("TestScenario", "Branch_Query_WithUid_Throws"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _stack.Branch("some-uid").Query()); } @@ -329,7 +369,7 @@ public void Test012_Should_Throw_When_Query_Called_With_Uid() public void Test013_Should_Throw_When_Fetch_Called_Without_Uid() { TestOutputLogger.LogContext("TestScenario", "Branch_Fetch_NoUid_Throws_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _stack.Branch().Fetch()); } @@ -338,7 +378,7 @@ public void Test013_Should_Throw_When_Fetch_Called_Without_Uid() public async Task Test014_Should_Throw_When_FetchAsync_Called_Without_Uid() { TestOutputLogger.LogContext("TestScenario", "Branch_Fetch_NoUid_Throws_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _stack.Branch().FetchAsync()); } @@ -347,7 +387,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test015_Should_Throw_When_Delete_Called_Without_Uid() { TestOutputLogger.LogContext("TestScenario", "Branch_Delete_NoUid_Throws_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _stack.Branch().Delete()); } @@ -356,7 +396,7 @@ public void Test015_Should_Throw_When_Delete_Called_Without_Uid() public async Task Test016_Should_Throw_When_DeleteAsync_Called_Without_Uid() { TestOutputLogger.LogContext("TestScenario", "Branch_Delete_NoUid_Throws_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _stack.Branch().DeleteAsync()); } @@ -365,7 +405,7 @@ await Assert.ThrowsExceptionAsync(() => public void Test017_Should_Throw_When_Create_Called_With_Uid() { TestOutputLogger.LogContext("TestScenario", "Branch_Create_WithUid_Throws_Sync"); - Assert.ThrowsException(() => + Assert.ThrowsExactly(() => _stack.Branch("some-uid").Create(new BranchModel())); } @@ -374,7 +414,7 @@ public void Test017_Should_Throw_When_Create_Called_With_Uid() public async Task Test018_Should_Throw_When_CreateAsync_Called_With_Uid() { TestOutputLogger.LogContext("TestScenario", "Branch_Create_WithUid_Throws_Async"); - await Assert.ThrowsExceptionAsync(() => + await Assert.ThrowsExactlyAsync(() => _stack.Branch("some-uid").CreateAsync(new BranchModel())); } @@ -504,8 +544,132 @@ public void Test025_Should_Fail_Create_Duplicate_Branch() } } + // ---- Create with publish_config.environments --------------------------- + + [TestMethod] + [DoNotParallelize] + public void Test026_Should_Create_Branch_With_Two_Environment_Names() + { + TestOutputLogger.LogContext("TestScenario", "Branch_Create_TwoEnvironments"); + try + { + var model = NewEnvironmentBranch(EnvTwoBranchUid, EnvironmentOne, EnvironmentTwo); + ContentstackResponse response = _stack.Branch().Create(model); + AssertLogger.IsNotNull(response.OpenJsonObjectResponse(), "response"); + AssertEnvironmentsEqual(response, "Branch_Create_TwoEnvironments", EnvironmentOne, EnvironmentTwo); + } + catch (Exception e) + { + AssertLogger.Fail(e.Message); + } + } + + [TestMethod] + [DoNotParallelize] + public void Test027_Should_Create_Branch_With_Empty_Environment_List() + { + TestOutputLogger.LogContext("TestScenario", "Branch_Create_EmptyEnvironments"); + try + { + var model = NewEnvironmentBranch(EnvNoneBranchUid); + ContentstackResponse response = _stack.Branch().Create(model); + AssertLogger.IsNotNull(response.OpenJsonObjectResponse(), "response"); + // [] must read back as an empty list (present, not null), so assert it is not null first + AssertEnvironmentsEqual(response, "Branch_Create_EmptyEnvironments"); + } + catch (Exception e) + { + AssertLogger.Fail(e.Message); + } + } + + [TestMethod] + [DoNotParallelize] + public void Test028_Should_Reject_Create_With_Unknown_Environment_Name() + { + TestOutputLogger.LogContext("TestScenario", "Branch_Create_UnknownEnvironment"); + var model = NewEnvironmentBranch(EnvUnknownBranchUid, UnknownEnvironment); + try + { + _stack.Branch().Create(model); + AssertLogger.Fail("Expected API error for an unknown environment name"); + } + catch (ContentstackErrorException ex) + { + AssertEnvironmentRejected(ex, EnvUnknownBranchUid, "Branch_Create_UnknownEnvironment"); + } + } + + [TestMethod] + [DoNotParallelize] + public void Test029_Should_Reject_Create_With_Mix_Of_Valid_And_Unknown_Environment_Names() + { + TestOutputLogger.LogContext("TestScenario", "Branch_Create_MixedEnvironments"); + var model = NewEnvironmentBranch(EnvMixBranchUid, EnvironmentOne, UnknownEnvironment); + try + { + _stack.Branch().Create(model); + AssertLogger.Fail("Expected API error for a mix of valid and unknown environment names"); + } + catch (ContentstackErrorException ex) + { + AssertEnvironmentRejected(ex, EnvMixBranchUid, "Branch_Create_MixedEnvironments"); + } + } + // ---- Helper methods --------------------------------------------------- + private static BranchModel NewEnvironmentBranch(string uid, params string[] environments) + { + return new BranchModel + { + Uid = uid, + Source = SourceBranch, + PublishConfig = new BranchPublishConfigModel { Environments = new List(environments) } + }; + } + + private static List EnvironmentsOf(ContentstackResponse response) + { + JsonNode node = response.OpenJsonObjectResponse()["branch"]?["publish_config"]?["environments"]; + return node?.AsArray().Select(n => n!.GetValue()).ToList(); + } + + private static void AssertEnvironmentsEqual(ContentstackResponse response, string assertionName, params string[] expected) + { + List names = EnvironmentsOf(response); + AssertLogger.IsNotNull(names, "publish_config.environments"); + AssertLogger.IsTrue( + names.SequenceEqual(expected), + $"Expected environments [{string.Join(", ", expected)}] but got [{string.Join(", ", names)}]", + assertionName); + } + + private static void AssertEnvironmentRejected(ContentstackErrorException ex, string uid, string assertionName) + { + AssertLogger.IsTrue( + ex.StatusCode == (HttpStatusCode)422, + $"Expected 422, got {(int)ex.StatusCode} ({ex.StatusCode})", + assertionName); + AssertLogger.IsTrue( + ex.Errors != null && ex.Errors.ContainsKey("publish_config.environments"), + "Expected the API error to be keyed publish_config.environments", + assertionName); + + // No branch may be created when the request is rejected + bool exists; + try + { + _stack.Branch(uid).Fetch(); + exists = true; + } + catch (ContentstackErrorException) + { + exists = false; + } + AssertLogger.IsTrue(!exists, "A rejected create must not leave a branch behind", assertionName); + } + private static void AssertBranchApiError(ContentstackErrorException ex, string assertionName) { AssertLogger.IsTrue( diff --git a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack012_NestedGlobalFieldTest.cs b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack012_NestedGlobalFieldTest.cs index adaae64..880c247 100644 --- a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack012_NestedGlobalFieldTest.cs +++ b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack012_NestedGlobalFieldTest.cs @@ -1317,7 +1317,7 @@ public void Test028_Should_Fail_Fetch_With_Empty_UID() { TestOutputLogger.LogContext("TestScenario", "FetchNestedGlobalField_EmptyUID"); - Assert.ThrowsException( + Assert.ThrowsExactly( () => _stack.GlobalField("").Fetch(), "Expected ArgumentException for empty UID"); } @@ -1329,7 +1329,7 @@ public void Test029_Should_Fail_Update_With_Empty_UID() TestOutputLogger.LogContext("TestScenario", "UpdateNestedGlobalField_EmptyUID"); var updateModel = CreateNestedGlobalFieldModel(); - Assert.ThrowsException( + Assert.ThrowsExactly( () => _stack.GlobalField("").Update(updateModel), "Expected ArgumentException for empty UID"); } @@ -1340,7 +1340,7 @@ public void Test030_Should_Fail_Delete_With_Empty_UID() { TestOutputLogger.LogContext("TestScenario", "DeleteNestedGlobalField_EmptyUID"); - Assert.ThrowsException( + Assert.ThrowsExactly( () => _stack.GlobalField("").Delete(), "Expected ArgumentException for empty UID"); } @@ -1352,7 +1352,7 @@ public void Test031_Should_Fail_Create_With_UID_Set() TestOutputLogger.LogContext("TestScenario", "CreateNestedGlobalField_UIDSet"); var model = CreateNestedGlobalFieldModel(); - Assert.ThrowsException( + Assert.ThrowsExactly( () => _stack.GlobalField("some_uid").Create(model), "Expected InvalidOperationException when UID is set for create operation"); } @@ -1363,7 +1363,7 @@ public void Test032_Should_Fail_Query_With_UID_Set() { TestOutputLogger.LogContext("TestScenario", "QueryNestedGlobalField_UIDSet"); - Assert.ThrowsException( + Assert.ThrowsExactly( () => _stack.GlobalField("some_uid").Query().Find(), "Expected InvalidOperationException when UID is set for query operation"); } diff --git a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack023_PreviewTokenTest.cs b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack023_PreviewTokenTest.cs index 4c90ed7..dd57d32 100644 --- a/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack023_PreviewTokenTest.cs +++ b/Contentstack.Management.Core.Tests/IntegrationTest/Contentstack023_PreviewTokenTest.cs @@ -36,7 +36,7 @@ public static void ClassInitialize(TestContext _) _client = Contentstack.CreateAuthenticatedClient(); } - [ClassCleanup(ClassCleanupBehavior.EndOfClass)] + [ClassCleanup] public static void ClassCleanup() { try { _client?.Logout(); } catch { } diff --git a/Contentstack.Management.Core.Unit.Tests/Models/BranchTest.cs b/Contentstack.Management.Core.Unit.Tests/Models/BranchTest.cs index f958c36..5c9c66f 100644 --- a/Contentstack.Management.Core.Unit.Tests/Models/BranchTest.cs +++ b/Contentstack.Management.Core.Unit.Tests/Models/BranchTest.cs @@ -1,7 +1,20 @@ using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using System.Threading.Tasks; using AutoFixture; +using Contentstack.Management.Core.Exceptions; +using Contentstack.Management.Core.Internal; using Contentstack.Management.Core.Models; using Contentstack.Management.Core.Queryable; +using Contentstack.Management.Core.Runtime.Contexts; +using Contentstack.Management.Core.Runtime.Pipeline; +using Contentstack.Management.Core.Services; using Contentstack.Management.Core.Unit.Tests.Mokes; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -63,6 +76,243 @@ public void Should_Query_Branches_With_Params() StringAssert.Contains(_mockHandler.LastRequestUri.Query, "limit=2"); StringAssert.Contains(_mockHandler.LastRequestUri.Query, "skip=2"); } + + [TestMethod] + public void Create_Sends_Environment_Names_As_Given() + { + var handler = new BranchRequestHandler(JsonResponse(HttpStatusCode.Created, BranchJson)); + var model = NewBranchWithEnvironments("development", "staging"); + + StackWith(handler).Branch().Create(model); + + AssertEnvironmentsSent(handler.LastRequestBody, "development", "staging"); + } + + [TestMethod] + public async Task CreateAsync_Sends_Environment_Names_As_Given() + { + var handler = new BranchRequestHandler(JsonResponse(HttpStatusCode.Created, BranchJson)); + var model = NewBranchWithEnvironments("development", "staging"); + + await StackWith(handler).Branch().CreateAsync(model); + + AssertEnvironmentsSent(handler.LastRequestBody, "development", "staging"); + } + + [TestMethod] + public void Create_Sends_Empty_Environment_List_As_Empty_Array() + { + var handler = new BranchRequestHandler(JsonResponse(HttpStatusCode.Created, BranchJson)); + var model = NewBranchWithEnvironments(); + + StackWith(handler).Branch().Create(model); + + AssertEnvironmentsSent(handler.LastRequestBody); + } + + [TestMethod] + public async Task CreateAsync_Sends_Empty_Environment_List_As_Empty_Array() + { + var handler = new BranchRequestHandler(JsonResponse(HttpStatusCode.Created, BranchJson)); + var model = NewBranchWithEnvironments(); + + await StackWith(handler).Branch().CreateAsync(model); + + AssertEnvironmentsSent(handler.LastRequestBody); + } + + [TestMethod] + public void Create_Without_PublishConfig_Omits_The_Key() + { + var handler = new BranchRequestHandler(JsonResponse(HttpStatusCode.Created, BranchJson)); + var model = new BranchModel { Uid = "dev", Source = "main" }; + + StackWith(handler).Branch().Create(model); + + AssertNoPublishConfigSent(handler.LastRequestBody); + } + + [TestMethod] + public async Task CreateAsync_Without_PublishConfig_Omits_The_Key() + { + var handler = new BranchRequestHandler(JsonResponse(HttpStatusCode.Created, BranchJson)); + var model = new BranchModel { Uid = "dev", Source = "main" }; + + await StackWith(handler).Branch().CreateAsync(model); + + AssertNoPublishConfigSent(handler.LastRequestBody); + } + + [TestMethod] + public void Create_Rejected_With_422_Throws_With_Api_Error_Unchanged() + { + var handler = new BranchRequestHandler(ErrorResponse()); + var model = NewBranchWithEnvironments("development", "staging_typo"); + + var ex = Assert.ThrowsException(() => StackWith(handler).Branch().Create(model)); + + AssertRejectedWithApiError(ex, handler.LastRequestBody); + } + + [TestMethod] + public async Task CreateAsync_Rejected_With_422_Throws_With_Api_Error_Unchanged() + { + var handler = new BranchRequestHandler(ErrorResponse()); + var model = NewBranchWithEnvironments("development", "staging_typo"); + + var ex = await Assert.ThrowsExceptionAsync(() => StackWith(handler).Branch().CreateAsync(model)); + + AssertRejectedWithApiError(ex, handler.LastRequestBody); + } + + [TestMethod] + public void Fetch_Deserializes_Environment_List_Into_Model() + { + const string json = "{\"branch\":{\"uid\":\"dev\",\"source\":\"main\",\"publish_config\":{\"environments\":[\"development\",\"staging\"]}}}"; + var handler = new BranchRequestHandler(JsonResponse(HttpStatusCode.OK, json)); + + ContentstackResponse response = StackWith(handler).Branch("dev").Fetch(); + BranchResponse fetched = response.OpenTResponse(); + + Assert.IsNotNull(fetched.Branch?.PublishConfig); + CollectionAssert.AreEqual(new List { "development", "staging" }, fetched.Branch.PublishConfig.Environments); + } + + [TestMethod] + public void Fetch_Without_PublishConfig_Leaves_It_Null() + { + var handler = new BranchRequestHandler(JsonResponse(HttpStatusCode.OK, BranchJson)); + + ContentstackResponse response = StackWith(handler).Branch("dev").Fetch(); + BranchResponse fetched = response.OpenTResponse(); + + Assert.IsNotNull(fetched.Branch); + Assert.IsNull(fetched.Branch.PublishConfig); + } + + // ---- helpers ----------------------------------------------------------- + + private const string BranchJson = "{\"branch\":{\"uid\":\"dev\",\"source\":\"main\"}}"; + + private Stack StackWith(IPipelineHandler handler) + { + var client = new ContentstackClient(); + client.ContentstackPipeline.ReplaceHandler(handler); + client.contentstackOptions.Authtoken = _fixture.Create(); + return new Stack(client, _fixture.Create()); + } + + private static BranchModel NewBranchWithEnvironments(params string[] environments) + { + return new BranchModel + { + Uid = "dev", + Source = "main", + PublishConfig = new BranchPublishConfigModel { Environments = new List(environments) } + }; + } + + private static ContentstackResponse JsonResponse(HttpStatusCode statusCode, string json) + { + return new ContentstackResponse(MockResponse.Create(statusCode, null, json), new JsonSerializerOptions()); + } + + private static HttpResponseMessage ErrorResponse() + { + const string json = "{\"error_message\":\"Environment not found.\",\"error_code\":422," + + "\"errors\":{\"publish_config.environments\":[\"staging_typo\"]}}"; + return MockResponse.Create((HttpStatusCode)422, null, json); + } + + private static JsonObject SentBranch(string body) + { + Assert.IsNotNull(body, "no request body was captured"); + return JsonNode.Parse(body)!["branch"]!.AsObject(); + } + + private static void AssertEnvironmentsSent(string body, params string[] expected) + { + JsonNode publishConfig = SentBranch(body)["publish_config"]; + Assert.IsNotNull(publishConfig, "publish_config was not sent"); + JsonNode environments = publishConfig["environments"]; + Assert.IsInstanceOfType(environments, typeof(JsonArray), "environments must be sent as a JSON array"); + CollectionAssert.AreEqual(expected, environments.AsArray().Select(n => n!.GetValue()).ToList()); + } + + private static void AssertNoPublishConfigSent(string body) + { + Assert.IsFalse(SentBranch(body).ContainsKey("publish_config"), "publish_config must be omitted when unset"); + } + + private static void AssertRejectedWithApiError(ContentstackErrorException ex, string body) + { + Assert.AreEqual(HttpStatusCode.UnprocessableEntity, ex.StatusCode); + Assert.AreEqual("Environment not found.", ex.Message); + Assert.AreEqual("Environment not found.", ex.ErrorMessage); + Assert.AreEqual(422, ex.ErrorCode); + Assert.IsNotNull(ex.Errors); + Assert.AreEqual("[\"staging_typo\"]", JsonSerializer.Serialize(ex.Errors["publish_config.environments"])); + AssertEnvironmentsSent(body, "development", "staging_typo"); + } + + private sealed class BranchResponse + { + [JsonPropertyName("branch")] + public BranchModel Branch { get; set; } + } + + /// + /// Stands in for the HTTP handler. It builds the request exactly as production does, records the + /// JSON body that would be sent, then either returns the canned response or throws the canned error + /// through the SDK's own error factory. + /// + private sealed class BranchRequestHandler : IPipelineHandler + { + private readonly ContentstackResponse _response; + private readonly HttpResponseMessage _error; + + public BranchRequestHandler(ContentstackResponse response) + { + _response = response; + } + + public BranchRequestHandler(HttpResponseMessage error) + { + _error = error; + } + + public string LastRequestBody { get; private set; } + + public ILogManager LogManager { get; set; } + public IPipelineHandler InnerHandler { get; set; } + + public void InvokeSync(IExecutionContext executionContext, bool addAcceptMediaHeader = false, string apiVersion = null) + { + Capture(executionContext); + if (_error != null) + { + throw ContentstackErrorException.CreateException(_error); + } + executionContext.ResponseContext.httpResponse = _response; + } + + public Task InvokeAsync(IExecutionContext executionContext, bool addAcceptMediaHeader = false, string apiVersion = null) + { + Capture(executionContext); + if (_error != null) + { + throw ContentstackErrorException.CreateException(_error); + } + executionContext.ResponseContext.httpResponse = _response; + return Task.FromResult((T)executionContext.ResponseContext.httpResponse); + } + + private void Capture(IExecutionContext executionContext) + { + IContentstackService service = executionContext.RequestContext.service; + service.CreateHttpRequest(null, executionContext.RequestContext.config); + LastRequestBody = service.Content?.ReadAsStringAsync().GetAwaiter().GetResult(); + } + } } } - diff --git a/Contentstack.Management.Core/Models/Branch.cs b/Contentstack.Management.Core/Models/Branch.cs index 1fb91c9..5aededb 100644 --- a/Contentstack.Management.Core/Models/Branch.cs +++ b/Contentstack.Management.Core/Models/Branch.cs @@ -32,11 +32,15 @@ public Query Query() /// /// The Create branch call creates a new branch in a stack. + /// Set with (environment names, not UIDs) to choose which environments the branch clones: + /// a list of names clones only those environments; an empty list clones none; leaving PublishConfig unset clones all environments, as before. + /// The list is sent unchanged. The SDK does not validate the names or limit the list length. An unknown name, or any other validation failure, + /// throws carrying the API's error message, error code and errors, and no branch is created. /// /// ///

         /// ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");
-        /// BranchModel model = new BranchModel() { Uid = "my-branch", Source = "main" };
+        /// BranchModel model = new BranchModel() { Uid = "my-branch", Source = "main", PublishConfig = new BranchPublishConfigModel() { Environments = new List<string> { "development", "staging" } } };
         /// ContentstackResponse contentstackResponse = client.Stack("<API_KEY>").Branch().Create(model);
         /// 
///
@@ -49,11 +53,15 @@ public override ContentstackResponse Create(BranchModel model, ParameterCollecti /// /// The Create branch call creates a new branch in a stack. + /// Set with (environment names, not UIDs) to choose which environments the branch clones: + /// a list of names clones only those environments; an empty list clones none; leaving PublishConfig unset clones all environments, as before. + /// The list is sent unchanged. The SDK does not validate the names or limit the list length. An unknown name, or any other validation failure, + /// throws carrying the API's error message, error code and errors, and no branch is created. /// /// ///

         /// ContentstackClient client = new ContentstackClient("<AUTHTOKEN>", "<API_HOST>");
-        /// BranchModel model = new BranchModel() { Uid = "my-branch", Source = "main" };
+        /// BranchModel model = new BranchModel() { Uid = "my-branch", Source = "main", PublishConfig = new BranchPublishConfigModel() { Environments = new List<string> { "development", "staging" } } };
         /// ContentstackResponse contentstackResponse = await client.Stack("<API_KEY>").Branch().CreateAsync(model);
         /// 
///
diff --git a/Contentstack.Management.Core/Models/BranchModel.cs b/Contentstack.Management.Core/Models/BranchModel.cs index 3d95542..26d78e9 100644 --- a/Contentstack.Management.Core/Models/BranchModel.cs +++ b/Contentstack.Management.Core/Models/BranchModel.cs @@ -9,6 +9,19 @@ public class BranchAliasModel public string? Uid { get; set; } } + /// + /// Publish configuration for a branch. lists the environment names (not UIDs) to clone. + /// + public class BranchPublishConfigModel + { + /// + /// Environment names to clone into the branch. An empty list clones none; leaving the publish config unset clones all environments. + /// The list is sent unchanged; the SDK does not validate the names or limit the list length. + /// + [JsonPropertyName("environments")] + public List? Environments { get; set; } + } + public class BranchModel { [JsonPropertyName("uid")] @@ -31,6 +44,9 @@ public class BranchModel [JsonPropertyName("alias")] public List? Alias { get; set; } + + [JsonPropertyName("publish_config")] + public BranchPublishConfigModel? PublishConfig { get; set; } } } diff --git a/Directory.Build.props b/Directory.Build.props index ee78b2c..8bdd5df 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,5 +1,5 @@ - 1.1.1 + 1.2.0