diff --git a/build/Build.cs b/build/Build.cs index 4c8423a..e808a5a 100644 --- a/build/Build.cs +++ b/build/Build.cs @@ -1,12 +1,4 @@ -using Nuke.Common; -using Nuke.Common.Execution; -using Nuke.Common.IO; -using Nuke.Common.ProjectModel; -using Nuke.Common.Tools.DotNet; -using Nuke.Common.Tools.OctoVersion; -using Nuke.Common.Utilities.Collections; -using static Nuke.Common.IO.FileSystemTasks; -using static Nuke.Common.Tools.DotNet.DotNetTasks; +using System; [UnsetVisualStudioEnvironmentVariables] class Build : NukeBuild @@ -16,15 +8,14 @@ class Build : NukeBuild [Solution] readonly Solution Solution; [Parameter("Branch name for OctoVersion to use to calculate the version number. Can be set via the environment variable OCTOVERSION_CurrentBranch.", - Name = "OCTOVERSION_CurrentBranch")] - readonly string BranchName; + Name = "OCTOVERSION_CurrentBranch")] + readonly string BranchName; - [Parameter("Whether to auto-detect the branch name - this is okay for a local build, but should not be used under CI.")] - readonly bool AutoDetectBranch = IsLocalBuild; + [Parameter("Whether to auto-detect the branch name - this is okay for a local build, but should not be used under CI.")] readonly bool AutoDetectBranch = IsLocalBuild; - [OctoVersion(UpdateBuildNumber = true, BranchParameter = nameof(BranchName), - AutoDetectBranchParameter = nameof(AutoDetectBranch), Framework = "net6.0")] - readonly OctoVersionInfo OctoVersionInfo; + [OctoVersion(UpdateBuildNumber = true, BranchParameter = nameof(BranchName), + AutoDetectBranchParameter = nameof(AutoDetectBranch), Framework = "net6.0")] + readonly OctoVersionInfo OctoVersionInfo; AbsolutePath SourceDirectory => RootDirectory / "source"; AbsolutePath ArtifactsDirectory => RootDirectory / "artifacts"; diff --git a/source/Tests/AssertionExtensions.cs b/source/Tests/AssertionExtensions.cs index e0030d3..f9ad4ba 100644 --- a/source/Tests/AssertionExtensions.cs +++ b/source/Tests/AssertionExtensions.cs @@ -1,11 +1,9 @@ using System; using Octopus.Ocl; -namespace Tests +namespace Tests; + +public static class AssertionExtensions { - public static class AssertionExtensions - { - public static OclBodyAssertions Should(this OclBody? subject) - => new OclBodyAssertions(subject); - } + public static OclBodyAssertions Should(this OclBody? subject) => new(subject); } \ No newline at end of file diff --git a/source/Tests/Converters/BlockOclConverterFixture.cs b/source/Tests/Converters/BlockOclConverterFixture.cs index 9d7c1dc..4816d40 100644 --- a/source/Tests/Converters/BlockOclConverterFixture.cs +++ b/source/Tests/Converters/BlockOclConverterFixture.cs @@ -5,62 +5,61 @@ using Octopus.Ocl; using Octopus.Ocl.Converters; -namespace Tests.Converters +namespace Tests.Converters; + +public class BlockOclConverterFixture { - public class BlockOclConverterFixture + [Test] + public void NameCaseIsKept() { - [Test] - public void NameCaseIsKept() - { - var context = new OclConversionContext(new OclSerializerOptions()); - var data = new object(); - var result = (OclBlock)new DefaultBlockOclConverter().ToElements(context, typeof(WithIndexer).GetProperty(nameof(WithIndexer.MyProp))!, data).Single(); - result.Name.Should().Be("my_prop"); - } + var context = new OclConversionContext(new OclSerializerOptions()); + var data = new object(); + var result = (OclBlock)new DefaultBlockOclConverter().ToElements(context, typeof(WithIndexer).GetProperty(nameof(WithIndexer.MyProp))!, data).Single(); + result.Name.Should().Be("my_prop"); + } - [Test] - public void AttributesComeBeforeBlocks() + [Test] + public void AttributesComeBeforeBlocks() + { + var context = new OclConversionContext(new OclSerializerOptions()); + var data = new { - var context = new OclConversionContext(new OclSerializerOptions()); - var data = new + MyBlock = new { BlockProp = "OtherValue" }, + MyProp = "MyValue" + }; + var result = (OclBlock)new DefaultBlockOclConverter().ToElements(context, typeof(WithIndexer).GetProperty(nameof(WithIndexer.MyProp)), data).Single(); + result.First() + .Should() + .BeEquivalentTo(new OclAttribute("my_prop", "MyValue")); + } + + [Test] + public void IndexersAreIgnored() + { + var context = new OclConversionContext(new OclSerializerOptions()); + var data = + new Dummy { - MyBlock = new { BlockProp = "OtherValue" }, - MyProp = "MyValue" + Foo = new WithIndexer() }; - var result = (OclBlock)new DefaultBlockOclConverter().ToElements(context, typeof(WithIndexer).GetProperty(nameof(WithIndexer.MyProp)), data).Single(); - result.First() - .Should() - .BeEquivalentTo(new OclAttribute("my_prop", "MyValue")); - } - - [Test] - public void IndexersAreIgnored() - { - var context = new OclConversionContext(new OclSerializerOptions()); - var data = - new Dummy + var result = (OclBlock)new DefaultBlockOclConverter().ToElements(context, typeof(Dummy).GetProperty(nameof(Dummy.Foo)), data.Foo).Single(); + result.Should() + .Be( + new OclBlock("foo") { - Foo = new WithIndexer() - }; - var result = (OclBlock)new DefaultBlockOclConverter().ToElements(context, typeof(Dummy).GetProperty(nameof(Dummy.Foo)), data.Foo).Single(); - result.Should() - .Be( - new OclBlock("foo") - { - new OclAttribute("my_prop", "MyValue") - } - ); - } + new OclAttribute("my_prop", "MyValue") + } + ); + } - class WithIndexer - { - public string MyProp => "MyValue"; - public string this[int index] => throw new NotImplementedException(); - } + class WithIndexer + { + public string MyProp => "MyValue"; + public string this[int index] => throw new NotImplementedException(); + } - class Dummy - { - public object? Foo { get; set; } - } + class Dummy + { + public object? Foo { get; set; } } } \ No newline at end of file diff --git a/source/Tests/Converters/DefaultAttributeOclConverterFixture.cs b/source/Tests/Converters/DefaultAttributeOclConverterFixture.cs index c46b60a..4f21dfb 100644 --- a/source/Tests/Converters/DefaultAttributeOclConverterFixture.cs +++ b/source/Tests/Converters/DefaultAttributeOclConverterFixture.cs @@ -5,21 +5,20 @@ using Octopus.Ocl; using Octopus.Ocl.Converters; -namespace Tests.Converters +namespace Tests.Converters; + +public class DefaultAttributeOclConverterFixture { - public class DefaultAttributeOclConverterFixture + [Test] + public void NameCaseIsKept() { - [Test] - public void NameCaseIsKept() - { - var context = new OclConversionContext(new OclSerializerOptions()); - var result = (OclAttribute)new DefaultAttributeOclConverter().ToElements(context, typeof(Dummy).GetProperty(nameof(Dummy.Test))!, "Value").Single(); - result.Name.Should().Be("test"); - } + var context = new OclConversionContext(new OclSerializerOptions()); + var result = (OclAttribute)new DefaultAttributeOclConverter().ToElements(context, typeof(Dummy).GetProperty(nameof(Dummy.Test))!, "Value").Single(); + result.Name.Should().Be("test"); + } - class Dummy - { - public string Test { get; } = "Value"; - } + class Dummy + { + public string Test { get; } = "Value"; } } \ No newline at end of file diff --git a/source/Tests/Converters/DefaultCollectionOclConverterFixture.cs b/source/Tests/Converters/DefaultCollectionOclConverterFixture.cs index b8f75cd..40bd6ee 100644 --- a/source/Tests/Converters/DefaultCollectionOclConverterFixture.cs +++ b/source/Tests/Converters/DefaultCollectionOclConverterFixture.cs @@ -5,64 +5,63 @@ using Octopus.Ocl; using Octopus.Ocl.Converters; -namespace Tests.Converters +namespace Tests.Converters; + +public class DefaultCollectionOclConverterFixture { - public class DefaultCollectionOclConverterFixture - { - const string Value = "Daffy"; + const string Value = "Daffy"; - readonly OclConversionContext context = new OclConversionContext(new OclSerializerOptions()); + readonly OclConversionContext context = new(new OclSerializerOptions()); - [Test] - public void FromElement_IEnumerableTargetWithCurrentAsNullReturnsAList() - => ExecuteFromElement>(null) - .Should() - .BeOfType>() - .And - .BeEquivalentTo(new[] { Value }); + [Test] + public void FromElement_IEnumerableTargetWithCurrentAsNullReturnsAList() + => ExecuteFromElement>(null) + .Should() + .BeOfType>() + .And + .BeEquivalentTo(new[] { Value }); - [Test] - public void FromElement_IListTargetWithCurrentAsNullReturnsAList() - => ExecuteFromElement>(null) - .Should() - .BeOfType>() - .And - .BeEquivalentTo(new[] { Value }); + [Test] + public void FromElement_IListTargetWithCurrentAsNullReturnsAList() + => ExecuteFromElement>(null) + .Should() + .BeOfType>() + .And + .BeEquivalentTo(new[] { Value }); - [Test] - public void FromElement_HashSetTargetWithCurrentAsNullReturnsAHashSet() - => ExecuteFromElement>(null) - .Should() - .BeOfType>() - .And - .BeEquivalentTo(new[] { Value }); + [Test] + public void FromElement_HashSetTargetWithCurrentAsNullReturnsAHashSet() + => ExecuteFromElement>(null) + .Should() + .BeOfType>() + .And + .BeEquivalentTo(new[] { Value }); - [Test] - public void FromElement_CustomCollectionIsSupported() - => ExecuteFromElement(null) - .Should() - .BeOfType() - .And - .BeEquivalentTo(new[] { Value }); + [Test] + public void FromElement_CustomCollectionIsSupported() + => ExecuteFromElement(null) + .Should() + .BeOfType() + .And + .BeEquivalentTo(new[] { Value }); - [Test] - public void FromElement_ReusesCurrentCollection() - { - var existing = new HashSet - { "ExistingItem" }; - ExecuteFromElement>(existing) - .Should() - .BeSameAs(existing) - .And - .BeEquivalentTo(new[] { "ExistingItem", Value }); - } + [Test] + public void FromElement_ReusesCurrentCollection() + { + var existing = new HashSet + { "ExistingItem" }; + ExecuteFromElement>(existing) + .Should() + .BeSameAs(existing) + .And + .BeEquivalentTo(new[] { "ExistingItem", Value }); + } - object? ExecuteFromElement(object? currentValue) - => new DefaultCollectionOclConverter() - .FromElement(context, typeof(TTarget), new OclAttribute("Test", Value), currentValue); + object? ExecuteFromElement(object? currentValue) + => new DefaultCollectionOclConverter() + .FromElement(context, typeof(TTarget), new OclAttribute("Test", Value), currentValue); - class MyCollection : HashSet - { - } + class MyCollection : HashSet + { } } \ No newline at end of file diff --git a/source/Tests/Converters/NameAttributeFixture.cs b/source/Tests/Converters/NameAttributeFixture.cs index 1bd431b..72f0868 100644 --- a/source/Tests/Converters/NameAttributeFixture.cs +++ b/source/Tests/Converters/NameAttributeFixture.cs @@ -5,50 +5,49 @@ using Octopus.Ocl; using Octopus.Ocl.Converters; -namespace Tests.Converters +namespace Tests.Converters; + +public class NameAttributeFixture { - public class NameAttributeFixture + [Test] + public void SerializingAttribute() { - [Test] - public void SerializingAttribute() - { - var context = new OclConversionContext(new OclSerializerOptions()); - var result = (OclAttribute)new DefaultAttributeOclConverter().ToElements(context, typeof(DummyWithAttribute).GetProperty(nameof(DummyWithAttribute.AttributeProperty))!, "whatever").Single(); - result.Name.Should().Be("NewName"); - } + var context = new OclConversionContext(new OclSerializerOptions()); + var result = (OclAttribute)new DefaultAttributeOclConverter().ToElements(context, typeof(DummyWithAttribute).GetProperty(nameof(DummyWithAttribute.AttributeProperty))!, "whatever").Single(); + result.Name.Should().Be("NewName"); + } - [Test] - public void SerializingBlock() - { - var context = new OclConversionContext(new OclSerializerOptions()); - var result = (OclBlock)new DefaultBlockOclConverter().ToElements(context, typeof(DummyWithBlock).GetProperty(nameof(DummyWithBlock.BlockProperty))!, new DummyWithAttribute()).Single(); - result.Name.Should().Be("AnotherName"); - } + [Test] + public void SerializingBlock() + { + var context = new OclConversionContext(new OclSerializerOptions()); + var result = (OclBlock)new DefaultBlockOclConverter().ToElements(context, typeof(DummyWithBlock).GetProperty(nameof(DummyWithBlock.BlockProperty))!, new DummyWithAttribute()).Single(); + result.Name.Should().Be("AnotherName"); + } - [Test] - public void Deserializing() - { - var context = new OclConversionContext(new OclSerializerOptions()); - var result = (DummyWithBlock?)new DefaultBlockOclConverter().FromElement(context, - typeof(DummyWithBlock), - new OclBlock("whatever", - Array.Empty(), - new[] { new OclBlock("AnotherName", Array.Empty(), new[] { new OclAttribute("NewName", "Boo") }) }), - null); + [Test] + public void Deserializing() + { + var context = new OclConversionContext(new OclSerializerOptions()); + var result = (DummyWithBlock?)new DefaultBlockOclConverter().FromElement(context, + typeof(DummyWithBlock), + new OclBlock("whatever", + Array.Empty(), + new[] { new OclBlock("AnotherName", Array.Empty(), new[] { new OclAttribute("NewName", "Boo") }) }), + null); - result?.BlockProperty.AttributeProperty.Should().Be("Boo"); - } + result?.BlockProperty.AttributeProperty.Should().Be("Boo"); + } - class DummyWithAttribute - { - [OclName("NewName")] - public string AttributeProperty { get; set; } = "Value"; - } + class DummyWithAttribute + { + [OclName("NewName")] + public string AttributeProperty { get; set; } = "Value"; + } - class DummyWithBlock - { - [OclName("AnotherName")] - public DummyWithAttribute BlockProperty { get; set; } = new DummyWithAttribute(); - } + class DummyWithBlock + { + [OclName("AnotherName")] + public DummyWithAttribute BlockProperty { get; set; } = new(); } } \ No newline at end of file diff --git a/source/Tests/FromOclDoc/FromOclDocumentDefaultBehaviourFixture.cs b/source/Tests/FromOclDoc/FromOclDocumentDefaultBehaviourFixture.cs index bbb48a4..bf46be0 100644 --- a/source/Tests/FromOclDoc/FromOclDocumentDefaultBehaviourFixture.cs +++ b/source/Tests/FromOclDoc/FromOclDocumentDefaultBehaviourFixture.cs @@ -4,339 +4,338 @@ using NUnit.Framework; using Octopus.Ocl; -namespace Tests.FromOclDoc +namespace Tests.FromOclDoc; + +public class DeserializeDefaultBehaviourFixture { - public class DeserializeDefaultBehaviourFixture + [Test] + public void Empty() { - [Test] - public void Empty() - { - var document = new OclDocument(); - var context = new OclConversionContext(new OclSerializerOptions()); - var result = context.FromElement(typeof(Car), document, null); - if (result == null) - throw new OclException("Document conversion resulted in null, which is not valid"); - ((Car)result) - .Should() - .BeEquivalentTo(new Car()); - } + var document = new OclDocument(); + var context = new OclConversionContext(new OclSerializerOptions()); + var result = context.FromElement(typeof(Car), document, null); + if (result == null) + throw new OclException("Document conversion resulted in null, which is not valid"); + ((Car)result) + .Should() + .BeEquivalentTo(new Car()); + } - [Test] - public void IntAttribute() + [Test] + public void IntAttribute() + { + var document = new OclDocument { - var document = new OclDocument - { - new OclAttribute("Doors", 4) - }; + new OclAttribute("Doors", 4) + }; + + var context = new OclConversionContext(new OclSerializerOptions()); + var result = context.FromElement(typeof(Car), document, null); + if (result == null) + throw new OclException("Document conversion resulted in null, which is not valid"); + ((Car)result) + .Should() + .BeEquivalentTo(new Car + { Doors = 4 }); + } - var context = new OclConversionContext(new OclSerializerOptions()); - var result = context.FromElement(typeof(Car), document, null); - if (result == null) - throw new OclException("Document conversion resulted in null, which is not valid"); - ((Car)result) - .Should() - .BeEquivalentTo(new Car - { Doors = 4 }); - } - - [Test] - public void IntAttributeToString() + [Test] + public void IntAttributeToString() + { + var document = new OclDocument { - var document = new OclDocument - { - new OclAttribute("Name", 4) - }; + new OclAttribute("Name", 4) + }; - new OclSerializer().Deserialize(document) - .Should() - .BeEquivalentTo(new Car - { Name = "4" }); - } + new OclSerializer().Deserialize(document) + .Should() + .BeEquivalentTo(new Car + { Name = "4" }); + } - [Test] - public void IntNullAttribute() + [Test] + public void IntNullAttribute() + { + var document = new OclDocument { - var document = new OclDocument - { - new OclAttribute("Doors", null) - }; + new OclAttribute("Doors", null) + }; - new OclSerializer().Deserialize(document) - .Should() - .BeEquivalentTo(new Car - { Doors = null }); - } + new OclSerializer().Deserialize(document) + .Should() + .BeEquivalentTo(new Car + { Doors = null }); + } - [Test] - public void StringAttribute() + [Test] + public void StringAttribute() + { + var document = new OclDocument { - var document = new OclDocument - { - new OclAttribute("Name", "Mystery Machine") - }; + new OclAttribute("Name", "Mystery Machine") + }; + + var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); + var result = context.FromElement(typeof(Car), document, null); + if (result == null) + throw new OclException("Document conversion resulted in null, which is not valid"); + ((Car)result) + .Should() + .BeEquivalentTo(new Car + { Name = "Mystery Machine" }); + } - var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); - var result = context.FromElement(typeof(Car), document, null); - if (result == null) - throw new OclException("Document conversion resulted in null, which is not valid"); - ((Car)result) - .Should() - .BeEquivalentTo(new Car - { Name = "Mystery Machine" }); - } - - [Test] - public void EnumAttribute() + [Test] + public void EnumAttribute() + { + var document = new OclDocument { - var document = new OclDocument - { - new OclAttribute("Type", "Suv") - }; + new OclAttribute("Type", "Suv") + }; - new OclSerializer().Deserialize(document) - .Should() - .BeEquivalentTo(new Car - { Type = CarType.Suv }); - } + new OclSerializer().Deserialize(document) + .Should() + .BeEquivalentTo(new Car + { Type = CarType.Suv }); + } - [Test] - public void DictionaryOfStrings() + [Test] + public void DictionaryOfStrings() + { + var dictionary = new Dictionary { - var dictionary = new Dictionary - { - { "One", "1" }, - { "Two", 2 } - }; + { "One", "1" }, + { "Two", 2 } + }; - var document = new OclDocument - { - new OclAttribute("StringDictionary", dictionary) - }; + var document = new OclDocument + { + new OclAttribute("StringDictionary", dictionary) + }; - new OclSerializer().Deserialize(document) - .Should() - .BeEquivalentTo(new Car + new OclSerializer().Deserialize(document) + .Should() + .BeEquivalentTo(new Car + { + StringDictionary = new Dictionary { - StringDictionary = new Dictionary - { - { "One", "1" }, - { "Two", "2" } - } - }); - } - - [Test] - public void DictionaryOfObjects() + { "One", "1" }, + { "Two", "2" } + } + }); + } + + [Test] + public void DictionaryOfObjects() + { + var dictionary = new Dictionary { - var dictionary = new Dictionary - { - { "One", "1" }, - { "Two", "2" } - }; + { "One", "1" }, + { "Two", "2" } + }; + + var document = new OclDocument + { + new OclAttribute("ObjectDictionary", dictionary) + }; - var document = new OclDocument + new OclSerializer().Deserialize(document) + .Should() + .BeEquivalentTo(new Car { - new OclAttribute("ObjectDictionary", dictionary) - }; + ObjectDictionary = dictionary + }); + } - new OclSerializer().Deserialize(document) - .Should() - .BeEquivalentTo(new Car - { - ObjectDictionary = dictionary - }); - } + [Test] + public void CaseIsIgnoredAttribute() + { + var document = new OclDocument + { + new OclAttribute("nAMe", "Mystery Machine") + }; + + var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); + var result = context.FromElement(typeof(Car), document, null); + if (result == null) + throw new OclException("Document conversion resulted in null, which is not valid"); + ((Car)result) + .Should() + .BeEquivalentTo(new Car + { Name = "Mystery Machine" }); + } - [Test] - public void CaseIsIgnoredAttribute() + [Test] + public void Block() + { + var document = new OclDocument { - var document = new OclDocument + new OclBlock("Driver") { - new OclAttribute("nAMe", "Mystery Machine") - }; + new OclAttribute("Name", "Bob") + } + }; + + var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); + var result = context.FromElement(typeof(Car), document, null); + if (result == null) + throw new OclException("Document conversion resulted in null, which is not valid"); + ((Car)result) + .Should() + .BeEquivalentTo(new Car + { + Driver = new Person + { Name = "Bob" } + }); + } - var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); - var result = context.FromElement(typeof(Car), document, null); - if (result == null) - throw new OclException("Document conversion resulted in null, which is not valid"); - ((Car)result) - .Should() - .BeEquivalentTo(new Car - { Name = "Mystery Machine" }); - } - - [Test] - public void Block() + [Test] + public void CollectionSingleItem() + { + var document = new OclDocument { - var document = new OclDocument + new OclBlock("Passengers") { - new OclBlock("Driver") - { - new OclAttribute("Name", "Bob") - } - }; - - var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); - var result = context.FromElement(typeof(Car), document, null); - if (result == null) - throw new OclException("Document conversion resulted in null, which is not valid"); - ((Car)result) - .Should() - .BeEquivalentTo(new Car + new OclAttribute("Name", "Bob") + } + }; + + var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); + var result = context.FromElement(typeof(Car), document, null); + if (result == null) + throw new OclException("Document conversion resulted in null, which is not valid"); + ((Car)result) + .Should() + .BeEquivalentTo(new Car + { + Passengers = new List { - Driver = new Person + new() { Name = "Bob" } - }); - } + } + }); + } - [Test] - public void CollectionSingleItem() + [Test] + public void CollectionMultipleItems() + { + var document = new OclDocument { - var document = new OclDocument + new OclBlock("Passengers") + { + new OclAttribute("Name", "Bob") + }, + new OclBlock("Passengers") { - new OclBlock("Passengers") + new OclAttribute("Name", "George") + } + }; + + var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); + var result = context.FromElement(typeof(Car), document, null); + if (result == null) + throw new OclException("Document conversion resulted in null, which is not valid"); + ((Car)result) + .Should() + .BeEquivalentTo(new Car + { + Passengers = new List { - new OclAttribute("Name", "Bob") + new() + { Name = "Bob" }, + new() + { Name = "George" } } - }; + }); + } - var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); - var result = context.FromElement(typeof(Car), document, null); - if (result == null) - throw new OclException("Document conversion resulted in null, which is not valid"); - ((Car)result) - .Should() - .BeEquivalentTo(new Car - { - Passengers = new List - { - new Person - { Name = "Bob" } - } - }); - } - - [Test] - public void CollectionMultipleItems() + [Test] + public void ExceptionIsThrownIfPropertyDoesNotExist() + { + var document = new OclDocument { - var document = new OclDocument - { - new OclBlock("Passengers") - { - new OclAttribute("Name", "Bob") - }, - new OclBlock("Passengers") - { - new OclAttribute("Name", "George") - } - }; + new OclAttribute("Wings", 1) + }; + var action = () => + { var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); var result = context.FromElement(typeof(Car), document, null); if (result == null) throw new OclException("Document conversion resulted in null, which is not valid"); - ((Car)result) - .Should() - .BeEquivalentTo(new Car - { - Passengers = new List - { - new Person - { Name = "Bob" }, - new Person - { Name = "George" } - } - }); - } - - [Test] - public void ExceptionIsThrownIfPropertyDoesNotExist() - { - var document = new OclDocument - { - new OclAttribute("Wings", 1) - }; + var temp = (Car)result; + }; + action.Should() + .Throw() + .WithMessage("*The property 'Wings' was not found on 'Car'*"); + } - Action action = () => - { - var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); - var result = context.FromElement(typeof(Car), document, null); - if (result == null) - throw new OclException("Document conversion resulted in null, which is not valid"); - var temp = (Car)result; - }; - action.Should() - .Throw() - .WithMessage("*The property 'Wings' was not found on 'Car'*"); - } - - [Test] - public void ExceptionIsThrownIfPropertyCantBeSet() + [Test] + public void ExceptionIsThrownIfPropertyCantBeSet() + { + var document = new OclDocument { - var document = new OclDocument - { - new OclAttribute("ReadOnly", 1) - }; + new OclAttribute("ReadOnly", 1) + }; - Action action = () => - { - var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); - var result = context.FromElement(typeof(Car), document, null); - if (result == null) - throw new OclException("Document conversion resulted in null, which is not valid"); - var temp = (Car)result; - }; - action.Should() - .Throw() - .WithMessage("*The property 'ReadOnly' on 'Car' does not have a setter*"); - } - - [Test] - public void ReadOnlyPropertiesWorkIfTheReferenceMatches() + var action = () => { - var document = new OclDocument - { - new OclBlock("ReadOnlyPassengers") - { - new OclAttribute("Name", "Bob") - } - }; - - var expected = new Car(); - expected.ReadOnlyPassengers.Add(new Person - { Name = "Bob" }); - var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); var result = context.FromElement(typeof(Car), document, null); if (result == null) throw new OclException("Document conversion resulted in null, which is not valid"); - ((Car)result) - .Should() - .BeEquivalentTo(expected); - } + var temp = (Car)result; + }; + action.Should() + .Throw() + .WithMessage("*The property 'ReadOnly' on 'Car' does not have a setter*"); + } - class Car - { - public string Name { get; set; } = ""; - public int? Doors { get; set; } - public int ReadOnly { get; } = 1; - public Person? Driver { get; set; } - public List? Passengers { get; set; } - public List ReadOnlyPassengers { get; } = new List(); - public CarType Type { get; set; } - public Dictionary? StringDictionary { get; set; } - public Dictionary? ObjectDictionary { get; set; } - } - - enum CarType + [Test] + public void ReadOnlyPropertiesWorkIfTheReferenceMatches() + { + var document = new OclDocument { - Hatchback, - Suv - } + new OclBlock("ReadOnlyPassengers") + { + new OclAttribute("Name", "Bob") + } + }; + + var expected = new Car(); + expected.ReadOnlyPassengers.Add(new Person + { Name = "Bob" }); + + var context = new OclConversionContext(new OclSerializerOptions() ?? new OclSerializerOptions()); + var result = context.FromElement(typeof(Car), document, null); + if (result == null) + throw new OclException("Document conversion resulted in null, which is not valid"); + ((Car)result) + .Should() + .BeEquivalentTo(expected); + } - class Person - { - public string Name { get; set; } = ""; - } + class Car + { + public string Name { get; set; } = ""; + public int? Doors { get; set; } + public int ReadOnly { get; } = 1; + public Person? Driver { get; set; } + public List? Passengers { get; set; } + public List ReadOnlyPassengers { get; } = new(); + public CarType Type { get; set; } + public Dictionary? StringDictionary { get; set; } + public Dictionary? ObjectDictionary { get; set; } + } + + enum CarType + { + Hatchback, + Suv + } + + class Person + { + public string Name { get; set; } = ""; } } \ No newline at end of file diff --git a/source/Tests/Namers/SnakeCaseOclNamerFixture.cs b/source/Tests/Namers/SnakeCaseOclNamerFixture.cs index b7a8d3e..f0418e5 100644 --- a/source/Tests/Namers/SnakeCaseOclNamerFixture.cs +++ b/source/Tests/Namers/SnakeCaseOclNamerFixture.cs @@ -6,53 +6,52 @@ using Octopus.Ocl; using Octopus.Ocl.Namers; -namespace Tests.Namers -{ - public class SnakeCaseOclNamerFixture - { - [TestCase("SnakeCase", "snake_case")] - [TestCase("MultipleCAPitals", "multiple_capitals")] - [TestCase("", "")] - [TestCase("ALLUPPER", "allupper")] - [TestCase("alllower", "alllower")] - [TestCase("With A Space", "with_a_space")] - public void FormatName(string input, string expected) - => new SnakeCaseOclNamer().FormatName(input).Should().Be(expected); +namespace Tests.Namers; - [Test] - public void GetPropertyNotFound() - => new SnakeCaseOclNamer() - .GetProperty("DoesNotExist", GetTestProperties()) - .Should() - .BeNull(); +public class SnakeCaseOclNamerFixture +{ + [TestCase("SnakeCase", "snake_case")] + [TestCase("MultipleCAPitals", "multiple_capitals")] + [TestCase("", "")] + [TestCase("ALLUPPER", "allupper")] + [TestCase("alllower", "alllower")] + [TestCase("With A Space", "with_a_space")] + public void FormatName(string input, string expected) + => new SnakeCaseOclNamer().FormatName(input).Should().Be(expected); - [TestCase("MyProperty")] - [TestCase("myproperty")] - [TestCase("myproPERTy")] - [TestCase("My_Property")] - [TestCase("my_property")] - public void GetPropertySingleMatch(string name) - => new SnakeCaseOclNamer() - .GetProperty(name, GetTestProperties()) - .Should() - .NotBeNull() - .And.Subject.Name.Should() - .Be("MyProperty"); + [Test] + public void GetPropertyNotFound() + => new SnakeCaseOclNamer() + .GetProperty("DoesNotExist", GetTestProperties()) + .Should() + .BeNull(); - [Test] - public void GetPropertyMultipleMatch() - { - Action action = () => new SnakeCaseOclNamer().GetProperty("DuplICAte", GetTestProperties()); - action.Should().Throw().WithMessage("Multiple properties match the name 'DuplICAte': duplicate, Duplicate"); - } + [TestCase("MyProperty")] + [TestCase("myproperty")] + [TestCase("myproPERTy")] + [TestCase("My_Property")] + [TestCase("my_property")] + public void GetPropertySingleMatch(string name) + => new SnakeCaseOclNamer() + .GetProperty(name, GetTestProperties()) + .Should() + .NotBeNull() + .And.Subject.Name.Should() + .Be("MyProperty"); - IReadOnlyCollection GetTestProperties() - => new - { - MyProperty = "", - duplicate = "", - Duplicate = "" - }.GetType() - .GetProperties(); + [Test] + public void GetPropertyMultipleMatch() + { + Action action = () => new SnakeCaseOclNamer().GetProperty("DuplICAte", GetTestProperties()); + action.Should().Throw().WithMessage("Multiple properties match the name 'DuplICAte': duplicate, Duplicate"); } + + IReadOnlyCollection GetTestProperties() + => new + { + MyProperty = "", + duplicate = "", + Duplicate = "" + }.GetType() + .GetProperties(); } \ No newline at end of file diff --git a/source/Tests/OclBodyAssertions.cs b/source/Tests/OclBodyAssertions.cs index 79f5fc7..2b15feb 100644 --- a/source/Tests/OclBodyAssertions.cs +++ b/source/Tests/OclBodyAssertions.cs @@ -2,27 +2,26 @@ using FluentAssertions.Primitives; using Octopus.Ocl; -namespace Tests +namespace Tests; + +public class OclBodyAssertions { - public class OclBodyAssertions - { - readonly OclBody? subject; + readonly OclBody? subject; - public OclBodyAssertions(OclBody? subject) - => this.subject = subject; + public OclBodyAssertions(OclBody? subject) + => this.subject = subject; - public void Be(OclBody expected) - { - new ObjectAssertions(subject).BeEquivalentTo( - expected, - config => config.IncludingAllRuntimeProperties() - ); - } + public void Be(OclBody expected) + { + new ObjectAssertions(subject).BeEquivalentTo( + expected, + config => config.IncludingAllRuntimeProperties() + ); + } - public void BeNull() - => new ObjectAssertions(subject).BeNull(); + public void BeNull() + => new ObjectAssertions(subject).BeNull(); - public void HaveChildrenExactly(params IOclElement[] expectedChildren) - => Be(new OclDocument(expectedChildren)); - } + public void HaveChildrenExactly(params IOclElement[] expectedChildren) + => Be(new OclDocument(expectedChildren)); } \ No newline at end of file diff --git a/source/Tests/Parsing/AttributeParsingFixture.cs b/source/Tests/Parsing/AttributeParsingFixture.cs index b383203..23a8a94 100644 --- a/source/Tests/Parsing/AttributeParsingFixture.cs +++ b/source/Tests/Parsing/AttributeParsingFixture.cs @@ -6,199 +6,198 @@ using Octopus.Ocl; using Octopus.Ocl.Parsing; -namespace Tests.Parsing +namespace Tests.Parsing; + +public class AttributeParsingFixture { - public class AttributeParsingFixture + [TestCase("Bar", "Bar")] + [TestCase(@"\r", "\r")] + [TestCase(@"\n", "\n")] + [TestCase(@"\t", "\t")] + [TestCase(@"\\", @"\")] + [TestCase(@"\""", @"""")] + [TestCase(@"\\\\\\\""\""", @"\\\""""")] + public void String(string text, string expected) + => OclParser.Execute($@"Foo = ""{text}""") + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", expected)); + + [Test] + public void StringInvalidEscape() { - [TestCase("Bar", "Bar")] - [TestCase(@"\r", "\r")] - [TestCase(@"\n", "\n")] - [TestCase(@"\t", "\t")] - [TestCase(@"\\", @"\")] - [TestCase(@"\""", @"""")] - [TestCase(@"\\\\\\\""\""", @"\\\""""")] - public void String(string text, string expected) - => OclParser.Execute($@"Foo = ""{text}""") - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", expected)); - - [Test] - public void StringInvalidEscape() - { - Action action = () => OclParser.Execute(@"Foo = ""\q"""); - action.Should().Throw().WithMessage(@"Unrecognised character escape: \q"); - } - - [Test] - public void WithExtraWhitespace() - => OclParser.Execute(" \t Foo = \t \"Bar\" \t ") - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", "Bar")); - - [TestCase("1", 1)] - [TestCase("-1", -1)] - public void Int(string input, int expected) - { - var result = OclParser.Execute(@"Foo = " + input); - result - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", expected)); - - result.OfType().First().Value.Should().BeOfType(typeof(int)); - } - - [TestCase("1.5", 1.5)] - [TestCase("-1.5", -1.5)] - public void Decimal(string input, decimal expected) - => OclParser.Execute(@"Foo = " + input) - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", expected)); - - [Test] - public void Null() - => OclParser.Execute("Foo = null") - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", null)); - - [Test] - public void True() - => OclParser.Execute("Foo = true") - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", true)); - - [Test] - public void False() - => OclParser.Execute("Foo = false") - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", false)); - - [TestCase("Foo=[]")] - [TestCase("Foo = []")] - [TestCase("Foo = [ ] ")] - [TestCase("Foo=[ ]")] - public void EmptyArray(string input) - => OclParser.Execute(input) - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", new string[0])); - - [TestCase(@"Foo=[""A""]")] - [TestCase(@"Foo= [ ""A"" ]")] - public void SingleStringArray(string input) - => OclParser.Execute(input) - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", new[] { "A" })); - - [TestCase(@"Foo=[""A"",""B""]")] - [TestCase(@"Foo = [ ""A"",""B"" ] ")] - [TestCase(@"Foo =[""A"", ""B""]")] - [TestCase(@"Foo= [ ""A"" , ""B"" ]")] - public void StringArray(string input) - => OclParser.Execute(input) - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", new[] { "A", "B" })); - - [TestCase(@"Foo=[1]")] - [TestCase(@"Foo= [ 1 ]")] - public void SingleIntArray(string input) - => OclParser.Execute(input) - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", new[] { 1 })); - - [TestCase(@"Foo=[1,2]")] - [TestCase(@"Foo = [ 1,2 ] ")] - [TestCase(@"Foo =[1, 2]")] - [TestCase(@"Foo= [ 1 , 2 ]")] - public void IntArray(string input) - => OclParser.Execute(input) - .Should() - .HaveChildrenExactly(new OclAttribute("Foo", new[] { 1, 2 })); - - [TestCase(@"Foo=[""A""""B""]", TestName = "Array without separator")] - [TestCase(@"Foo=[1 2]", TestName = "Array without separator")] - [TestCase(@"Foo=[1,,2]", TestName = "Array missing element separator")] - public void Invalid(string input) - { - var (document, error) = OclParser.TryExecute(input); - error.Should().NotBeEmpty(); - document.Should().BeNull(); - } - - [Test] - public void MultipleInRoot() - => OclParser.Execute(@" + Action action = () => OclParser.Execute(@"Foo = ""\q"""); + action.Should().Throw().WithMessage(@"Unrecognised character escape: \q"); + } + + [Test] + public void WithExtraWhitespace() + => OclParser.Execute(" \t Foo = \t \"Bar\" \t ") + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", "Bar")); + + [TestCase("1", 1)] + [TestCase("-1", -1)] + public void Int(string input, int expected) + { + var result = OclParser.Execute(@"Foo = " + input); + result + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", expected)); + + result.OfType().First().Value.Should().BeOfType(typeof(int)); + } + + [TestCase("1.5", 1.5)] + [TestCase("-1.5", -1.5)] + public void Decimal(string input, decimal expected) + => OclParser.Execute(@"Foo = " + input) + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", expected)); + + [Test] + public void Null() + => OclParser.Execute("Foo = null") + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", null)); + + [Test] + public void True() + => OclParser.Execute("Foo = true") + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", true)); + + [Test] + public void False() + => OclParser.Execute("Foo = false") + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", false)); + + [TestCase("Foo=[]")] + [TestCase("Foo = []")] + [TestCase("Foo = [ ] ")] + [TestCase("Foo=[ ]")] + public void EmptyArray(string input) + => OclParser.Execute(input) + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", new string[0])); + + [TestCase(@"Foo=[""A""]")] + [TestCase(@"Foo= [ ""A"" ]")] + public void SingleStringArray(string input) + => OclParser.Execute(input) + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", new[] { "A" })); + + [TestCase(@"Foo=[""A"",""B""]")] + [TestCase(@"Foo = [ ""A"",""B"" ] ")] + [TestCase(@"Foo =[""A"", ""B""]")] + [TestCase(@"Foo= [ ""A"" , ""B"" ]")] + public void StringArray(string input) + => OclParser.Execute(input) + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", new[] { "A", "B" })); + + [TestCase(@"Foo=[1]")] + [TestCase(@"Foo= [ 1 ]")] + public void SingleIntArray(string input) + => OclParser.Execute(input) + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", new[] { 1 })); + + [TestCase(@"Foo=[1,2]")] + [TestCase(@"Foo = [ 1,2 ] ")] + [TestCase(@"Foo =[1, 2]")] + [TestCase(@"Foo= [ 1 , 2 ]")] + public void IntArray(string input) + => OclParser.Execute(input) + .Should() + .HaveChildrenExactly(new OclAttribute("Foo", new[] { 1, 2 })); + + [TestCase(@"Foo=[""A""""B""]", TestName = "Array without separator")] + [TestCase(@"Foo=[1 2]", TestName = "Array without separator")] + [TestCase(@"Foo=[1,,2]", TestName = "Array missing element separator")] + public void Invalid(string input) + { + var (document, error) = OclParser.TryExecute(input); + error.Should().NotBeEmpty(); + document.Should().BeNull(); + } + + [Test] + public void MultipleInRoot() + => OclParser.Execute(@" One = 1 Two = 2 ") - .Should() - .HaveChildrenExactly( - new OclAttribute("One", 1), - new OclAttribute("Two", 2) - ); - - [Test] - public void MultipleInBlock() - => OclParser.Execute(@" + .Should() + .HaveChildrenExactly( + new OclAttribute("One", 1), + new OclAttribute("Two", 2) + ); + + [Test] + public void MultipleInBlock() + => OclParser.Execute(@" MyBlock { One = 1 Two = 2 } ") - .Should() - .HaveChildrenExactly( - new OclBlock("MyBlock") - { - new OclAttribute("One", 1), - new OclAttribute("Two", 2) - } - ); + .Should() + .HaveChildrenExactly( + new OclBlock("MyBlock") + { + new OclAttribute("One", 1), + new OclAttribute("Two", 2) + } + ); - [Test] - public void Dictionary() - => OclParser.Execute(@" + [Test] + public void Dictionary() + => OclParser.Execute(@" Properties = { One.One = ""1"" ""Two Two"" = ""2"" ""Three\""Three"" = ""3"" } ") - .Should() - .HaveChildrenExactly( - new OclAttribute("Properties", - new Dictionary - { - { "One.One", "1" }, - { "Two Two", "2" }, - { "Three\"Three", "3" } - } - ) - ); - - [Test] - public void DictionaryOneItem() - => OclParser.Execute(@" + .Should() + .HaveChildrenExactly( + new OclAttribute("Properties", + new Dictionary + { + { "One.One", "1" }, + { "Two Two", "2" }, + { "Three\"Three", "3" } + } + ) + ); + + [Test] + public void DictionaryOneItem() + => OclParser.Execute(@" Properties = { ""One"" = ""1"" } ") - .Should() - .HaveChildrenExactly( - new OclAttribute("Properties", - new Dictionary - { - { "One", "1" } - } - ) - ); - - [Test] - public void DictionaryEmpty() - => OclParser.Execute(@" + .Should() + .HaveChildrenExactly( + new OclAttribute("Properties", + new Dictionary + { + { "One", "1" } + } + ) + ); + + [Test] + public void DictionaryEmpty() + => OclParser.Execute(@" Properties = { } ") - .Should() - .HaveChildrenExactly( - new OclAttribute("Properties", new Dictionary()) - ); - } + .Should() + .HaveChildrenExactly( + new OclAttribute("Properties", new Dictionary()) + ); } \ No newline at end of file diff --git a/source/Tests/Parsing/BlockParsingFixture.cs b/source/Tests/Parsing/BlockParsingFixture.cs index 1556f98..755f5b1 100644 --- a/source/Tests/Parsing/BlockParsingFixture.cs +++ b/source/Tests/Parsing/BlockParsingFixture.cs @@ -3,100 +3,100 @@ using Octopus.Ocl; using Octopus.Ocl.Parsing; -namespace Tests.Parsing +namespace Tests.Parsing; + +public class BlockParsingFixture { - public class BlockParsingFixture - { - [Test] - public void EmptySingleLine() - => OclParser.Execute(@"MyBlock {}") - .Should() - .HaveChildrenExactly(new OclBlock("MyBlock")); - - [Test] - public void Empty() - => OclParser.Execute(@" + [Test] + public void EmptySingleLine() + => OclParser.Execute(@"MyBlock {}") + .Should() + .HaveChildrenExactly(new OclBlock("MyBlock")); + + [Test] + public void Empty() + => OclParser.Execute(@" MyBlock { } ") - .Should() - .HaveChildrenExactly(new OclBlock("MyBlock")); + .Should() + .HaveChildrenExactly(new OclBlock("MyBlock")); - [Test] - public void MultipleInRoot() - => OclParser.Execute(@" + [Test] + public void MultipleInRoot() + => OclParser.Execute(@" MyBlock {} MyBlock {} ") - .Should() - .HaveChildrenExactly( - new OclBlock("MyBlock"), - new OclBlock("MyBlock") - ); - - [Test] - public void SingleLabel() - => OclParser.Execute(@"MyBlock ""Foo"" {}") - .Should() - .HaveChildrenExactly(new OclBlock("MyBlock", new[] { "Foo" })); - - [Test] - public void MultipleLabels() - => OclParser.Execute(@"MyBlock ""Foo"" ""Bar"" ""Baz"" {}") - .Should() - .HaveChildrenExactly(new OclBlock("MyBlock", new[] { "Foo" })); - - [Test] - public void WithSingleAttributeChild() - => OclParser.Execute(@" + .Should() + .HaveChildrenExactly( + new OclBlock("MyBlock"), + new OclBlock("MyBlock") + ); + + [Test] + public void SingleLabel() + => OclParser.Execute(@"MyBlock ""Foo"" {}") + .Should() + .HaveChildrenExactly(new OclBlock("MyBlock", new[] { "Foo" })); + + [Test] + public void MultipleLabels() + => OclParser.Execute(@"MyBlock ""Foo"" ""Bar"" ""Baz"" {}") + .Should() + .HaveChildrenExactly(new OclBlock("MyBlock", new[] { "Foo" })); + + [Test] + public void WithSingleAttributeChild() + => OclParser.Execute(@" MyBlock { Child = 1 } ") - .Should() - .HaveChildrenExactly(new OclBlock("MyBlock") - { - new OclAttribute("Child", 1) - }); - - [Test] - public void WithMultipleAttributeChild() - => OclParser.Execute(@" + .Should() + .HaveChildrenExactly(new OclBlock("MyBlock") + { + new OclAttribute("Child", 1) + }); + + [Test] + public void WithMultipleAttributeChild() + => OclParser.Execute(@" MyBlock { Child = 1 Child2 = 2 } ") - .Should() - .HaveChildrenExactly(new OclBlock("MyBlock") - { - new OclAttribute("Child", 1), - new OclAttribute("Child2", 2) - }); - - [Test] - public void NestedBlocks() - => OclParser.Execute(@" + .Should() + .HaveChildrenExactly(new OclBlock("MyBlock") + { + new OclAttribute("Child", 1), + new OclAttribute("Child2", 2) + }); + + [Test] + public void NestedBlocks() + => OclParser.Execute(@" MyBlock { ChildBlock { GrandChildBlock {} } } ") - .Should() - .HaveChildrenExactly(new OclBlock("MyBlock") + .Should() + .HaveChildrenExactly(new OclBlock("MyBlock") + { + new OclBlock("ChildBlock") { - new OclBlock("ChildBlock") - { - new OclBlock("GrandChildBlock") - } - }); + new OclBlock("GrandChildBlock") + } + }); - [Test] - public void MixedChildren() - => OclParser.Execute(@" + [Test] + public void MixedChildren() + => OclParser.Execute(@" MyBlock { ChildBlock1 { @@ -115,18 +115,17 @@ public void MixedChildren() } } ") - .Should() - .HaveChildrenExactly(new OclBlock("MyBlock") + .Should() + .HaveChildrenExactly(new OclBlock("MyBlock") + { + new OclBlock("ChildBlock1"), + new OclAttribute("Child1", 1), + new OclAttribute("Child2", 2), + + new OclBlock("ChildBlock2", new[] { "Label" }) { - new OclBlock("ChildBlock1"), - new OclAttribute("Child1", 1), - new OclAttribute("Child2", 2), - - new OclBlock("ChildBlock2", new[] { "Label" }) - { - new OclBlock("GrandChildBlock"), - new OclAttribute("GrandChild", "A") - } - }); - } + new OclBlock("GrandChildBlock"), + new OclAttribute("GrandChild", "A") + } + }); } \ No newline at end of file diff --git a/source/Tests/Parsing/HeredocParsingFixture.cs b/source/Tests/Parsing/HeredocParsingFixture.cs index d2f0bba..dde6f84 100644 --- a/source/Tests/Parsing/HeredocParsingFixture.cs +++ b/source/Tests/Parsing/HeredocParsingFixture.cs @@ -8,141 +8,140 @@ using Octopus.Ocl.Parsing; using Sprache; -namespace Tests.Parsing -{ - public class HeredocParsingFixture - { - [TestCase("< HeredocParser.Start - .Parse(input) - .Should() - .Be((tag, format)); +namespace Tests.Parsing; - [TestCase("< HeredocParser.Start - .TryParse(input) - .WasSuccessful - .Should() - .BeFalse(); +public class HeredocParsingFixture +{ + [TestCase("< HeredocParser.Start + .Parse(input) + .Should() + .Be((tag, format)); - [TestCase("ZZZ\n")] - [TestCase("ZZZ")] - [TestCase("\t\tZZZ\t\t\n")] - [TestCase("ZZZ\nFoo\n")] - public void End(string input) - => HeredocParser.End("ZZZ") - .Parse(input) - .Should() - .Be("ZZZ"); + [TestCase("< HeredocParser.Start + .TryParse(input) + .WasSuccessful + .Should() + .BeFalse(); - [TestCase("ZZZ A\n")] - [TestCase("A ZZZ\n")] - public void EndInvalid(string input) - => HeredocParser.End("ZZZ") - .TryParse(input) - .WasSuccessful - .Should() - .BeFalse(); + [TestCase("ZZZ\n")] + [TestCase("ZZZ")] + [TestCase("\t\tZZZ\t\t\n")] + [TestCase("ZZZ\nFoo\n")] + public void End(string input) + => HeredocParser.End("ZZZ") + .Parse(input) + .Should() + .Be("ZZZ"); - [TestCase("< OclParser.Execute("Foo = " + input.ToUnixLineEndings()) - .Should() - .HaveChildrenExactly( - new OclAttribute("Foo", - new OclStringLiteral(expected, OclStringLiteralFormat.Heredoc) - { - HeredocTag = "ZZZ" - } - ) - ); + [TestCase("ZZZ A\n")] + [TestCase("A ZZZ\n")] + public void EndInvalid(string input) + => HeredocParser.End("ZZZ") + .TryParse(input) + .WasSuccessful + .Should() + .BeFalse(); - [TestCase("<<-ZZZ\nZZZ", "", Description = "IndentedHeredoc - Empty")] - [TestCase("<<-ZZZ\n \n \nZZZ", "\n", Description = "IndentedHeredoc - Whitespace")] - [TestCase("<<-ZZZ\n A\n B\nZZZ", "A\nB", Description = "IndentedHeredoc - NoExtraIndent")] - [TestCase("<<-ZZZ\n A\n B\n ZZZ", "A\n B", Description = "IndentedHeredoc - ExtraIndent")] - [TestCase("<<-ZZZ\n A ZZZ\n ZZZ B\nZZZ", "A ZZZ\n ZZZ B", Description = "IndentedHeredoc - End Marker In Text")] - [TestCase("<<-ZZZ\n A\n B\nZZZ", "A\n B", Description = "IndentedHeredoc - End marker does not affect indent")] - public void IndentedHeredoc(string input, string expected) - => OclParser.Execute("Foo = " + input.ToUnixLineEndings()) - .Should() - .HaveChildrenExactly( - new OclAttribute("Foo", - new OclStringLiteral(expected, OclStringLiteralFormat.IndentedHeredoc) - { - HeredocTag = "ZZZ" - } - ) - ); + [TestCase("< OclParser.Execute("Foo = " + input.ToUnixLineEndings()) + .Should() + .HaveChildrenExactly( + new OclAttribute("Foo", + new OclStringLiteral(expected, OclStringLiteralFormat.Heredoc) + { + HeredocTag = "ZZZ" + } + ) + ); - [TestCase("\r\n")] - [TestCase("\n")] - public void LineEndingsArePreserved(string lineEnding) - { - var documentLineEnding = lineEnding == "\n" ? "\r\n" : "\n"; // The opposite + [TestCase("<<-ZZZ\nZZZ", "", Description = "IndentedHeredoc - Empty")] + [TestCase("<<-ZZZ\n \n \nZZZ", "\n", Description = "IndentedHeredoc - Whitespace")] + [TestCase("<<-ZZZ\n A\n B\nZZZ", "A\nB", Description = "IndentedHeredoc - NoExtraIndent")] + [TestCase("<<-ZZZ\n A\n B\n ZZZ", "A\n B", Description = "IndentedHeredoc - ExtraIndent")] + [TestCase("<<-ZZZ\n A ZZZ\n ZZZ B\nZZZ", "A ZZZ\n ZZZ B", Description = "IndentedHeredoc - End Marker In Text")] + [TestCase("<<-ZZZ\n A\n B\nZZZ", "A\n B", Description = "IndentedHeredoc - End marker does not affect indent")] + public void IndentedHeredoc(string input, string expected) + => OclParser.Execute("Foo = " + input.ToUnixLineEndings()) + .Should() + .HaveChildrenExactly( + new OclAttribute("Foo", + new OclStringLiteral(expected, OclStringLiteralFormat.IndentedHeredoc) + { + HeredocTag = "ZZZ" + } + ) + ); - var expected = $"{lineEnding}A{lineEnding}B{lineEnding}"; + [TestCase("\r\n")] + [TestCase("\n")] + public void LineEndingsArePreserved(string lineEnding) + { + var documentLineEnding = lineEnding == "\n" ? "\r\n" : "\n"; // The opposite - var attribute = new OclAttribute("value", - new OclStringLiteral(expected, OclStringLiteralFormat.Heredoc) - { - HeredocTag = "ZZZ" - } - ); + var expected = $"{lineEnding}A{lineEnding}B{lineEnding}"; - var sb = new StringBuilder(); - using (var tw = new StringWriter(sb) { NewLine = documentLineEnding }) - using (var writer = new OclWriter(tw)) + var attribute = new OclAttribute("value", + new OclStringLiteral(expected, OclStringLiteralFormat.Heredoc) { - writer.Write(attribute); + HeredocTag = "ZZZ" } + ); - OclParser.Execute(sb.ToString()) - .Should() - .HaveChildrenExactly(attribute); - } - - [TestCase("")] - [TestCase("A")] - [TestCase("", "", "")] - [TestCase("A", " B")] - [TestCase("A", " ", " B")] - [TestCase(" A", "B")] - public void UnindentNoChange(params string[] input) + var sb = new StringBuilder(); + using (var tw = new StringWriter(sb) { NewLine = documentLineEnding }) + using (var writer = new OclWriter(tw)) { - var result = HeredocParser.Unindent(input, OclStringLiteralFormat.IndentedHeredoc); - result.Should().BeEquivalentTo(input); + writer.Write(attribute); } - [TestCase(" A")] - [TestCase(" ", " ")] - [TestCase(" A", "\t\t\t\tB")] - [TestCase(" A", " B")] - [TestCase(" A", " B")] - [TestCase(" A", - " ", - " ", - " B", - Description = "Empty lines do not affect unindent")] - public void UnindentBy4Chars(params string[] input) - { - var expected = input.Select(i => i.Length < 4 ? "" : i.Substring(4)); - var result = HeredocParser.Unindent(input, OclStringLiteralFormat.IndentedHeredoc); - result.Should().BeEquivalentTo(expected); - } + OclParser.Execute(sb.ToString()) + .Should() + .HaveChildrenExactly(attribute); + } + + [TestCase("")] + [TestCase("A")] + [TestCase("", "", "")] + [TestCase("A", " B")] + [TestCase("A", " ", " B")] + [TestCase(" A", "B")] + public void UnindentNoChange(params string[] input) + { + var result = HeredocParser.Unindent(input, OclStringLiteralFormat.IndentedHeredoc); + result.Should().BeEquivalentTo(input); + } + + [TestCase(" A")] + [TestCase(" ", " ")] + [TestCase(" A", "\t\t\t\tB")] + [TestCase(" A", " B")] + [TestCase(" A", " B")] + [TestCase(" A", + " ", + " ", + " B", + Description = "Empty lines do not affect unindent")] + public void UnindentBy4Chars(params string[] input) + { + var expected = input.Select(i => i.Length < 4 ? "" : i.Substring(4)); + var result = HeredocParser.Unindent(input, OclStringLiteralFormat.IndentedHeredoc); + result.Should().BeEquivalentTo(expected); } } \ No newline at end of file diff --git a/source/Tests/Parsing/ParserFixture.cs b/source/Tests/Parsing/ParserFixture.cs index 8c3bac1..2f2b62b 100644 --- a/source/Tests/Parsing/ParserFixture.cs +++ b/source/Tests/Parsing/ParserFixture.cs @@ -4,35 +4,34 @@ using Octopus.Ocl; using Octopus.Ocl.Parsing; -namespace Tests.Parsing +namespace Tests.Parsing; + +public class ParserFixture { - public class ParserFixture - { - [Test] - public void Empty() - => OclParser.Execute("") - .Should() - .Be(new OclDocument()); + [Test] + public void Empty() + => OclParser.Execute("") + .Should() + .Be(new OclDocument()); - [Test] - public void Blank() - => OclParser.Execute(" \t \r\n \t ") - .Should() - .Be(new OclDocument()); + [Test] + public void Blank() + => OclParser.Execute(" \t \r\n \t ") + .Should() + .Be(new OclDocument()); - [Test] - public void InvalidDocumentReportsCorrectLineNumber() - { - var fooBarFooBar = @" + [Test] + public void InvalidDocumentReportsCorrectLineNumber() + { + var fooBarFooBar = @" Foo = ""Bar"" Foo = ""Bar ".ToUnixLineEndings(); - var (_, error) = OclParser.TryExecute(fooBarFooBar); + var (_, error) = OclParser.TryExecute(fooBarFooBar); - var expected = "Parsing failure: unexpected '\n'; expected \" (Line 4, Column 31); recently consumed: Foo = \"Bar"; - error?.Should().Be(expected); - } + var expected = "Parsing failure: unexpected '\n'; expected \" (Line 4, Column 31); recently consumed: Foo = \"Bar"; + error?.Should().Be(expected); } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/ActionNames.cs b/source/Tests/RealLifeScenario/Entities/ActionNames.cs index c46939a..0888012 100644 --- a/source/Tests/RealLifeScenario/Entities/ActionNames.cs +++ b/source/Tests/RealLifeScenario/Entities/ActionNames.cs @@ -1,17 +1,16 @@ using System; using System.Collections.Generic; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class ActionNames { - public class ActionNames - { - public const string Iis = "Octopus.IIS"; - public const string Script = "Octopus.Script"; + public const string Iis = "Octopus.IIS"; + public const string Script = "Octopus.Script"; - public static IReadOnlyList All = new[] - { - Iis, - Script - }; - } + public static IReadOnlyList All = new[] + { + Iis, + Script + }; } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/ChannelIdOrName.cs b/source/Tests/RealLifeScenario/Entities/ChannelIdOrName.cs index 5d5bd46..37854df 100644 --- a/source/Tests/RealLifeScenario/Entities/ChannelIdOrName.cs +++ b/source/Tests/RealLifeScenario/Entities/ChannelIdOrName.cs @@ -1,13 +1,12 @@ using System; using Octopus.TinyTypes; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class ChannelIdOrName : CaseInsensitiveStringTinyType { - public class ChannelIdOrName : CaseInsensitiveStringTinyType + public ChannelIdOrName(string value) + : base(value) { - public ChannelIdOrName(string value) - : base(value) - { - } } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/DeploymentAction.cs b/source/Tests/RealLifeScenario/Entities/DeploymentAction.cs index 3a1e613..73ae4e3 100644 --- a/source/Tests/RealLifeScenario/Entities/DeploymentAction.cs +++ b/source/Tests/RealLifeScenario/Entities/DeploymentAction.cs @@ -3,60 +3,59 @@ using Octopus.Data.Model; using Octopus.Server.Extensibility.HostServices.Model; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class DeploymentAction { - public class DeploymentAction + public DeploymentAction(string name, string actionType) { - public DeploymentAction(string name, string actionType) - { - Id = Guid.NewGuid().ToString(); - Container = new DeploymentActionContainer(); - Name = name; - ActionType = actionType; - } + Id = Guid.NewGuid().ToString(); + Container = new DeploymentActionContainer(); + Name = name; + ActionType = actionType; + } - public string Id { get; set; } - public string Name { get; set; } - public string ActionType { get; set; } + public string Id { get; set; } + public string Name { get; set; } + public string ActionType { get; set; } - [JsonProperty("WorkerPoolId")] - public WorkerPoolIdOrName? WorkerPoolIdOrName { get; set; } + [JsonProperty("WorkerPoolId")] + public WorkerPoolIdOrName? WorkerPoolIdOrName { get; set; } - public string? WorkerPoolVariable { get; set; } + public string? WorkerPoolVariable { get; set; } - public DeploymentActionContainer Container { get; set; } + public DeploymentActionContainer Container { get; set; } - [JsonIgnore] - public bool HasWorkerPoolSet => !string.IsNullOrWhiteSpace(WorkerPoolIdOrName?.Value) || !string.IsNullOrWhiteSpace(WorkerPoolVariable); + [JsonIgnore] + public bool HasWorkerPoolSet => !string.IsNullOrWhiteSpace(WorkerPoolIdOrName?.Value) || !string.IsNullOrWhiteSpace(WorkerPoolVariable); - public bool IsDisabled { get; set; } + public bool IsDisabled { get; set; } - [JsonIgnore] - public bool Enabled => !IsDisabled; + [JsonIgnore] + public bool Enabled => !IsDisabled; - public bool IsRequired { get; set; } + public bool IsRequired { get; set; } - [JsonIgnore] - public bool CanBeUsedForProjectVersioning => true; + [JsonIgnore] + public bool CanBeUsedForProjectVersioning => true; - [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] - public ReferenceCollection Environments { get; } = new ReferenceCollection(); + [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] + public ReferenceCollection Environments { get; } = new(); - [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] - public ReferenceCollection ExcludedEnvironments { get; } = new ReferenceCollection(); + [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] + public ReferenceCollection ExcludedEnvironments { get; } = new(); - [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] - public ReferenceCollection Channels { get; } = new ReferenceCollection(); + [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] + public ReferenceCollection Channels { get; } = new(); - [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] - public ReferenceCollection TenantTags { get; } = new ReferenceCollection(); + [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] + public ReferenceCollection TenantTags { get; } = new(); - [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] - public PackageReferenceCollection Packages { get; } = new PackageReferenceCollection(); + [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] + public PackageReferenceCollection Packages { get; } = new(); - public DeploymentActionCondition Condition { get; set; } + public DeploymentActionCondition Condition { get; set; } - [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] - public PropertiesDictionary Properties { get; } = new PropertiesDictionary(); - } + [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] + public PropertiesDictionary Properties { get; } = new(); } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/DeploymentActionCondition.cs b/source/Tests/RealLifeScenario/Entities/DeploymentActionCondition.cs index 2138fc8..1c97c66 100644 --- a/source/Tests/RealLifeScenario/Entities/DeploymentActionCondition.cs +++ b/source/Tests/RealLifeScenario/Entities/DeploymentActionCondition.cs @@ -1,10 +1,9 @@ using System; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public enum DeploymentActionCondition { - public enum DeploymentActionCondition - { - Success, - Variable - } + Success, + Variable } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/DeploymentActionContainer.cs b/source/Tests/RealLifeScenario/Entities/DeploymentActionContainer.cs index 7a6cb59..8f6c399 100644 --- a/source/Tests/RealLifeScenario/Entities/DeploymentActionContainer.cs +++ b/source/Tests/RealLifeScenario/Entities/DeploymentActionContainer.cs @@ -1,10 +1,9 @@ using System; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class DeploymentActionContainer { - public class DeploymentActionContainer - { - public string? Image { get; set; } - public string? FeedId { get; set; } - } + public string? Image { get; set; } + public string? FeedId { get; set; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/DeploymentActionExtensions.cs b/source/Tests/RealLifeScenario/Entities/DeploymentActionExtensions.cs index 989ba10..f97d127 100644 --- a/source/Tests/RealLifeScenario/Entities/DeploymentActionExtensions.cs +++ b/source/Tests/RealLifeScenario/Entities/DeploymentActionExtensions.cs @@ -1,20 +1,19 @@ using System; using Octopus.Server.Extensibility.HostServices.Model; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public static class DeploymentActionExtensions { - public static class DeploymentActionExtensions + public static DeploymentAction WithProperty(this DeploymentAction action, string key, string value) { - public static DeploymentAction WithProperty(this DeploymentAction action, string key, string value) - { - action.Properties[key] = new PropertyValue(value); - return action; - } + action.Properties[key] = new PropertyValue(value); + return action; + } - public static DeploymentAction WithSensitiveProperty(this DeploymentAction action, string key, string value) - { - action.Properties[key] = new PropertyValue(value, true); - return action; - } + public static DeploymentAction WithSensitiveProperty(this DeploymentAction action, string key, string value) + { + action.Properties[key] = new PropertyValue(value, true); + return action; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/DeploymentEnvironmentIdOrName.cs b/source/Tests/RealLifeScenario/Entities/DeploymentEnvironmentIdOrName.cs index 7a8d0bd..f9297fe 100644 --- a/source/Tests/RealLifeScenario/Entities/DeploymentEnvironmentIdOrName.cs +++ b/source/Tests/RealLifeScenario/Entities/DeploymentEnvironmentIdOrName.cs @@ -1,13 +1,12 @@ using System; using Octopus.TinyTypes; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class DeploymentEnvironmentIdOrName : CaseInsensitiveStringTinyType { - public class DeploymentEnvironmentIdOrName : CaseInsensitiveStringTinyType + public DeploymentEnvironmentIdOrName(string value) + : base(value) { - public DeploymentEnvironmentIdOrName(string value) - : base(value) - { - } } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/DeploymentStep.cs b/source/Tests/RealLifeScenario/Entities/DeploymentStep.cs index 188c151..4836503 100644 --- a/source/Tests/RealLifeScenario/Entities/DeploymentStep.cs +++ b/source/Tests/RealLifeScenario/Entities/DeploymentStep.cs @@ -3,32 +3,31 @@ using System.Linq; using Newtonsoft.Json; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class DeploymentStep { - public class DeploymentStep + public DeploymentStep(string name) { - public DeploymentStep(string name) - { - Name = name; - Id = Guid.NewGuid().ToString(); - } - - public string Id { get; set; } - public string Name { get; set; } - public DeploymentStepCondition Condition { get; set; } - public DeploymentStepStartTrigger StartTrigger { get; set; } - public DeploymentStepPackageRequirement PackageRequirement { get; set; } + Name = name; + Id = Guid.NewGuid().ToString(); + } - [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] - public List Actions { get; } = new List(); + public string Id { get; set; } + public string Name { get; set; } + public DeploymentStepCondition Condition { get; set; } + public DeploymentStepStartTrigger StartTrigger { get; set; } + public DeploymentStepPackageRequirement PackageRequirement { get; set; } - [JsonIgnore] - public IEnumerable InheritedPropertiesForActions - { - get { return Actions.Select(a => new PropertiesDictionary(a.Properties, Properties)); } - } + [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] + public List Actions { get; } = new(); - [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] - public PropertiesDictionary Properties { get; } = new PropertiesDictionary(); + [JsonIgnore] + public IEnumerable InheritedPropertiesForActions + { + get { return Actions.Select(a => new PropertiesDictionary(a.Properties, Properties)); } } + + [JsonProperty(ObjectCreationHandling = ObjectCreationHandling.Reuse)] + public PropertiesDictionary Properties { get; } = new(); } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/DeploymentStepCondition.cs b/source/Tests/RealLifeScenario/Entities/DeploymentStepCondition.cs index 9cdb078..12fe755 100644 --- a/source/Tests/RealLifeScenario/Entities/DeploymentStepCondition.cs +++ b/source/Tests/RealLifeScenario/Entities/DeploymentStepCondition.cs @@ -1,12 +1,11 @@ using System; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public enum DeploymentStepCondition { - public enum DeploymentStepCondition - { - Success, - Failure, - Always, - Variable - } + Success, + Failure, + Always, + Variable } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/DeploymentStepPackageRequirement.cs b/source/Tests/RealLifeScenario/Entities/DeploymentStepPackageRequirement.cs index 7755118..f778e4e 100644 --- a/source/Tests/RealLifeScenario/Entities/DeploymentStepPackageRequirement.cs +++ b/source/Tests/RealLifeScenario/Entities/DeploymentStepPackageRequirement.cs @@ -1,11 +1,10 @@ using System; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public enum DeploymentStepPackageRequirement { - public enum DeploymentStepPackageRequirement - { - LetOctopusDecide, - BeforePackageAcquisition, - AfterPackageAcquisition - } + LetOctopusDecide, + BeforePackageAcquisition, + AfterPackageAcquisition } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/DeploymentStepStartTrigger.cs b/source/Tests/RealLifeScenario/Entities/DeploymentStepStartTrigger.cs index cf157c6..0e2e802 100644 --- a/source/Tests/RealLifeScenario/Entities/DeploymentStepStartTrigger.cs +++ b/source/Tests/RealLifeScenario/Entities/DeploymentStepStartTrigger.cs @@ -1,10 +1,9 @@ using System; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public enum DeploymentStepStartTrigger { - public enum DeploymentStepStartTrigger - { - StartAfterPrevious = 0, - StartWithPrevious = 1 - } + StartAfterPrevious = 0, + StartWithPrevious = 1 } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/IProcess.cs b/source/Tests/RealLifeScenario/Entities/IProcess.cs index cd04346..52ccde0 100644 --- a/source/Tests/RealLifeScenario/Entities/IProcess.cs +++ b/source/Tests/RealLifeScenario/Entities/IProcess.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public interface IProcess { - public interface IProcess - { - List Steps { get; } - IEnumerable AllEnabledActions { get; } - IEnumerable AllActions { get; } - } + List Steps { get; } + IEnumerable AllEnabledActions { get; } + IEnumerable AllActions { get; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/PropertiesDictionary.cs b/source/Tests/RealLifeScenario/Entities/PropertiesDictionary.cs index feb5052..de7ce26 100644 --- a/source/Tests/RealLifeScenario/Entities/PropertiesDictionary.cs +++ b/source/Tests/RealLifeScenario/Entities/PropertiesDictionary.cs @@ -3,30 +3,29 @@ using System.Linq; using Octopus.Server.Extensibility.HostServices.Model; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class PropertiesDictionary : Dictionary { - public class PropertiesDictionary : Dictionary + public PropertiesDictionary() : base(StringComparer.OrdinalIgnoreCase) { - public PropertiesDictionary() : base(StringComparer.OrdinalIgnoreCase) - { - } + } - public PropertiesDictionary(IDictionary values) - : base(values, StringComparer.OrdinalIgnoreCase) - { - } + public PropertiesDictionary(IDictionary values) + : base(values, StringComparer.OrdinalIgnoreCase) + { + } - public PropertiesDictionary(params IDictionary[] propertiesDictionaries) - : base(Merge(propertiesDictionaries)) - { - } + public PropertiesDictionary(params IDictionary[] propertiesDictionaries) + : base(Merge(propertiesDictionaries)) + { + } - static IDictionary Merge(IDictionary[] dictionaries) - where T : notnull - { - return dictionaries.SelectMany(dict => dict) - .ToLookup(pair => pair.Key, pair => pair.Value) - .ToDictionary(group => group.Key, group => group.First()); - } + static IDictionary Merge(IDictionary[] dictionaries) + where T : notnull + { + return dictionaries.SelectMany(dict => dict) + .ToLookup(pair => pair.Key, pair => pair.Value) + .ToDictionary(group => group.Key, group => group.First()); } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/RunbookEnvironmentScope.cs b/source/Tests/RealLifeScenario/Entities/RunbookEnvironmentScope.cs index d8b5201..e006165 100644 --- a/source/Tests/RealLifeScenario/Entities/RunbookEnvironmentScope.cs +++ b/source/Tests/RealLifeScenario/Entities/RunbookEnvironmentScope.cs @@ -1,11 +1,10 @@ using System; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public enum RunbookEnvironmentScope { - public enum RunbookEnvironmentScope - { - All = 0, - Specified, - FromProjectLifecycles - } + All = 0, + Specified, + FromProjectLifecycles } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/RunbookProcess.cs b/source/Tests/RealLifeScenario/Entities/RunbookProcess.cs index 86a1825..60a6995 100644 --- a/source/Tests/RealLifeScenario/Entities/RunbookProcess.cs +++ b/source/Tests/RealLifeScenario/Entities/RunbookProcess.cs @@ -6,67 +6,66 @@ using Octopus.Server.Extensibility.HostServices.Model.Environments; using Octopus.Server.Extensibility.HostServices.Model.TagSets; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class RunbookProcess : IProcess { - public class RunbookProcess : IProcess + public RunbookProcess(string projectId, string spaceId) { - public RunbookProcess(string projectId, string spaceId) - { - ProjectId = projectId; - Id = Guid.NewGuid().ToString(); - OwnerId = projectId; - SpaceId = spaceId; - Steps = new List(); - } + ProjectId = projectId; + Id = Guid.NewGuid().ToString(); + OwnerId = projectId; + SpaceId = spaceId; + Steps = new List(); + } - public string ProjectId { get; set; } + public string ProjectId { get; set; } - [JsonIgnore] - public string RunbookId - { - get => OwnerId; - set => OwnerId = value; - } + [JsonIgnore] + public string RunbookId + { + get => OwnerId; + set => OwnerId = value; + } - public string Id { get; internal set; } - public string OwnerId { get; set; } + public string Id { get; internal set; } + public string OwnerId { get; set; } - [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] - public bool IsFrozen { get; set; } + [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] + public bool IsFrozen { get; set; } - public int Version { get; set; } - public string SpaceId { get; set; } - public List Steps { get; protected set; } + public int Version { get; set; } + public string SpaceId { get; set; } + public List Steps { get; protected set; } - [JsonIgnore] - public IEnumerable AllEnabledActions - { - get { return AllActions.Where(a => !a.IsDisabled); } - } + [JsonIgnore] + public IEnumerable AllEnabledActions + { + get { return AllActions.Where(a => !a.IsDisabled); } + } - [JsonIgnore] - public IEnumerable AllActions - { - get { return Steps.SelectMany(s => s.Actions); } - } + [JsonIgnore] + public IEnumerable AllActions + { + get { return Steps.SelectMany(s => s.Actions); } + } - [JsonIgnore] - public IEnumerable<(string id, Type documentType)> RelatedDocuments + [JsonIgnore] + public IEnumerable<(string id, Type documentType)> RelatedDocuments + { + get { - get - { - var actions = (IsFrozen ? AllEnabledActions : AllActions).ToArray(); + var actions = (IsFrozen ? AllEnabledActions : AllActions).ToArray(); - var environments = actions.SelectMany(a => a.Environments).Select(x => x.Value).Select(id => (id, typeof(DeploymentEnvironmentId))); - var excludedEnvironments = actions.SelectMany(a => a.ExcludedEnvironments).Select(x => x.Value).Select(id => (id, typeof(DeploymentEnvironmentId))); - var channels = actions.SelectMany(a => a.Channels).Select(x => x.Value).Select(id => (id, typeof(Channel))); - var tenantTags = actions.SelectMany(a => a.TenantTags).Select(x => x.Value).Select(id => (id, typeof(TagSetId))); + var environments = actions.SelectMany(a => a.Environments).Select(x => x.Value).Select(id => (id, typeof(DeploymentEnvironmentId))); + var excludedEnvironments = actions.SelectMany(a => a.ExcludedEnvironments).Select(x => x.Value).Select(id => (id, typeof(DeploymentEnvironmentId))); + var channels = actions.SelectMany(a => a.Channels).Select(x => x.Value).Select(id => (id, typeof(Channel))); + var tenantTags = actions.SelectMany(a => a.TenantTags).Select(x => x.Value).Select(id => (id, typeof(TagSetId))); - return environments - .Concat(excludedEnvironments) - .Concat(channels) - .Concat(tenantTags); - } + return environments + .Concat(excludedEnvironments) + .Concat(channels) + .Concat(tenantTags); } } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/TagCanonicalIdOrName.cs b/source/Tests/RealLifeScenario/Entities/TagCanonicalIdOrName.cs index f553174..1a85cf0 100644 --- a/source/Tests/RealLifeScenario/Entities/TagCanonicalIdOrName.cs +++ b/source/Tests/RealLifeScenario/Entities/TagCanonicalIdOrName.cs @@ -1,13 +1,12 @@ using System; using Octopus.TinyTypes; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class TagCanonicalIdOrName : CaseInsensitiveStringTinyType { - public class TagCanonicalIdOrName : CaseInsensitiveStringTinyType + public TagCanonicalIdOrName(string value) + : base(value) { - public TagCanonicalIdOrName(string value) - : base(value) - { - } } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/VcsRunbook.cs b/source/Tests/RealLifeScenario/Entities/VcsRunbook.cs index d5fc555..ef8415d 100644 --- a/source/Tests/RealLifeScenario/Entities/VcsRunbook.cs +++ b/source/Tests/RealLifeScenario/Entities/VcsRunbook.cs @@ -3,36 +3,35 @@ using Octopus.Server.Extensibility.HostServices.Model.Projects; using Octopus.Server.Extensibility.HostServices.Model.Tenants; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class VcsRunbook { - public class VcsRunbook - { - public VcsRunbook(string name) - => Name = name; + public VcsRunbook(string name) + => Name = name; - public string Name { get; } + public string Name { get; } - public string Description { get; set; } = ""; + public string Description { get; set; } = ""; - public TenantedDeploymentMode MultiTenancyMode { get; set; } + public TenantedDeploymentMode MultiTenancyMode { get; set; } - public ProjectConnectivityPolicy ConnectivityPolicy { get; set; } = new ProjectConnectivityPolicy - { - AllowDeploymentsToNoTargets = true - }; + public ProjectConnectivityPolicy ConnectivityPolicy { get; set; } = new() + { + AllowDeploymentsToNoTargets = true + }; - public RunbookEnvironmentScope EnvironmentScope { get; set; } + public RunbookEnvironmentScope EnvironmentScope { get; set; } - public ReferenceCollection Environments { get; } = new ReferenceCollection(); + public ReferenceCollection Environments { get; } = new(); - public GuidedFailureMode DefaultGuidedFailureMode { get; set; } - } + public GuidedFailureMode DefaultGuidedFailureMode { get; set; } +} - public class ProjectConnectivityPolicy - { - public bool AllowDeploymentsToNoTargets { get; set; } - public ReferenceCollection? TargetRoles { get; set; } - public bool ExcludeUnhealthyTargets { get; set; } - public SkipMachineBehavior SkipMachineBehavior { get; set; } - } +public class ProjectConnectivityPolicy +{ + public bool AllowDeploymentsToNoTargets { get; set; } + public ReferenceCollection? TargetRoles { get; set; } + public bool ExcludeUnhealthyTargets { get; set; } + public SkipMachineBehavior SkipMachineBehavior { get; set; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/VcsRunbookPersistenceModel.cs b/source/Tests/RealLifeScenario/Entities/VcsRunbookPersistenceModel.cs index 7dc3db5..7915200 100644 --- a/source/Tests/RealLifeScenario/Entities/VcsRunbookPersistenceModel.cs +++ b/source/Tests/RealLifeScenario/Entities/VcsRunbookPersistenceModel.cs @@ -1,14 +1,13 @@ using System; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class VcsRunbookPersistenceModel { - public class VcsRunbookPersistenceModel - { - public VcsRunbookPersistenceModel(VcsRunbook runbook) - => Runbook = runbook; + public VcsRunbookPersistenceModel(VcsRunbook runbook) + => Runbook = runbook; - public VcsRunbook Runbook { get; } + public VcsRunbook Runbook { get; } - public RunbookProcess? Process { get; set; } - } + public RunbookProcess? Process { get; set; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Entities/WorkerPoolIdOrName.cs b/source/Tests/RealLifeScenario/Entities/WorkerPoolIdOrName.cs index 60574c3..28b33a7 100644 --- a/source/Tests/RealLifeScenario/Entities/WorkerPoolIdOrName.cs +++ b/source/Tests/RealLifeScenario/Entities/WorkerPoolIdOrName.cs @@ -1,13 +1,12 @@ using System; using Octopus.TinyTypes; -namespace Tests.RealLifeScenario.Entities +namespace Tests.RealLifeScenario.Entities; + +public class WorkerPoolIdOrName : CaseInsensitiveStringTinyType { - public class WorkerPoolIdOrName : CaseInsensitiveStringTinyType + public WorkerPoolIdOrName(string value) + : base(value) { - public WorkerPoolIdOrName(string value) - : base(value) - { - } } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/DeploymentActionOclConverter.cs b/source/Tests/RealLifeScenario/Implementation/DeploymentActionOclConverter.cs index bfe99f7..646d1f4 100644 --- a/source/Tests/RealLifeScenario/Implementation/DeploymentActionOclConverter.cs +++ b/source/Tests/RealLifeScenario/Implementation/DeploymentActionOclConverter.cs @@ -7,79 +7,78 @@ using Octopus.Ocl.Converters; using Tests.RealLifeScenario.Entities; -namespace Tests.RealLifeScenario.Implementation +namespace Tests.RealLifeScenario.Implementation; + +public class DeploymentActionOclConverter : DefaultBlockOclConverter { - public class DeploymentActionOclConverter : DefaultBlockOclConverter + public override bool CanConvert(Type type) + => type == typeof(DeploymentAction); + + protected override IOclElement ConvertInternal(OclConversionContext context, PropertyInfo? propertyInfo, object obj) { - public override bool CanConvert(Type type) - => type == typeof(DeploymentAction); + var action = (DeploymentAction)obj; + if (string.IsNullOrWhiteSpace(action.Name)) + throw new Exception("The name of the action must be set"); - protected override IOclElement ConvertInternal(OclConversionContext context, PropertyInfo? propertyInfo, object obj) - { - var action = (DeploymentAction)obj; - if (string.IsNullOrWhiteSpace(action.Name)) - throw new Exception("The name of the action must be set"); + return base.ConvertInternal(context, propertyInfo, obj); + } - return base.ConvertInternal(context, propertyInfo, obj); - } + protected override object CreateInstance(Type type, IOclElement oclElement) + { + var block = (OclBlock)oclElement; - protected override object CreateInstance(Type type, IOclElement oclElement) - { - var block = (OclBlock)oclElement; + if (block.Labels.Count != 1) + throw new OclException("The block for a deployment action must contain one label, the name of the step"); - if (block.Labels.Count != 1) - throw new OclException("The block for a deployment action must contain one label, the name of the step"); + var actionTypeElement = (OclAttribute?)block.FirstOrDefault(b => b.Name == "action_type"); + if (actionTypeElement == null) + throw new OclException("The block for a deployment action must contain the type field"); - var actionTypeElement = (OclAttribute?)block.FirstOrDefault(b => b.Name == "action_type"); - if (actionTypeElement == null) - throw new OclException("The block for a deployment action must contain the type field"); + var actionType = actionTypeElement.Value as string; + if (actionType == null) + throw new OclException("The action type must be a string and not null"); - var actionType = actionTypeElement.Value as string; - if (actionType == null) - throw new OclException("The action type must be a string and not null"); + return new DeploymentAction(block.Labels[0], actionType); + } - return new DeploymentAction(block.Labels[0], actionType); - } + protected override void SetLabels(Type type, OclBlock block, object target) + { + } - protected override void SetLabels(Type type, OclBlock block, object target) + protected override IEnumerable GetLabelProperties(Type type) + => new[] { - } + typeof(DeploymentAction).GetProperty(nameof(DeploymentAction.Name))! + }; - protected override IEnumerable GetLabelProperties(Type type) - => new[] - { - typeof(DeploymentAction).GetProperty(nameof(DeploymentAction.Name))! - }; + protected override IEnumerable GetProperties(Type type) + => base.GetProperties(type).Where(ShouldSerialize); - protected override IEnumerable GetProperties(Type type) - => base.GetProperties(type).Where(ShouldSerialize); - - internal static bool ShouldSerialize(PropertyInfo property) + internal static bool ShouldSerialize(PropertyInfo property) + { + switch (property.Name) { - switch (property.Name) - { - case nameof(DeploymentAction.Id): - return false; - } - - return property.GetCustomAttribute() == null; + case nameof(DeploymentAction.Id): + return false; } - protected override IEnumerable GetElements(object obj, OclConversionContext context) - { - var elements = base.GetElements(obj, context).ToList(); - elements.RemoveAll(e => e.Name == "container" && ((OclBlock)e).None()); - return elements; - } + return property.GetCustomAttribute() == null; + } - public override object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) - { - var obj = base.FromElement(context, type, element, currentValue); + protected override IEnumerable GetElements(object obj, OclConversionContext context) + { + var elements = base.GetElements(obj, context).ToList(); + elements.RemoveAll(e => e.Name == "container" && ((OclBlock)e).None()); + return elements; + } - if (obj is DeploymentAction action) - action.Id = action.Name.Replace(" ", "-"); + public override object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) + { + var obj = base.FromElement(context, type, element, currentValue); - return obj; - } + if (obj is DeploymentAction action) + action.Id = action.Name.Replace(" ", "-"); + + return obj; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/DeploymentStepOclConverter.cs b/source/Tests/RealLifeScenario/Implementation/DeploymentStepOclConverter.cs index 24d2eeb..882ac20 100644 --- a/source/Tests/RealLifeScenario/Implementation/DeploymentStepOclConverter.cs +++ b/source/Tests/RealLifeScenario/Implementation/DeploymentStepOclConverter.cs @@ -6,58 +6,57 @@ using Octopus.Ocl.Converters; using Tests.RealLifeScenario.Entities; -namespace Tests.RealLifeScenario.Implementation +namespace Tests.RealLifeScenario.Implementation; + +public class DeploymentStepOclConverter : DefaultBlockOclConverter { - public class DeploymentStepOclConverter : DefaultBlockOclConverter + protected override IOclElement ConvertInternal(OclConversionContext context, PropertyInfo? propertyInfo, object obj) { - protected override IOclElement ConvertInternal(OclConversionContext context, PropertyInfo? propertyInfo, object obj) - { - var step = (DeploymentStep)obj; - if (string.IsNullOrWhiteSpace(step.Name)) - throw new Exception("The name of the action must be set"); + var step = (DeploymentStep)obj; + if (string.IsNullOrWhiteSpace(step.Name)) + throw new Exception("The name of the action must be set"); - return base.ConvertInternal(context, propertyInfo, obj); - } + return base.ConvertInternal(context, propertyInfo, obj); + } - public override bool CanConvert(Type type) - => type == typeof(DeploymentStep); + public override bool CanConvert(Type type) + => type == typeof(DeploymentStep); - protected override object CreateInstance(Type type, IOclElement oclElement) - { - var block = (OclBlock)oclElement; + protected override object CreateInstance(Type type, IOclElement oclElement) + { + var block = (OclBlock)oclElement; - if (block.Labels.Count != 1) - throw new OclException("The block for a deployment step must contain one label, the name of the step"); + if (block.Labels.Count != 1) + throw new OclException("The block for a deployment step must contain one label, the name of the step"); - return new DeploymentStep(block.Labels[0]); - } + return new DeploymentStep(block.Labels[0]); + } - protected override void SetLabels(Type type, OclBlock block, object target) - { - } + protected override void SetLabels(Type type, OclBlock block, object target) + { + } - protected override IEnumerable GetLabelProperties(Type type) - => new[] - { - typeof(DeploymentStep).GetProperty(nameof(DeploymentStep.Name))! - }; + protected override IEnumerable GetLabelProperties(Type type) + => new[] + { + typeof(DeploymentStep).GetProperty(nameof(DeploymentStep.Name))! + }; - protected override IEnumerable GetProperties(Type type) - => base.GetProperties(type).Where(ShouldSerialize); + protected override IEnumerable GetProperties(Type type) + => base.GetProperties(type).Where(ShouldSerialize); - internal static bool ShouldSerialize(PropertyInfo property) + internal static bool ShouldSerialize(PropertyInfo property) + { + switch (property.Name) { - switch (property.Name) - { - case nameof(DeploymentStep.Id): - return false; + case nameof(DeploymentStep.Id): + return false; - case nameof(DeploymentStep.Actions): - case nameof(DeploymentStep.Properties): - return true; - } - - return property.CanWrite; + case nameof(DeploymentStep.Actions): + case nameof(DeploymentStep.Properties): + return true; } + + return property.CanWrite; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/OclConverterExtensions.cs b/source/Tests/RealLifeScenario/Implementation/OclConverterExtensions.cs index da3b0aa..4dd6df4 100644 --- a/source/Tests/RealLifeScenario/Implementation/OclConverterExtensions.cs +++ b/source/Tests/RealLifeScenario/Implementation/OclConverterExtensions.cs @@ -3,18 +3,17 @@ using System.Linq; using Octopus.Ocl; -namespace Tests.RealLifeScenario.Implementation +namespace Tests.RealLifeScenario.Implementation; + +public static class OclConverterExtensions { - public static class OclConverterExtensions - { - public static IEnumerable OrderByThenAlpha(this IEnumerable elements, params string[] names) - => from e in elements - let index = Array.FindIndex(names, n => n.Equals(e.Name, StringComparison.OrdinalIgnoreCase)) - orderby - e is OclAttribute, - index == -1, - index, - e.Name - select e; - } + public static IEnumerable OrderByThenAlpha(this IEnumerable elements, params string[] names) + => from e in elements + let index = Array.FindIndex(names, n => n.Equals(e.Name, StringComparison.OrdinalIgnoreCase)) + orderby + e is OclAttribute, + index == -1, + index, + e.Name + select e; } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/OclSerializerFactory.cs b/source/Tests/RealLifeScenario/Implementation/OclSerializerFactory.cs index 54128ed..122c8cc 100644 --- a/source/Tests/RealLifeScenario/Implementation/OclSerializerFactory.cs +++ b/source/Tests/RealLifeScenario/Implementation/OclSerializerFactory.cs @@ -2,25 +2,24 @@ using System.Collections.Generic; using Octopus.Ocl; -namespace Tests.RealLifeScenario.Implementation +namespace Tests.RealLifeScenario.Implementation; + +public class OclSerializerFactory { - public class OclSerializerFactory - { - public IOclSerializer Create() - => new OclSerializer( - new OclSerializerOptions + public IOclSerializer Create() + => new OclSerializer( + new OclSerializerOptions + { + Converters = new List { - Converters = new List - { - new ReferenceCollectionOclConverter(), - new TinyTypeOclConverter(), - new TinyTypeReferenceCollectionOclConverter(), - new DeploymentStepOclConverter(), - new DeploymentActionOclConverter(), - new PackageReferenceOclConverter(), - new PropertiesDictionaryOclConverter(), - new VcsRunbookPersistenceModelOclConverter() - } - }); - } + new ReferenceCollectionOclConverter(), + new TinyTypeOclConverter(), + new TinyTypeReferenceCollectionOclConverter(), + new DeploymentStepOclConverter(), + new DeploymentActionOclConverter(), + new PackageReferenceOclConverter(), + new PropertiesDictionaryOclConverter(), + new VcsRunbookPersistenceModelOclConverter() + } + }); } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/PackageReferenceOclConverter.cs b/source/Tests/RealLifeScenario/Implementation/PackageReferenceOclConverter.cs index 1f7db42..5dcd34f 100644 --- a/source/Tests/RealLifeScenario/Implementation/PackageReferenceOclConverter.cs +++ b/source/Tests/RealLifeScenario/Implementation/PackageReferenceOclConverter.cs @@ -6,48 +6,47 @@ using Octopus.Ocl.Converters; using Octopus.Server.Extensibility.HostServices.Model; -namespace Tests.RealLifeScenario.Implementation +namespace Tests.RealLifeScenario.Implementation; + +public class PackageReferenceOclConverter : DefaultBlockOclConverter { - public class PackageReferenceOclConverter : DefaultBlockOclConverter + readonly IReadOnlyList labelProperties = new[] { - readonly IReadOnlyList labelProperties = new[] - { - typeof(PackageReference).GetProperty(nameof(PackageReference.Name))! - }; + typeof(PackageReference).GetProperty(nameof(PackageReference.Name))! + }; - public override bool CanConvert(Type type) - => type == typeof(PackageReference); + public override bool CanConvert(Type type) + => type == typeof(PackageReference); - protected override void SetLabels(Type type, OclBlock block, object target) - { - if (block.Labels.Count == 0) - return; - if (block.Labels.Count > 1) - throw new OclException("Package reference blocks can only have zero or one label"); + protected override void SetLabels(Type type, OclBlock block, object target) + { + if (block.Labels.Count == 0) + return; + if (block.Labels.Count > 1) + throw new OclException("Package reference blocks can only have zero or one label"); - ((PackageReference)target).Name = block.Labels[0]; - } + ((PackageReference)target).Name = block.Labels[0]; + } - protected override IEnumerable GetLabels(object obj) - { - var name = ((PackageReference)obj).Name; - return string.IsNullOrWhiteSpace(name) ? Array.Empty() : new[] { name }; - } + protected override IEnumerable GetLabels(object obj) + { + var name = ((PackageReference)obj).Name; + return string.IsNullOrWhiteSpace(name) ? Array.Empty() : new[] { name }; + } - protected override IEnumerable GetProperties(Type type) - => base.GetProperties(type).Where(ShouldSerialize); + protected override IEnumerable GetProperties(Type type) + => base.GetProperties(type).Where(ShouldSerialize); - internal static bool ShouldSerialize(PropertyInfo property) + internal static bool ShouldSerialize(PropertyInfo property) + { + switch (property.Name) { - switch (property.Name) - { - case nameof(PackageReference.Id): - case nameof(PackageReference.Name): - case nameof(PackageReference.IsPrimaryPackage): - return false; - } - - return true; + case nameof(PackageReference.Id): + case nameof(PackageReference.Name): + case nameof(PackageReference.IsPrimaryPackage): + return false; } + + return true; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/PropertiesDictionaryOclConverter.cs b/source/Tests/RealLifeScenario/Implementation/PropertiesDictionaryOclConverter.cs index 3a5d7a8..4999597 100644 --- a/source/Tests/RealLifeScenario/Implementation/PropertiesDictionaryOclConverter.cs +++ b/source/Tests/RealLifeScenario/Implementation/PropertiesDictionaryOclConverter.cs @@ -6,52 +6,51 @@ using Octopus.Server.Extensibility.HostServices.Model; using Tests.RealLifeScenario.Entities; -namespace Tests.RealLifeScenario.Implementation -{ - public class PropertiesDictionaryOclConverter : IOclConverter - { - public bool CanConvert(Type type) - => type == typeof(PropertiesDictionary); +namespace Tests.RealLifeScenario.Implementation; - public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) - { - var dict = (PropertiesDictionary)value; +public class PropertiesDictionaryOclConverter : IOclConverter +{ + public bool CanConvert(Type type) + => type == typeof(PropertiesDictionary); - if (dict.None()) - yield break; + public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) + { + var dict = (PropertiesDictionary)value; - if (dict.Values.Any(v => v.IsSensitive)) - throw new NotSupportedException("Sensitive property values are not supported"); + if (dict.None()) + yield break; - var stringDict = dict.ToDictionary( - kvp => kvp.Key, - kvp => kvp.Value.Value - ); + if (dict.Values.Any(v => v.IsSensitive)) + throw new NotSupportedException("Sensitive property values are not supported"); - yield return new OclAttribute("properties", stringDict); - } + var stringDict = dict.ToDictionary( + kvp => kvp.Key, + kvp => kvp.Value.Value + ); - public OclDocument ToDocument(OclConversionContext context, object obj) - => throw new NotSupportedException(); + yield return new OclAttribute("properties", stringDict); + } - public object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) - { - if (!(element is OclAttribute attribute)) - throw new OclException("The properties must be an attribute"); + public OclDocument ToDocument(OclConversionContext context, object obj) + => throw new NotSupportedException(); - var properties = currentValue == null ? new PropertiesDictionary() : (PropertiesDictionary)currentValue; + public object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) + { + if (!(element is OclAttribute attribute)) + throw new OclException("The properties must be an attribute"); - if (!(attribute.Value is Dictionary source)) - throw new OclException("The properties attribute value must be a dictionary"); + var properties = currentValue == null ? new PropertiesDictionary() : (PropertiesDictionary)currentValue; - foreach (var item in source) - { - var itemValue = item.Value is OclStringLiteral lit ? lit.Value : item.Value?.ToString(); - if (itemValue != null) - properties[item.Key] = new PropertyValue(itemValue); - } + if (!(attribute.Value is Dictionary source)) + throw new OclException("The properties attribute value must be a dictionary"); - return properties; + foreach (var item in source) + { + var itemValue = item.Value is OclStringLiteral lit ? lit.Value : item.Value?.ToString(); + if (itemValue != null) + properties[item.Key] = new PropertyValue(itemValue); } + + return properties; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/ReferenceCollectionOclConverter.cs b/source/Tests/RealLifeScenario/Implementation/ReferenceCollectionOclConverter.cs index e632d99..91bc942 100644 --- a/source/Tests/RealLifeScenario/Implementation/ReferenceCollectionOclConverter.cs +++ b/source/Tests/RealLifeScenario/Implementation/ReferenceCollectionOclConverter.cs @@ -5,42 +5,41 @@ using Octopus.Data.Model; using Octopus.Ocl; -namespace Tests.RealLifeScenario.Implementation +namespace Tests.RealLifeScenario.Implementation; + +public class ReferenceCollectionOclConverter : IOclConverter { - public class ReferenceCollectionOclConverter : IOclConverter - { - public bool CanConvert(Type type) - => type == typeof(ReferenceCollection); + public bool CanConvert(Type type) + => type == typeof(ReferenceCollection); - public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) - { - var collection = (ReferenceCollection)value; + public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) + { + var collection = (ReferenceCollection)value; - if (collection.Count == 0) - return Array.Empty(); + if (collection.Count == 0) + return Array.Empty(); - return new[] - { - new OclAttribute(context.Namer.FormatName(propertyInfo!.Name), collection.ToArray()) - }; - } + return new[] + { + new OclAttribute(context.Namer.FormatName(propertyInfo!.Name), collection.ToArray()) + }; + } - public OclDocument ToDocument(OclConversionContext context, object obj) - => throw new NotSupportedException(); + public OclDocument ToDocument(OclConversionContext context, object obj) + => throw new NotSupportedException(); - public object FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) - { - if (!(element is OclAttribute attrib)) - throw new OclException($"The {element.Name} element must be an attribute"); + public object FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) + { + if (!(element is OclAttribute attrib)) + throw new OclException($"The {element.Name} element must be an attribute"); - if (!(attrib.Value is string[] valuesToAdd)) - throw new Exception($"The {element.Name} attribute must have a string array value"); + if (!(attrib.Value is string[] valuesToAdd)) + throw new Exception($"The {element.Name} attribute must have a string array value"); - var collection = currentValue == null ? new ReferenceCollection() : (ReferenceCollection)currentValue; + var collection = currentValue == null ? new ReferenceCollection() : (ReferenceCollection)currentValue; - collection.ReplaceAll(valuesToAdd); + collection.ReplaceAll(valuesToAdd); - return collection; - } + return collection; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/TinyTypeOclConverter.cs b/source/Tests/RealLifeScenario/Implementation/TinyTypeOclConverter.cs index 8fc276e..ad9b22f 100644 --- a/source/Tests/RealLifeScenario/Implementation/TinyTypeOclConverter.cs +++ b/source/Tests/RealLifeScenario/Implementation/TinyTypeOclConverter.cs @@ -4,31 +4,30 @@ using Octopus.Ocl; using Octopus.TinyTypes; -namespace Tests.RealLifeScenario.Implementation +namespace Tests.RealLifeScenario.Implementation; + +public class TinyTypeOclConverter : IOclConverter { - public class TinyTypeOclConverter : IOclConverter - { - public bool CanConvert(Type type) - => type.IsTinyType(); + public bool CanConvert(Type type) + => type.IsTinyType(); - public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) - => new[] - { - new OclAttribute(context.Namer.FormatName(propertyInfo!.Name), value.ToString()) - }; + public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) + => new[] + { + new OclAttribute(context.Namer.FormatName(propertyInfo!.Name), value.ToString()) + }; - public OclDocument ToDocument(OclConversionContext context, object obj) - => throw new NotSupportedException(); + public OclDocument ToDocument(OclConversionContext context, object obj) + => throw new NotSupportedException(); - public object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) - { - if (!(element is OclAttribute attrib)) - throw new OclException($"The {element.Name} element must be an attribute"); + public object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) + { + if (!(element is OclAttribute attrib)) + throw new OclException($"The {element.Name} element must be an attribute"); - if (attrib.Value is string str) - return Activator.CreateInstance(type, str); + if (attrib.Value is string str) + return Activator.CreateInstance(type, str); - throw new Exception($"The {element.Name} attribute must have a string value"); - } + throw new Exception($"The {element.Name} attribute must have a string value"); } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/TinyTypeReferenceCollectionOclConverter.cs b/source/Tests/RealLifeScenario/Implementation/TinyTypeReferenceCollectionOclConverter.cs index 7946f24..5158171 100644 --- a/source/Tests/RealLifeScenario/Implementation/TinyTypeReferenceCollectionOclConverter.cs +++ b/source/Tests/RealLifeScenario/Implementation/TinyTypeReferenceCollectionOclConverter.cs @@ -7,55 +7,54 @@ using Octopus.Ocl; using Octopus.TinyTypes; -namespace Tests.RealLifeScenario.Implementation +namespace Tests.RealLifeScenario.Implementation; + +public class TinyTypeReferenceCollectionOclConverter : IOclConverter { - public class TinyTypeReferenceCollectionOclConverter : IOclConverter - { - public bool CanConvert(Type type) - => GetUnderlyingTypeOfReferenceCollection(type)?.IsTinyType() ?? false; + public bool CanConvert(Type type) + => GetUnderlyingTypeOfReferenceCollection(type)?.IsTinyType() ?? false; - static Type? GetUnderlyingTypeOfReferenceCollection(Type type) - { - if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ReferenceCollection<>)) - return type.GenericTypeArguments[0]; + static Type? GetUnderlyingTypeOfReferenceCollection(Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ReferenceCollection<>)) + return type.GenericTypeArguments[0]; - return type.BaseType == null ? null : GetUnderlyingTypeOfReferenceCollection(type.BaseType); - } + return type.BaseType == null ? null : GetUnderlyingTypeOfReferenceCollection(type.BaseType); + } - public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) - { - var values = ((IEnumerable)value) - .Cast() - .Select(v => v.ToString()) - .ToArray(); + public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) + { + var values = ((IEnumerable)value) + .Cast() + .Select(v => v.ToString()) + .ToArray(); - if (values.Length == 0) - return Array.Empty(); + if (values.Length == 0) + return Array.Empty(); - return new[] - { - new OclAttribute(context.Namer.FormatName(propertyInfo!.Name), values) - }; - } + return new[] + { + new OclAttribute(context.Namer.FormatName(propertyInfo!.Name), values) + }; + } - public OclDocument ToDocument(OclConversionContext context, object obj) - => throw new NotSupportedException(); + public OclDocument ToDocument(OclConversionContext context, object obj) + => throw new NotSupportedException(); - public object FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) - { - if (!(element is OclAttribute attrib)) - throw new OclException($"The {element.Name} element must be an attribute"); + public object FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) + { + if (!(element is OclAttribute attrib)) + throw new OclException($"The {element.Name} element must be an attribute"); - if (!(attrib.Value is string[] valuesToAdd)) - throw new Exception($"The {element.Name} attribute must have a string array value"); + if (!(attrib.Value is string[] valuesToAdd)) + throw new Exception($"The {element.Name} attribute must have a string array value"); - dynamic collection = currentValue ?? Activator.CreateInstance(type, new object?[] { null })!; - var tinyTypeType = GetUnderlyingTypeOfReferenceCollection(collection.GetType()); + dynamic collection = currentValue ?? Activator.CreateInstance(type, new object?[] { null })!; + var tinyTypeType = GetUnderlyingTypeOfReferenceCollection(collection.GetType()); - foreach (var value in valuesToAdd) - collection.Add(Activator.CreateInstance(tinyTypeType, value)); + foreach (var value in valuesToAdd) + collection.Add(Activator.CreateInstance(tinyTypeType, value)); - return (object)collection; - } + return (object)collection; } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/Implementation/VcsRunbookPersistenceModelOclConverter.cs b/source/Tests/RealLifeScenario/Implementation/VcsRunbookPersistenceModelOclConverter.cs index 24047dc..38ac25e 100644 --- a/source/Tests/RealLifeScenario/Implementation/VcsRunbookPersistenceModelOclConverter.cs +++ b/source/Tests/RealLifeScenario/Implementation/VcsRunbookPersistenceModelOclConverter.cs @@ -7,113 +7,112 @@ using Octopus.Ocl.Converters; using Tests.RealLifeScenario.Entities; -namespace Tests.RealLifeScenario.Implementation +namespace Tests.RealLifeScenario.Implementation; + +public class VcsRunbookPersistenceModelOclConverter : IOclConverter { - public class VcsRunbookPersistenceModelOclConverter : IOclConverter + readonly RunbookProcessOclConverter processConverter; + readonly VcsRunbookOclConverter runbookConverter; + + public VcsRunbookPersistenceModelOclConverter() { - readonly RunbookProcessOclConverter processConverter; - readonly VcsRunbookOclConverter runbookConverter; + runbookConverter = new VcsRunbookOclConverter(); + processConverter = new RunbookProcessOclConverter(); + } - public VcsRunbookPersistenceModelOclConverter() - { - runbookConverter = new VcsRunbookOclConverter(); - processConverter = new RunbookProcessOclConverter(); - } + public bool CanConvert(Type type) + => type == typeof(VcsRunbookPersistenceModel); - public bool CanConvert(Type type) - => type == typeof(VcsRunbookPersistenceModel); + public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) + => throw new NotSupportedException(); - public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) - => throw new NotSupportedException(); + public OclDocument ToDocument(OclConversionContext context, object obj) + { + var model = (VcsRunbookPersistenceModel)obj; - public OclDocument ToDocument(OclConversionContext context, object obj) + var doc = runbookConverter.ToDocument(context, model.Runbook); + if (model.Process != null) { - var model = (VcsRunbookPersistenceModel)obj; - - var doc = runbookConverter.ToDocument(context, model.Runbook); - if (model.Process != null) - { - var process = processConverter.ToDocument(context, model.Process); + var process = processConverter.ToDocument(context, model.Process); - foreach (var child in process) - doc.Add(child); - } - - return doc; + foreach (var child in process) + doc.Add(child); } - public object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) - { - if (!(element is OclDocument doc)) - throw new OclException("Can only convert from OclDocument"); + return doc; + } - var (process, runbookElements) = processConverter.FromDocument(context, doc); + public object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) + { + if (!(element is OclDocument doc)) + throw new OclException("Can only convert from OclDocument"); - var runbook = runbookConverter.FromRemainingElements(context, runbookElements); + var (process, runbookElements) = processConverter.FromDocument(context, doc); - return new VcsRunbookPersistenceModel(runbook) - { - Process = process - }; - } + var runbook = runbookConverter.FromRemainingElements(context, runbookElements); - class VcsRunbookOclConverter : DefaultBlockOclConverter + return new VcsRunbookPersistenceModel(runbook) { - public override bool CanConvert(Type type) - => throw new NotImplementedException("This converter is used directly"); + Process = process + }; + } - public VcsRunbook FromRemainingElements(OclConversionContext context, IReadOnlyList runbookElements) - { - var name = runbookElements.OfType().First(r => r.Name == "name").Value?.ToString(); - var runbook = new VcsRunbook(name ?? ""); - var properties = GetProperties(typeof(VcsRunbook)).ToArray(); - SetProperties(context, runbookElements, runbook, properties); - return runbook; - } + class VcsRunbookOclConverter : DefaultBlockOclConverter + { + public override bool CanConvert(Type type) + => throw new NotImplementedException("This converter is used directly"); - protected override IEnumerable GetElements(object obj, OclConversionContext context) - => base.GetElements(obj, context) - .OrderByThenAlpha( - nameof(VcsRunbook.Name), - nameof(VcsRunbook.Description) - ); + public VcsRunbook FromRemainingElements(OclConversionContext context, IReadOnlyList runbookElements) + { + var name = runbookElements.OfType().First(r => r.Name == "name").Value?.ToString(); + var runbook = new VcsRunbook(name ?? ""); + var properties = GetProperties(typeof(VcsRunbook)).ToArray(); + SetProperties(context, runbookElements, runbook, properties); + return runbook; } - internal class RunbookProcessOclConverter : DefaultBlockOclConverter - { - public override bool CanConvert(Type type) - => type == typeof(RunbookProcess); + protected override IEnumerable GetElements(object obj, OclConversionContext context) + => base.GetElements(obj, context) + .OrderByThenAlpha( + nameof(VcsRunbook.Name), + nameof(VcsRunbook.Description) + ); + } - protected override IEnumerable GetProperties(Type type) - => base.GetProperties(type).Where(ShouldSerialize); + internal class RunbookProcessOclConverter : DefaultBlockOclConverter + { + public override bool CanConvert(Type type) + => type == typeof(RunbookProcess); - public (RunbookProcess process, IReadOnlyList notFound) FromDocument( - OclConversionContext context, - OclDocument doc - ) - { - var runbook = new RunbookProcess("PLACEHOLDER", "PLACEHOLDER"); + protected override IEnumerable GetProperties(Type type) + => base.GetProperties(type).Where(ShouldSerialize); - var properties = GetProperties(typeof(RunbookProcess)).ToArray(); - var notFound = SetProperties(context, doc, runbook, properties); + public (RunbookProcess process, IReadOnlyList notFound) FromDocument( + OclConversionContext context, + OclDocument doc + ) + { + var runbook = new RunbookProcess("PLACEHOLDER", "PLACEHOLDER"); - return (runbook, notFound); - } + var properties = GetProperties(typeof(RunbookProcess)).ToArray(); + var notFound = SetProperties(context, doc, runbook, properties); - internal static bool ShouldSerialize(PropertyInfo property) + return (runbook, notFound); + } + + internal static bool ShouldSerialize(PropertyInfo property) + { + switch (property.Name) { - switch (property.Name) - { - case nameof(RunbookProcess.Id): - case nameof(RunbookProcess.SpaceId): - case nameof(RunbookProcess.OwnerId): - case nameof(RunbookProcess.IsFrozen): - case nameof(RunbookProcess.Version): - return false; - } - - return property.GetCustomAttribute() == null; + case nameof(RunbookProcess.Id): + case nameof(RunbookProcess.SpaceId): + case nameof(RunbookProcess.OwnerId): + case nameof(RunbookProcess.IsFrozen): + case nameof(RunbookProcess.Version): + return false; } + + return property.GetCustomAttribute() == null; } } } \ No newline at end of file diff --git a/source/Tests/RealLifeScenario/RealLifeScenarioFixtureBase.cs b/source/Tests/RealLifeScenario/RealLifeScenarioFixtureBase.cs index 40ee561..1a7a740 100644 --- a/source/Tests/RealLifeScenario/RealLifeScenarioFixtureBase.cs +++ b/source/Tests/RealLifeScenario/RealLifeScenarioFixtureBase.cs @@ -13,205 +13,204 @@ using Tests.RealLifeScenario.Entities; using Tests.RealLifeScenario.Implementation; -namespace Tests.RealLifeScenario +namespace Tests.RealLifeScenario; + +public class RealLifeScenarioFixture { - public class RealLifeScenarioFixture - { - const string SpaceId = "Spaces-1"; - const string ProjectId = "Projects-1"; + const string SpaceId = "Spaces-1"; + const string ProjectId = "Projects-1"; - protected string Serialize(VcsRunbookPersistenceModel model) - => new OclSerializerFactory().Create().Serialize(model); + protected string Serialize(VcsRunbookPersistenceModel model) + => new OclSerializerFactory().Create().Serialize(model); - protected VcsRunbookPersistenceModel Deserialize(string ocl) - => new OclSerializerFactory().Create().Deserialize(ocl); + protected VcsRunbookPersistenceModel Deserialize(string ocl) + => new OclSerializerFactory().Create().Deserialize(ocl); - [Test] - public void MostFieldsWithNonDefaults() - => ExecuteTest( - new VcsRunbook("My Runbook") + [Test] + public void MostFieldsWithNonDefaults() + => ExecuteTest( + new VcsRunbook("My Runbook") + { + Description = "This is a \n multiline a description with trailing newline\n", + EnvironmentScope = RunbookEnvironmentScope.Specified, + Environments = { "Production", "Development" }, + ConnectivityPolicy = new ProjectConnectivityPolicy { - Description = "This is a \n multiline a description with trailing newline\n", - EnvironmentScope = RunbookEnvironmentScope.Specified, - Environments = { "Production", "Development" }, - ConnectivityPolicy = new ProjectConnectivityPolicy - { - TargetRoles = new ReferenceCollection("Target Role"), - ExcludeUnhealthyTargets = true, - SkipMachineBehavior = SkipMachineBehavior.SkipUnavailableMachines, - AllowDeploymentsToNoTargets = true - }, - MultiTenancyMode = TenantedDeploymentMode.TenantedOrUntenanted, - DefaultGuidedFailureMode = GuidedFailureMode.On + TargetRoles = new ReferenceCollection("Target Role"), + ExcludeUnhealthyTargets = true, + SkipMachineBehavior = SkipMachineBehavior.SkipUnavailableMachines, + AllowDeploymentsToNoTargets = true }, - new RunbookProcess(ProjectId, SpaceId) + MultiTenancyMode = TenantedDeploymentMode.TenantedOrUntenanted, + DefaultGuidedFailureMode = GuidedFailureMode.On + }, + new RunbookProcess(ProjectId, SpaceId) + { + Id = "Should not appear", + Version = 4, + OwnerId = "Should not appear", + IsFrozen = true, + RunbookId = "Should not appear", + Steps = { - Id = "Should not appear", - Version = 4, - OwnerId = "Should not appear", - IsFrozen = true, - RunbookId = "Should not appear", - Steps = + new DeploymentStep("Script Step") { - new DeploymentStep("Script Step") - { - Id = "Should Not Appear", + Id = "Should Not Appear", - Condition = DeploymentStepCondition.Always, - StartTrigger = DeploymentStepStartTrigger.StartWithPrevious, - PackageRequirement = DeploymentStepPackageRequirement.BeforePackageAcquisition, - Properties = - { - { "StepProperty", new PropertyValue("Value1") }, - { "Octopus.Action.TargetRoles", new PropertyValue("Portal") } - }, - Actions = + Condition = DeploymentStepCondition.Always, + StartTrigger = DeploymentStepStartTrigger.StartWithPrevious, + PackageRequirement = DeploymentStepPackageRequirement.BeforePackageAcquisition, + Properties = + { + { "StepProperty", new PropertyValue("Value1") }, + { "Octopus.Action.TargetRoles", new PropertyValue("Portal") } + }, + Actions = + { + new DeploymentAction("Script Step", ActionNames.Script) { - new DeploymentAction("Script Step", ActionNames.Script) + Id = "Should Not Appear", + Channels = { new ChannelIdOrName("Release"), new ChannelIdOrName("Beta") }, + Condition = DeploymentActionCondition.Variable, + Container = new DeploymentActionContainer + { + Image = "ContainerImage", + FeedId = "Container Feed" + }, + Environments = { new DeploymentEnvironmentIdOrName("Pre Production") }, + ExcludedEnvironments = { new DeploymentEnvironmentIdOrName("Production") }, + TenantTags = { new TagCanonicalIdOrName("David/Who") }, + WorkerPoolIdOrName = new WorkerPoolIdOrName("My Worker Pool"), + WorkerPoolVariable = "WorkerPoolVar", + IsDisabled = true, + IsRequired = true, + Packages = + { + new PackageReference("", "OctoFx.Web", new FeedIdOrName("External Feed"), PackageAcquisitionLocation.ExecutionTarget), + new PackageReference("Helper Package", "OctoFx.Helper", new FeedIdOrName("External Feed"), PackageAcquisitionLocation.Server) + }, + Properties = { - Id = "Should Not Appear", - Channels = { new ChannelIdOrName("Release"), new ChannelIdOrName("Beta") }, - Condition = DeploymentActionCondition.Variable, - Container = new DeploymentActionContainer - { - Image = "ContainerImage", - FeedId = "Container Feed" - }, - Environments = { new DeploymentEnvironmentIdOrName("Pre Production") }, - ExcludedEnvironments = { new DeploymentEnvironmentIdOrName("Production") }, - TenantTags = { new TagCanonicalIdOrName("David/Who") }, - WorkerPoolIdOrName = new WorkerPoolIdOrName("My Worker Pool"), - WorkerPoolVariable = "WorkerPoolVar", - IsDisabled = true, - IsRequired = true, - Packages = - { - new PackageReference("", "OctoFx.Web", new FeedIdOrName("External Feed"), PackageAcquisitionLocation.ExecutionTarget), - new PackageReference("Helper Package", "OctoFx.Helper", new FeedIdOrName("External Feed"), PackageAcquisitionLocation.Server) - }, - Properties = - { - { "Action.Prop", new PropertyValue("The Value") } - // { "Action.Sensitive", new PropertyValue("Sensitive Value", true) } - } + { "Action.Prop", new PropertyValue("The Value") } + // { "Action.Sensitive", new PropertyValue("Sensitive Value", true) } } } } } } - ); + } + ); - [Test] - public void Rolling() - => ExecuteTest( - new VcsRunbook("My Runbook"), - new RunbookProcess(ProjectId, SpaceId) + [Test] + public void Rolling() + => ExecuteTest( + new VcsRunbook("My Runbook"), + new RunbookProcess(ProjectId, SpaceId) + { + Steps = { - Steps = + new DeploymentStep("My Rolling Step") { - new DeploymentStep("My Rolling Step") + Actions = { - Actions = - { - new DeploymentAction("First", ActionNames.Script), - new DeploymentAction("Second", ActionNames.Script) - } + new DeploymentAction("First", ActionNames.Script), + new DeploymentAction("Second", ActionNames.Script) } } } - ); + } + ); - [Test] - public void ScriptAction() - => ExecuteTest( - new DeploymentAction("Backup the Database", ActionNames.Script) - .WithProperty("Octopus.Action.RunOnServer", "true") - .WithProperty("Octopus.Action.Script.Syntax", "PowerShell") - .WithProperty("Octopus.Action.Script.ScriptSource", "Inline") - .WithProperty( - "Octopus.Action.Script.ScriptBody", - "$backupResult = $OctopusParameters[\"Octopus.Action[Backup Octofront Prod SQL Database].Output.backupResult\"]\r\n\r\n\r\n$TableSAName = 'infrascoreprodaccount'\r\n$TableName = 'results'\r\n$partitionKey = \"OctofrontSQL\"\r\n\r\n$data = @{\r\n RowKey = ([guid]::NewGuid().tostring())\r\n PartitionKey = $partitionKey\r\n state = $backupResult \r\n description = \"Octofront SQL Backup weekly\"\r\n dtDate = [datetime]::UtcNow\r\n}\r\nNew-AzureTableEntity -StorageAccountName $TableSAName `\r\n -StorageAccountAccessKey $TableStorageKey `\r\n -TableName $TableName `\r\n -Entities $data \r\n\r\n$querystring = \"(PartitionKey eq '$partitionKey')\"\r\n$tableWrite = Get-AzureTableEntity -TableName $TableName `\r\n -StorageAccountName $TableSAName `\r\n -StorageAccountAccessKey $TableStorageKey `\r\n -QueryString $querystring `\r\n -ConvertDateTimeFields $true `\r\n -GetAll $false \r\n\r\n$ordered = $tableWrite | Sort-Object -Descending -Property Timestamp \r\n$entryResult = $ordered[0] | Sort-Object -Descending -Property Timestamp | Select-Object description, state\r\n\r\nwrite-output $entryResult | ft\r\n" - )); + [Test] + public void ScriptAction() + => ExecuteTest( + new DeploymentAction("Backup the Database", ActionNames.Script) + .WithProperty("Octopus.Action.RunOnServer", "true") + .WithProperty("Octopus.Action.Script.Syntax", "PowerShell") + .WithProperty("Octopus.Action.Script.ScriptSource", "Inline") + .WithProperty( + "Octopus.Action.Script.ScriptBody", + "$backupResult = $OctopusParameters[\"Octopus.Action[Backup Octofront Prod SQL Database].Output.backupResult\"]\r\n\r\n\r\n$TableSAName = 'infrascoreprodaccount'\r\n$TableName = 'results'\r\n$partitionKey = \"OctofrontSQL\"\r\n\r\n$data = @{\r\n RowKey = ([guid]::NewGuid().tostring())\r\n PartitionKey = $partitionKey\r\n state = $backupResult \r\n description = \"Octofront SQL Backup weekly\"\r\n dtDate = [datetime]::UtcNow\r\n}\r\nNew-AzureTableEntity -StorageAccountName $TableSAName `\r\n -StorageAccountAccessKey $TableStorageKey `\r\n -TableName $TableName `\r\n -Entities $data \r\n\r\n$querystring = \"(PartitionKey eq '$partitionKey')\"\r\n$tableWrite = Get-AzureTableEntity -TableName $TableName `\r\n -StorageAccountName $TableSAName `\r\n -StorageAccountAccessKey $TableStorageKey `\r\n -QueryString $querystring `\r\n -ConvertDateTimeFields $true `\r\n -GetAll $false \r\n\r\n$ordered = $tableWrite | Sort-Object -Descending -Property Timestamp \r\n$entryResult = $ordered[0] | Sort-Object -Descending -Property Timestamp | Select-Object description, state\r\n\r\nwrite-output $entryResult | ft\r\n" + )); - [Test] - public void IisAction() - => ExecuteTest( - new DeploymentAction("Deploy Website", ActionNames.Iis) - .WithProperty("Octopus.Action.IISWebSite.DeploymentType", "webSite") - .WithProperty("Octopus.Action.IISWebSite.CreateOrUpdateWebSite", "True") - .WithProperty("Octopus.Action.IISWebSite.Bindings", - "[{\"protocol\",\"https\",\"port\",\"443\",\"host\",\"#{Domain}\",\"thumbprint\",null,\"certificateVariable\",\"Certificate\",\"requireSni\",\"True\",\"enabled\",\"True\"){\"protocol\",\"https\",\"ipAddress\",\"\",\"port\",\"443\",\"host\",\"#{DirectDomainPrefix}.#{Domain}\",\"thumbprint\",null,\"certificateVariable\",\"Certificate\",\"requireSni\",\"True\",\"enabled\",true){\"protocol\",\"http\",\"ipAddress\",\"*\",\"port\",\"80\",\"host\",\"#{Domain}\",\"thumbprint\",null,\"certificateVariable\",null,\"requireSni\",false,\"enabled\",true){\"protocol\",\"http\",\"ipAddress\",\"*\",\"port\",\"80\",\"host\",\"www.#{Domain}\",\"thumbprint\",null,\"certificateVariable\",null,\"requireSni\",false,\"enabled\",true){\"protocol\",\"https\",\"ipAddress\",\"*\",\"port\",\"443\",\"host\",\"www.#{domain}\",\"thumbprint\",null,\"certificateVariable\",\"Certificate\",\"requireSni\",\"True\",\"enabled\",true}]") - .WithProperty("Octopus.Action.IISWebSite.ApplicationPoolIdentityType", "ApplicationPoolIdentity") - .WithProperty("Octopus.Action.IISWebSite.EnableAnonymousAuthentication", "True") - .WithProperty("Octopus.Action.IISWebSite.EnableBasicAuthentication", "False") - .WithProperty("Octopus.Action.IISWebSite.EnableWindowsAuthentication", "False") - .WithProperty("Octopus.Action.IISWebSite.WebApplication.ApplicationPoolFrameworkVersion", "v4.0") - .WithProperty("Octopus.Action.IISWebSite.WebApplication.ApplicationPoolIdentityType", "ApplicationPoolIdentity") - .WithProperty("Octopus.Action.EnabledFeatures", "Octopus.Features.IISWebSite,Octopus.Features.JsonConfigurationVariables") - .WithProperty("Octopus.Action.Package.FeedId", "My External Feed") - .WithProperty("Octopus.Action.Package.DownloadOnTentacle", "True") - .WithProperty("Octopus.Action.IISWebSite.WebRootType", "packageRoot") - .WithProperty("Octopus.Action.IISWebSite.StartApplicationPool", "True") - .WithProperty("Octopus.Action.IISWebSite.StartWebSite", "True") - .WithProperty("Octopus.Action.Package.PackageId", "OctoFX.Web") - .WithProperty("Octopus.Action.IISWebSite.WebSiteName", "#{Domain}") - .WithProperty("Octopus.Action.IISWebSite.ApplicationPoolName", "#{Domain}") - .WithProperty("Octopus.Action.Package.JsonConfigurationVariablesEnabled", "True") - .WithProperty("Octopus.Action.Package.JsonConfigurationVariablesTargets", "appsettings.json") - ); + [Test] + public void IisAction() + => ExecuteTest( + new DeploymentAction("Deploy Website", ActionNames.Iis) + .WithProperty("Octopus.Action.IISWebSite.DeploymentType", "webSite") + .WithProperty("Octopus.Action.IISWebSite.CreateOrUpdateWebSite", "True") + .WithProperty("Octopus.Action.IISWebSite.Bindings", + "[{\"protocol\",\"https\",\"port\",\"443\",\"host\",\"#{Domain}\",\"thumbprint\",null,\"certificateVariable\",\"Certificate\",\"requireSni\",\"True\",\"enabled\",\"True\"){\"protocol\",\"https\",\"ipAddress\",\"\",\"port\",\"443\",\"host\",\"#{DirectDomainPrefix}.#{Domain}\",\"thumbprint\",null,\"certificateVariable\",\"Certificate\",\"requireSni\",\"True\",\"enabled\",true){\"protocol\",\"http\",\"ipAddress\",\"*\",\"port\",\"80\",\"host\",\"#{Domain}\",\"thumbprint\",null,\"certificateVariable\",null,\"requireSni\",false,\"enabled\",true){\"protocol\",\"http\",\"ipAddress\",\"*\",\"port\",\"80\",\"host\",\"www.#{Domain}\",\"thumbprint\",null,\"certificateVariable\",null,\"requireSni\",false,\"enabled\",true){\"protocol\",\"https\",\"ipAddress\",\"*\",\"port\",\"443\",\"host\",\"www.#{domain}\",\"thumbprint\",null,\"certificateVariable\",\"Certificate\",\"requireSni\",\"True\",\"enabled\",true}]") + .WithProperty("Octopus.Action.IISWebSite.ApplicationPoolIdentityType", "ApplicationPoolIdentity") + .WithProperty("Octopus.Action.IISWebSite.EnableAnonymousAuthentication", "True") + .WithProperty("Octopus.Action.IISWebSite.EnableBasicAuthentication", "False") + .WithProperty("Octopus.Action.IISWebSite.EnableWindowsAuthentication", "False") + .WithProperty("Octopus.Action.IISWebSite.WebApplication.ApplicationPoolFrameworkVersion", "v4.0") + .WithProperty("Octopus.Action.IISWebSite.WebApplication.ApplicationPoolIdentityType", "ApplicationPoolIdentity") + .WithProperty("Octopus.Action.EnabledFeatures", "Octopus.Features.IISWebSite,Octopus.Features.JsonConfigurationVariables") + .WithProperty("Octopus.Action.Package.FeedId", "My External Feed") + .WithProperty("Octopus.Action.Package.DownloadOnTentacle", "True") + .WithProperty("Octopus.Action.IISWebSite.WebRootType", "packageRoot") + .WithProperty("Octopus.Action.IISWebSite.StartApplicationPool", "True") + .WithProperty("Octopus.Action.IISWebSite.StartWebSite", "True") + .WithProperty("Octopus.Action.Package.PackageId", "OctoFX.Web") + .WithProperty("Octopus.Action.IISWebSite.WebSiteName", "#{Domain}") + .WithProperty("Octopus.Action.IISWebSite.ApplicationPoolName", "#{Domain}") + .WithProperty("Octopus.Action.Package.JsonConfigurationVariablesEnabled", "True") + .WithProperty("Octopus.Action.Package.JsonConfigurationVariablesTargets", "appsettings.json") + ); - void ExecuteTest( - DeploymentAction action, - [CallerMemberName] - string? testName = null - ) - => ExecuteTest( - new VcsRunbook("My Runbook"), - new RunbookProcess(ProjectId, SpaceId) + void ExecuteTest( + DeploymentAction action, + [CallerMemberName] + string? testName = null + ) + => ExecuteTest( + new VcsRunbook("My Runbook"), + new RunbookProcess(ProjectId, SpaceId) + { + Steps = { - Steps = + new DeploymentStep(action.Name) { - new DeploymentStep(action.Name) - { - Actions = { action } - } + Actions = { action } } - }, - testName); + } + }, + testName); - void ExecuteTest( - VcsRunbook runbook, - RunbookProcess process, - [CallerMemberName] - string? testName = null - ) - { - var model = new VcsRunbookPersistenceModel(runbook) { Process = process }; - var ocl = Serialize(model); - this.Assent(ocl, testName: testName); + void ExecuteTest( + VcsRunbook runbook, + RunbookProcess process, + [CallerMemberName] + string? testName = null + ) + { + var model = new VcsRunbookPersistenceModel(runbook) { Process = process }; + var ocl = Serialize(model); + this.Assent(ocl, testName: testName); - var result = Deserialize(ocl); - result.Should() - .BeEquivalentTo( - model, - config => config.IncludingAllDeclaredProperties() - // v5 of Fluent assertions should provide us the property info directly - .Excluding(i => ExcludePropertyFromAssertion(i.SelectedMemberInfo.DeclaringType.GetProperty(i.SelectedMemberInfo.Name)!) - ) - ); - } + var result = Deserialize(ocl); + result.Should() + .BeEquivalentTo( + model, + config => config.IncludingAllDeclaredProperties() + // v5 of Fluent assertions should provide us the property info directly + .Excluding(i => ExcludePropertyFromAssertion(i.SelectedMemberInfo.DeclaringType.GetProperty(i.SelectedMemberInfo.Name)!) + ) + ); + } - protected bool ExcludePropertyFromAssertion(PropertyInfo info) - { - if (info.DeclaringType == typeof(RunbookProcess)) - return !VcsRunbookPersistenceModelOclConverter.RunbookProcessOclConverter.ShouldSerialize(info); - if (info.DeclaringType == typeof(DeploymentStep)) - return !DeploymentStepOclConverter.ShouldSerialize(info); - if (info.DeclaringType == typeof(DeploymentAction)) - return !DeploymentActionOclConverter.ShouldSerialize(info); - if (info.DeclaringType == typeof(PackageReference)) - return !PackageReferenceOclConverter.ShouldSerialize(info); - return false; - } + protected bool ExcludePropertyFromAssertion(PropertyInfo info) + { + if (info.DeclaringType == typeof(RunbookProcess)) + return !VcsRunbookPersistenceModelOclConverter.RunbookProcessOclConverter.ShouldSerialize(info); + if (info.DeclaringType == typeof(DeploymentStep)) + return !DeploymentStepOclConverter.ShouldSerialize(info); + if (info.DeclaringType == typeof(DeploymentAction)) + return !DeploymentActionOclConverter.ShouldSerialize(info); + if (info.DeclaringType == typeof(PackageReference)) + return !PackageReferenceOclConverter.ShouldSerialize(info); + return false; } } \ No newline at end of file diff --git a/source/Tests/StringExtensions.cs b/source/Tests/StringExtensions.cs index b277b9f..37056f4 100644 --- a/source/Tests/StringExtensions.cs +++ b/source/Tests/StringExtensions.cs @@ -2,14 +2,13 @@ using System.Collections.Generic; using System.Linq; -namespace Tests +namespace Tests; + +public static class Extensions { - public static class Extensions - { - public static string ToUnixLineEndings(this string str) - => str.Replace("\r", ""); + public static string ToUnixLineEndings(this string str) + => str.Replace("\r", ""); - public static bool None(this IEnumerable items) - => !items.Any(); - } + public static bool None(this IEnumerable items) + => !items.Any(); } \ No newline at end of file diff --git a/source/Tests/ToOclDoc/ToOclDocConverterFixture.cs b/source/Tests/ToOclDoc/ToOclDocConverterFixture.cs index 3a36e78..6170899 100644 --- a/source/Tests/ToOclDoc/ToOclDocConverterFixture.cs +++ b/source/Tests/ToOclDoc/ToOclDocConverterFixture.cs @@ -6,70 +6,68 @@ using NUnit.Framework; using Octopus.Ocl; -namespace Tests.ToOclDoc +namespace Tests.ToOclDoc; + +public class ToOclDocConverterFixture { - public class ToOclDocConverterFixture + [Test] + public void ConverterIsUsedForTheRootDocument() { - [Test] - public void ConverterIsUsedForTheRootDocument() - { - var options = new OclSerializerOptions(); - options.Converters.Add(new FakeConverter()); + var options = new OclSerializerOptions(); + options.Converters.Add(new FakeConverter()); - new OclSerializer(options).ToOclDocument(new FakeType()) - .Should() - .HaveChildrenExactly(new OclAttribute("Fake", null)); - } + new OclSerializer(options).ToOclDocument(new FakeType()) + .Should() + .HaveChildrenExactly(new OclAttribute("Fake", null)); + } - [Test] - public void SerializingCollectionOfObjectsUsesClassNameAsBlockName() + [Test] + public void SerializingCollectionOfObjectsUsesClassNameAsBlockName() + { + var subject = new[] { - var subject = new[] - { - new FakeType(), - new FakeType { Foo = 2 } - }; + new FakeType(), + new FakeType { Foo = 2 } + }; - new OclSerializer().ToOclDocument(subject) - .Should() - .HaveChildrenExactly( + new OclSerializer().ToOclDocument(subject) + .Should() + .HaveChildrenExactly( + new OclBlock("fake_type", Array.Empty(), new[] { new OclAttribute("foo", 1) }), + new OclBlock("fake_type", Array.Empty(), new[] { new OclAttribute("foo", 2) }) + ); + } + + [Test] + public void DeserializingCollectionOfObjectsWithClassNamesAsBlockNames() + { + var result = new OclSerializer().Deserialize>( + new OclDocument( + new[] + { new OclBlock("fake_type", Array.Empty(), new[] { new OclAttribute("foo", 1) }), new OclBlock("fake_type", Array.Empty(), new[] { new OclAttribute("foo", 2) }) - ); - } + })); - [Test] - public void DeserializingCollectionOfObjectsWithClassNamesAsBlockNames() - { - var result = new OclSerializer().Deserialize>( - new OclDocument( - new[] - { - new OclBlock("fake_type", Array.Empty(), new[] { new OclAttribute("foo", 1) }), - new OclBlock("fake_type", Array.Empty(), new[] { new OclAttribute("foo", 2) }) - })); - - result.Count().Should().Be(2); - } + result.Count().Should().Be(2); + } - class FakeType - { - public int Foo { get; set; } = 1; - } + class FakeType + { + public int Foo { get; set; } = 1; + } - class FakeConverter : IOclConverter - { - public bool CanConvert(Type type) - => type == typeof(FakeType); + class FakeConverter : IOclConverter + { + public bool CanConvert(Type type) + => type == typeof(FakeType); - public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) - => throw new NotImplementedException(); + public IEnumerable ToElements(OclConversionContext context, PropertyInfo? propertyInfo, object value) + => throw new NotImplementedException(); - public OclDocument ToDocument(OclConversionContext context, object obj) - => new OclDocument(new[] { new OclAttribute("Fake", null) }); + public OclDocument ToDocument(OclConversionContext context, object obj) => new(new[] { new OclAttribute("Fake", null) }); - public object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) - => throw new NotImplementedException(); - } + public object? FromElement(OclConversionContext context, Type type, IOclElement element, object? currentValue) + => throw new NotImplementedException(); } } \ No newline at end of file diff --git a/source/Tests/ToOclDoc/ToOclDocDefaultBehaviourFixture.cs b/source/Tests/ToOclDoc/ToOclDocDefaultBehaviourFixture.cs index 2619bb7..c44cd97 100644 --- a/source/Tests/ToOclDoc/ToOclDocDefaultBehaviourFixture.cs +++ b/source/Tests/ToOclDoc/ToOclDocDefaultBehaviourFixture.cs @@ -4,70 +4,69 @@ using NUnit.Framework; using Octopus.Ocl; -namespace Tests.ToOclDoc +namespace Tests.ToOclDoc; + +public class ToOclDocDefaultBehaviourFixture { - public class ToOclDocDefaultBehaviourFixture + [Test] + public void Null() { - [Test] - public void Null() - { - new OclSerializer().ToOclDocument(null) - .Should() - .Be(new OclDocument()); - } + new OclSerializer().ToOclDocument(null) + .Should() + .Be(new OclDocument()); + } - [Test] - public void SimpleObject() - { - new OclSerializer().ToOclDocument(new { MyProp = "MyValue" }) - .Should() - .HaveChildrenExactly( - new OclAttribute("my_prop", "MyValue") - ); - } + [Test] + public void SimpleObject() + { + new OclSerializer().ToOclDocument(new { MyProp = "MyValue" }) + .Should() + .HaveChildrenExactly( + new OclAttribute("my_prop", "MyValue") + ); + } - [Test] - public void ListOfComplexTypesProperty() + [Test] + public void ListOfComplexTypesProperty() + { + var data = new { - var data = new - { - Cars = new List - { new Car(), new Car() } - }; + Cars = new List + { new(), new() } + }; - var result = new OclSerializer().ToOclDocument(data); - result.Should() - .HaveChildrenExactly( - new OclBlock("car") - { - new OclAttribute("doors", 2) - }, - new OclBlock("car") - { - new OclAttribute("doors", 2) - } - ); - } + var result = new OclSerializer().ToOclDocument(data); + result.Should() + .HaveChildrenExactly( + new OclBlock("car") + { + new OclAttribute("doors", 2) + }, + new OclBlock("car") + { + new OclAttribute("doors", 2) + } + ); + } - [Test] - public void Enum() + [Test] + public void Enum() + { + var data = new { - var data = new - { - MyProp = BindingFlags.Static - }; + MyProp = BindingFlags.Static + }; - var result = new OclSerializer().ToOclDocument(data); + var result = new OclSerializer().ToOclDocument(data); - result.Should() - .HaveChildrenExactly( - new OclAttribute("my_prop", "Static") - ); - } + result.Should() + .HaveChildrenExactly( + new OclAttribute("my_prop", "Static") + ); + } - class Car - { - public int Doors { get; } = 2; - } + class Car + { + public int Doors { get; } = 2; } } \ No newline at end of file diff --git a/source/Tests/ToOclDoc/ToOclDocNamingFixture.cs b/source/Tests/ToOclDoc/ToOclDocNamingFixture.cs index c4f6a8b..3ad7015 100644 --- a/source/Tests/ToOclDoc/ToOclDocNamingFixture.cs +++ b/source/Tests/ToOclDoc/ToOclDocNamingFixture.cs @@ -5,62 +5,61 @@ using Octopus.Ocl; using Octopus.Ocl.Converters; -namespace Tests.ToOclDoc +namespace Tests.ToOclDoc; + +public class ToOclDocNamingFixture { - public class ToOclDocNamingFixture + [Test] + public void TheDefaultNameIsThePropertyName() { - [Test] - public void TheDefaultNameIsThePropertyName() - { - var obj = new { Sample = "My Value" }; - new OclSerializer().ToOclDocument(obj) - .Should() - .Be( - new OclDocument - { - new OclAttribute("sample", "My Value") - } - ); - } + var obj = new { Sample = "My Value" }; + new OclSerializer().ToOclDocument(obj) + .Should() + .Be( + new OclDocument + { + new OclAttribute("sample", "My Value") + } + ); + } - [Test] - public void BlockNamesCanBeDerivedFromTheBlocksTypeOrData() + [Test] + public void BlockNamesCanBeDerivedFromTheBlocksTypeOrData() + { + var options = new OclSerializerOptions(); + options.Converters.Add(new DefaultBlockNameFromNamePropertyConverter()); + var obj = new { - var options = new OclSerializerOptions(); - options.Converters.Add(new DefaultBlockNameFromNamePropertyConverter()); - var obj = new + Sample = new SampleWithANameProperty { - Sample = new SampleWithANameProperty + Name = "The Name" + } + }; + + new OclSerializer(options).ToOclDocument(obj) + .Should() + .Be( + new OclDocument { - Name = "The Name" + new OclBlock("the_name") } - }; - - new OclSerializer(options).ToOclDocument(obj) - .Should() - .Be( - new OclDocument - { - new OclBlock("the_name") - } - ); - } + ); + } - class SampleWithANameProperty - { - public string? Name { get; set; } - } + class SampleWithANameProperty + { + public string? Name { get; set; } + } - class DefaultBlockNameFromNamePropertyConverter : DefaultBlockOclConverter - { - public override bool CanConvert(Type type) - => type == typeof(SampleWithANameProperty); + class DefaultBlockNameFromNamePropertyConverter : DefaultBlockOclConverter + { + public override bool CanConvert(Type type) + => type == typeof(SampleWithANameProperty); - protected override string GetName(OclConversionContext context, PropertyInfo? propertyInfo, object obj) - => context.Namer.FormatName(((dynamic)obj).Name); + protected override string GetName(OclConversionContext context, PropertyInfo? propertyInfo, object obj) + => context.Namer.FormatName(((dynamic)obj).Name); - protected override IEnumerable GetElements(object obj, OclConversionContext context) - => new IOclElement[0]; - } + protected override IEnumerable GetElements(object obj, OclConversionContext context) + => new IOclElement[0]; } } \ No newline at end of file diff --git a/source/Tests/ToString/OclWriterFixture.cs b/source/Tests/ToString/OclWriterFixture.cs index 828890f..e9d5f70 100644 --- a/source/Tests/ToString/OclWriterFixture.cs +++ b/source/Tests/ToString/OclWriterFixture.cs @@ -6,274 +6,273 @@ using NUnit.Framework; using Octopus.Ocl; -namespace Tests.ToString +namespace Tests.ToString; + +[Parallelizable(ParallelScope.All)] +public class OclWriterFixture { - [Parallelizable(ParallelScope.All)] - public class OclWriterFixture + static IEnumerable WriteAttributeDataSource() { - static IEnumerable WriteAttributeDataSource() - { - TestCaseData CreateCase(string name, object? value, string expected) - => new TestCaseData(value, expected) { TestName = "WriteAttribute value: " + name }; - - yield return CreateCase("null", null, "null"); - yield return CreateCase("bool", false, "false"); - yield return CreateCase("char", '5', "\"5\""); - yield return CreateCase("byte", (byte)5, "5"); - yield return CreateCase("short", (short)-5, "-5"); - yield return CreateCase("ushort", (ushort)5, "5"); - yield return CreateCase("uint", 5u, "5"); - yield return CreateCase("int", 5, "5"); - - yield return CreateCase("negative", -5, "-5"); - yield return CreateCase("long", -4398257458902378590L, "-4398257458902378590"); - yield return CreateCase("ulong", 4398257458902437590uL, "4398257458902437590"); - yield return CreateCase("float", 3243242.43432f, "3243242.5"); - yield return CreateCase("double", 3243242.43432d, "3243242.43432"); - yield return CreateCase("double small exponential", 3243242e+3, "3243242000"); - yield return CreateCase("double large exponential", 3243242e+34, "3.243242E+40"); - yield return CreateCase("decimal", 3243242.43432m, "3243242.43432"); - yield return CreateCase("string", "MyValue", @"""MyValue"""); - yield return CreateCase("double quotes", @"a""b", @"""a\""b"""); - yield return CreateCase("string array", new[] { "B", "C" }, @"[""B"", ""C""]"); - yield return CreateCase("Int array", new[] { 4, 3, 4 }, @"[4, 3, 4]"); - yield return CreateCase("single line string slashes are escaped", new OclStringLiteral(@"a\c\r\nb\t", OclStringLiteralFormat.SingleLine), @"""a\\c\\r\\nb\\t"""); - yield return CreateCase("single line string tab is escaped", new OclStringLiteral("a\tb", OclStringLiteralFormat.SingleLine), @"""a\tb"""); - yield return CreateCase("single line string newlines are escaped", new OclStringLiteral("a\r\nb", OclStringLiteralFormat.SingleLine), @"""a\r\nb"""); - yield return CreateCase("single line string double quotes are escaped", new OclStringLiteral("a\"b", OclStringLiteralFormat.SingleLine), @"""a\""b"""); - } + TestCaseData CreateCase(string name, object? value, string expected) => new(value, expected) { TestName = "WriteAttribute value: " + name }; + + yield return CreateCase("null", null, "null"); + yield return CreateCase("bool", false, "false"); + yield return CreateCase("char", '5', "\"5\""); + yield return CreateCase("byte", (byte)5, "5"); + yield return CreateCase("short", (short)-5, "-5"); + yield return CreateCase("ushort", (ushort)5, "5"); + yield return CreateCase("uint", 5u, "5"); + yield return CreateCase("int", 5, "5"); + + yield return CreateCase("negative", -5, "-5"); + yield return CreateCase("long", -4398257458902378590L, "-4398257458902378590"); + yield return CreateCase("ulong", 4398257458902437590uL, "4398257458902437590"); + yield return CreateCase("float", 3243242.43432f, "3243242.5"); + yield return CreateCase("double", 3243242.43432d, "3243242.43432"); + yield return CreateCase("double small exponential", 3243242e+3, "3243242000"); + yield return CreateCase("double large exponential", 3243242e+34, "3.243242E+40"); + yield return CreateCase("decimal", 3243242.43432m, "3243242.43432"); + yield return CreateCase("string", "MyValue", @"""MyValue"""); + yield return CreateCase("double quotes", @"a""b", @"""a\""b"""); + yield return CreateCase("string array", new[] { "B", "C" }, @"[""B"", ""C""]"); + yield return CreateCase("Int array", new[] { 4, 3, 4 }, @"[4, 3, 4]"); + yield return CreateCase("single line string slashes are escaped", new OclStringLiteral(@"a\c\r\nb\t", OclStringLiteralFormat.SingleLine), @"""a\\c\\r\\nb\\t"""); + yield return CreateCase("single line string tab is escaped", new OclStringLiteral("a\tb", OclStringLiteralFormat.SingleLine), @"""a\tb"""); + yield return CreateCase("single line string newlines are escaped", new OclStringLiteral("a\r\nb", OclStringLiteralFormat.SingleLine), @"""a\r\nb"""); + yield return CreateCase("single line string double quotes are escaped", new OclStringLiteral("a\"b", OclStringLiteralFormat.SingleLine), @"""a\""b"""); + } - [TestCaseSource(nameof(WriteAttributeDataSource))] - public void WriteAttribute(object? input, string expected) - => Execute(w => w.Write(new OclAttribute("MyAttr", input))) - .Should() - .Be($"MyAttr = {expected}"); + [TestCaseSource(nameof(WriteAttributeDataSource))] + public void WriteAttribute(object? input, string expected) + => Execute(w => w.Write(new OclAttribute("MyAttr", input))) + .Should() + .Be($"MyAttr = {expected}"); - [Test] - public void WriteAttributeInvalidValueThrows() - { - Action action = () => Execute(w => w.Write(new OclAttribute("MyAttr", new Random()))); - action.Should() - .Throw() - .WithMessage("*System.Random*"); - } + [Test] + public void WriteAttributeInvalidValueThrows() + { + Action action = () => Execute(w => w.Write(new OclAttribute("MyAttr", new Random()))); + action.Should() + .Throw() + .WithMessage("*System.Random*"); + } - [Test] - public void WriteAttributeLeadingNumberInName() - => Execute(w => w.Write(new OclAttribute("0MyAttr", 5))) - .Should() - .Be("_0MyAttr = 5"); + [Test] + public void WriteAttributeLeadingNumberInName() + => Execute(w => w.Write(new OclAttribute("0MyAttr", 5))) + .Should() + .Be("_0MyAttr = 5"); - [Test] - public void WriteAttributeSpecialCharactersInName() - => Execute(w => w.Write(new OclAttribute("My0%&2_'\"-Attr", 5))) - .Should() - .Be("My0__2___-Attr = 5"); + [Test] + public void WriteAttributeSpecialCharactersInName() + => Execute(w => w.Write(new OclAttribute("My0%&2_'\"-Attr", 5))) + .Should() + .Be("My0__2___-Attr = 5"); - [Test] - public void WriteDictionaryAttributes() + [Test] + public void WriteDictionaryAttributes() + { + var dict = new Dictionary { - var dict = new Dictionary - { - { "One.One", "1" }, - { "Two Two", 2 }, - { "Three\"Three", null } - }; + { "One.One", "1" }, + { "Two Two", 2 }, + { "Three\"Three", null } + }; - var expected = @"properties = { + var expected = @"properties = { One.One = ""1"" ""Three\""Three"" = null ""Two Two"" = 2 }"; - Execute(w => w.Write(new OclAttribute("properties", dict))) - .Trim() - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(new OclAttribute("properties", dict))) + .Trim() + .Should() + .Be(expected.ToUnixLineEndings()); + } - [Test] - public void Heredoc() + [Test] + public void Heredoc() + { + var literal = new OclStringLiteral(" a\n b", OclStringLiteralFormat.Heredoc) { HeredocTag = "ZZZ" }; + var block = new OclBlock("MyBlock") { - var literal = new OclStringLiteral(" a\n b", OclStringLiteralFormat.Heredoc) { HeredocTag = "ZZZ" }; - var block = new OclBlock("MyBlock") - { - new OclAttribute("MyAttr", literal) - }; + new OclAttribute("MyAttr", literal) + }; - var expected = @"MyBlock { + var expected = @"MyBlock { MyAttr = < w.Write(block)) - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(block)) + .Should() + .Be(expected.ToUnixLineEndings()); + } - [Test] - public void HeredocIndented() + [Test] + public void HeredocIndented() + { + var literal = new OclStringLiteral(" a\n b", OclStringLiteralFormat.IndentedHeredoc); + var block = new OclBlock("MyBlock") { - var literal = new OclStringLiteral(" a\n b", OclStringLiteralFormat.IndentedHeredoc); - var block = new OclBlock("MyBlock") - { - new OclAttribute("MyAttr", literal) - }; + new OclAttribute("MyAttr", literal) + }; - var expected = @"MyBlock { + var expected = @"MyBlock { MyAttr = <<-EOT a b EOT }"; - Execute(w => w.Write(block)) - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(block)) + .Should() + .Be(expected.ToUnixLineEndings()); + } - [Test] - public void MultilineStringsUseHeredocAndTheHeredocIdentifierFromOptions() + [Test] + public void MultilineStringsUseHeredocAndTheHeredocIdentifierFromOptions() + { + var options = new OclSerializerOptions { - var options = new OclSerializerOptions - { - DefaultHeredocTag = "YYY" - }; + DefaultHeredocTag = "YYY" + }; - var expected = @"MyAttr = <<-YYY + var expected = @"MyAttr = <<-YYY a b YYY"; - Execute(w => w.Write(new OclAttribute("MyAttr", "a\nb")), options) - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(new OclAttribute("MyAttr", "a\nb")), options) + .Should() + .Be(expected.ToUnixLineEndings()); + } - [Test] - public void WriteBlockEmpty() - => Execute(w => w.Write(new OclBlock("MyBlock"))) - .Should() - .Be("MyBlock {\n}"); + [Test] + public void WriteBlockEmpty() + => Execute(w => w.Write(new OclBlock("MyBlock"))) + .Should() + .Be("MyBlock {\n}"); - [Test] - public void WriteBlockSpecialCharactersInName() - => Execute(w => w.Write(new OclBlock("My0%&2_'\"-Block"))) - .Should() - .Be("My0__2___-Block {\n}"); + [Test] + public void WriteBlockSpecialCharactersInName() + => Execute(w => w.Write(new OclBlock("My0%&2_'\"-Block"))) + .Should() + .Be("My0__2___-Block {\n}"); - [Test] - public void WriteBlockSingleLabel() - { - var block = new OclBlock("MyBlock"); - block.Labels.Add("MyLabel"); + [Test] + public void WriteBlockSingleLabel() + { + var block = new OclBlock("MyBlock"); + block.Labels.Add("MyLabel"); - Execute(w => w.Write(block)) - .Should() - .Be("MyBlock \"MyLabel\" {\n}"); - } + Execute(w => w.Write(block)) + .Should() + .Be("MyBlock \"MyLabel\" {\n}"); + } - [Test] - public void WriteBlockMultipleLabel() - { - var block = new OclBlock("MyBlock"); - block.Labels.Add("MyLabel"); - block.Labels.Add("OtherLabel"); - block.Labels.Add("LastLabel"); - - Execute(w => w.Write(block)) - .Should() - .Be("MyBlock \"MyLabel\" \"OtherLabel\" \"LastLabel\" {\n}"); - } + [Test] + public void WriteBlockMultipleLabel() + { + var block = new OclBlock("MyBlock"); + block.Labels.Add("MyLabel"); + block.Labels.Add("OtherLabel"); + block.Labels.Add("LastLabel"); + + Execute(w => w.Write(block)) + .Should() + .Be("MyBlock \"MyLabel\" \"OtherLabel\" \"LastLabel\" {\n}"); + } - [Test] - public void WriteBlockDoubleQuotesInLabel() - { - var block = new OclBlock("MyBlock"); - block.Labels.Add("My\"Label"); + [Test] + public void WriteBlockDoubleQuotesInLabel() + { + var block = new OclBlock("MyBlock"); + block.Labels.Add("My\"Label"); - Execute(w => w.Write(block)) - .Should() - .Be("MyBlock \"My\\\"Label\" {\n}"); - } + Execute(w => w.Write(block)) + .Should() + .Be("MyBlock \"My\\\"Label\" {\n}"); + } - [Test] - public void WriteBlockSingleChildBlock() + [Test] + public void WriteBlockSingleChildBlock() + { + var block = new OclBlock("MyBlock") { - var block = new OclBlock("MyBlock") - { - new OclBlock("Child") - }; + new OclBlock("Child") + }; - var expected = @"MyBlock { + var expected = @"MyBlock { Child { } }"; - Execute(w => w.Write(block)) - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(block)) + .Should() + .Be(expected.ToUnixLineEndings()); + } - [Test] - public void WriteBlockSingleChildAttribute() + [Test] + public void WriteBlockSingleChildAttribute() + { + var block = new OclBlock("MyBlock") { - var block = new OclBlock("MyBlock") - { - new OclAttribute("Child", 5) - }; + new OclAttribute("Child", 5) + }; - var expected = @"MyBlock { + var expected = @"MyBlock { Child = 5 }"; - Execute(w => w.Write(block)) - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(block)) + .Should() + .Be(expected.ToUnixLineEndings()); + } - [Test] - public void IndentOptionsAreUsed() + [Test] + public void IndentOptionsAreUsed() + { + var options = new OclSerializerOptions { - var options = new OclSerializerOptions - { - IndentChar = '+', - IndentDepth = 5 - }; + IndentChar = '+', + IndentDepth = 5 + }; - var block = new OclBlock("MyBlock") - { - new OclAttribute("Child", 5) - }; + var block = new OclBlock("MyBlock") + { + new OclAttribute("Child", 5) + }; - var expected = @"MyBlock { + var expected = @"MyBlock { +++++Child = 5 }"; - Execute(w => w.Write(block), options) - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(block), options) + .Should() + .Be(expected.ToUnixLineEndings()); + } - [Test] - public void WriteBlockMixedAttributesAndBlocks() + [Test] + public void WriteBlockMixedAttributesAndBlocks() + { + var block = new OclBlock("MyBlock") { - var block = new OclBlock("MyBlock") + new OclAttribute("First", 1), + new OclAttribute("Second", 2), + new OclBlock("Third") { - new OclAttribute("First", 1), - new OclAttribute("Second", 2), - new OclBlock("Third") - { - new OclAttribute("ThirdChild", 3) - }, - new OclBlock("Fourth"), - new OclAttribute("Last", 9) - }; - - var expected = @"MyBlock { + new OclAttribute("ThirdChild", 3) + }, + new OclBlock("Fourth"), + new OclAttribute("Last", 9) + }; + + var expected = @"MyBlock { First = 1 Second = 2 @@ -287,25 +286,25 @@ public void WriteBlockMixedAttributesAndBlocks() Last = 9 }"; - Execute(w => w.Write(block)) - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(block)) + .Should() + .Be(expected.ToUnixLineEndings()); + } - [Test] - public void CollectionAttributeFollowedByEndOfBlock() + [Test] + public void CollectionAttributeFollowedByEndOfBlock() + { + var block = new OclBlock("OuterBlock") { - var block = new OclBlock("OuterBlock") + new OclBlock("InnerBlock") { - new OclBlock("InnerBlock") - { - new OclAttribute("MapAttribute", - new Dictionary - { { "alpha", 1 }, { "bravo", 2 } }) - } - }; + new OclAttribute("MapAttribute", + new Dictionary + { { "alpha", 1 }, { "bravo", 2 } }) + } + }; - const string expected = @"OuterBlock { + const string expected = @"OuterBlock { InnerBlock { MapAttribute = { @@ -315,26 +314,26 @@ public void CollectionAttributeFollowedByEndOfBlock() } }"; - Execute(w => w.Write(block)) - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(block)) + .Should() + .Be(expected.ToUnixLineEndings()); + } - [Test] - public void CollectionAttributeFollowedByAttribute() + [Test] + public void CollectionAttributeFollowedByAttribute() + { + var block = new OclBlock("OuterBlock") { - var block = new OclBlock("OuterBlock") + new OclBlock("InnerBlock") { - new OclBlock("InnerBlock") - { - new OclAttribute("MapAttribute", - new Dictionary - { { "alpha", 1 }, { "bravo", 2 } }), - new OclAttribute("StringAttribute", "Value") - } - }; + new OclAttribute("MapAttribute", + new Dictionary + { { "alpha", 1 }, { "bravo", 2 } }), + new OclAttribute("StringAttribute", "Value") + } + }; - const string expected = @"OuterBlock { + const string expected = @"OuterBlock { InnerBlock { MapAttribute = { @@ -345,22 +344,21 @@ public void CollectionAttributeFollowedByAttribute() } }"; - Execute(w => w.Write(block)) - .Should() - .Be(expected.ToUnixLineEndings()); - } + Execute(w => w.Write(block)) + .Should() + .Be(expected.ToUnixLineEndings()); + } - string Execute(Action when, OclSerializerOptions? options = null) + string Execute(Action when, OclSerializerOptions? options = null) + { + var sb = new StringBuilder(); + using (var sw = new StringWriter(sb)) + using (var writer = new OclWriter(sw, options)) { - var sb = new StringBuilder(); - using (var sw = new StringWriter(sb)) - using (var writer = new OclWriter(sw, options)) - { - sw.NewLine = "\n"; - when(writer); - } - - return sb.ToString(); + sw.NewLine = "\n"; + when(writer); } + + return sb.ToString(); } } \ No newline at end of file