From 1c0dbc22b53860fe95c9d9c3595063d0be9bf8ac Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 17 Jun 2018 16:27:58 +0200 Subject: [PATCH 01/97] generators: Ignore Rider settings files --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index dea37c33e2..cf03e5e831 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,7 @@ packages/ obj/ bin/ *.userprefs -.dotnet/ +*.DotSettings.user .dotnet/ .vs/ From d510410b7fc2d182fbe8364dc4401c7c5302f800 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 17 Jun 2018 16:35:19 +0200 Subject: [PATCH 02/97] generators: Refactor additional namespaces --- generators/Exercises/Alphametics.cs | 2 +- generators/Exercises/BinarySearchTree.cs | 2 +- generators/Exercises/Bowling.cs | 5 +---- generators/Exercises/CircularBuffer.cs | 3 +-- generators/Exercises/ComplexNumbers.cs | 5 +---- generators/Exercises/Dominoes.cs | 2 +- generators/Exercises/Etl.cs | 2 +- generators/Exercises/Gigasecond.cs | 2 +- generators/Exercises/GoCounting.cs | 2 +- generators/Exercises/Grep.cs | 12 +++++------- generators/Exercises/ListOps.cs | 2 +- generators/Exercises/Meetup.cs | 2 +- generators/Exercises/Minesweeper.cs | 2 +- generators/Exercises/NucleotideCount.cs | 2 +- generators/Exercises/OcrNumbers.cs | 2 +- generators/Exercises/React.cs | 2 +- generators/Exercises/SaddlePoints.cs | 8 +------- generators/Exercises/SimpleCipher.cs | 2 +- generators/Exercises/Sublist.cs | 2 +- generators/Exercises/Tournament.cs | 15 ++++++--------- generators/Exercises/WordCount.cs | 2 +- generators/Exercises/WordSearch.cs | 2 +- generators/GeneratorExercise.cs | 7 ++----- 23 files changed, 33 insertions(+), 54 deletions(-) diff --git a/generators/Exercises/Alphametics.cs b/generators/Exercises/Alphametics.cs index 0b4eaf5d9f..f8f9a67561 100644 --- a/generators/Exercises/Alphametics.cs +++ b/generators/Exercises/Alphametics.cs @@ -27,6 +27,6 @@ private static dynamic ConvertExpected(CanonicalDataCase canonicalDataCase) return expected.ToDictionary(kv => kv.Key[0], kv => int.Parse(kv.Value.ToString())); } - protected override HashSet AddAdditionalNamespaces() => new HashSet { typeof(Dictionary).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Dictionary).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index dc668caed8..583353453e 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -29,7 +29,7 @@ public IEnumerable TestAsserts(string traverse = "") public class BinarySearchTree : GeneratorExercise { - protected override HashSet AddAdditionalNamespaces() => new HashSet() { typeof(System.Linq.IQueryable).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(System.Linq.IQueryable).Namespace }; private StringBuilder testFactCodeLines; void addCodeLine(string line) => testFactCodeLines.Append(line + "\r\n"); diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index 2f561f75c7..d48e5ed2a6 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -112,9 +112,6 @@ public void DoRoll(ICollection rolls, BowlingGame sut) }" }; } - protected override HashSet AddAdditionalNamespaces() - { - return new HashSet { typeof(ICollection<>).Namespace }; - } + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(ICollection<>).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/CircularBuffer.cs index 4049e49a7f..c95824cfbf 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/CircularBuffer.cs @@ -68,7 +68,6 @@ private static string RenderOverwriteOperation(dynamic operation) private static string RenderClearOperation(dynamic operation) => "buffer.Clear();"; - protected override HashSet AddAdditionalNamespaces() - => new HashSet { typeof(InvalidOperationException).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(InvalidOperationException).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 1be6cbe87a..5d1c307126 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -50,10 +50,7 @@ private static string RenderComplexNumberAssert(TestMethodBody testMethodBody) return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); } - protected override HashSet AddAdditionalNamespaces() => new HashSet - { - typeof(Math).Namespace - }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Math).Namespace }; private static object ConvertToType(dynamic rawValue) { diff --git a/generators/Exercises/Dominoes.cs b/generators/Exercises/Dominoes.cs index 2bc4625b67..7599cea219 100644 --- a/generators/Exercises/Dominoes.cs +++ b/generators/Exercises/Dominoes.cs @@ -18,7 +18,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } - protected override HashSet AddAdditionalNamespaces() => new HashSet() { typeof(Tuple).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Tuple).Namespace }; private UnescapedValue ConvertInput(dynamic input) { diff --git a/generators/Exercises/Etl.cs b/generators/Exercises/Etl.cs index 5e81377877..9f9ab35609 100644 --- a/generators/Exercises/Etl.cs +++ b/generators/Exercises/Etl.cs @@ -28,6 +28,6 @@ private static IDictionary ConvertInput(IDictionary int.Parse(kv.Key), kv => (string[])kv.Value) }; - protected override HashSet AddAdditionalNamespaces() => new HashSet { typeof(Dictionary).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Dictionary).Namespace }; } } diff --git a/generators/Exercises/Gigasecond.cs b/generators/Exercises/Gigasecond.cs index ca61e5d75b..b11b254a1a 100644 --- a/generators/Exercises/Gigasecond.cs +++ b/generators/Exercises/Gigasecond.cs @@ -18,7 +18,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } - protected override HashSet AddAdditionalNamespaces() => new HashSet { typeof(DateTime).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(DateTime).Namespace }; private static string FormatDateTime(DateTime dateTime) { diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index f797faf073..22ca1955f1 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -86,7 +86,7 @@ private string FormatOwner(dynamic owner) private string FormatTerritory(dynamic territory) => ValueFormatter.Format((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); - protected override HashSet AddAdditionalNamespaces() => new HashSet + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(ArgumentException).Namespace, typeof(Dictionary).Namespace diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index 6c7b814779..4ecd131af2 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -20,6 +20,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) canonicalDataCase.UseVariableForExpected = true; } } + private static dynamic ConvertExpected(dynamic expected) { var arr = expected as object[]; @@ -38,14 +39,11 @@ protected override TestClass CreateTestClass() return testClass; } - protected override HashSet AddAdditionalNamespaces() + protected override IEnumerable AdditionalNamespaces() => new[] { - return new HashSet - { - typeof(IDisposable).Namespace, - typeof(System.IO.File).Namespace - }; - } + typeof(IDisposable).Namespace, + typeof(System.IO.File).Namespace + }; protected override string[] RenderAdditionalMethods() { diff --git a/generators/Exercises/ListOps.cs b/generators/Exercises/ListOps.cs index 123cccfce6..855a7641e4 100644 --- a/generators/Exercises/ListOps.cs +++ b/generators/Exercises/ListOps.cs @@ -114,7 +114,7 @@ private static dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) return value; } - protected override HashSet AddAdditionalNamespaces() => new HashSet + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Func).Namespace, typeof(List).Namespace diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 76b063a5f5..fa6620a924 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -40,6 +40,6 @@ protected override String RenderTestMethodBodyAssert(TestMethodBody testMethodBo return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); } - protected override HashSet AddAdditionalNamespaces() => new HashSet { typeof(DayOfWeek).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(DayOfWeek).Namespace }; } } diff --git a/generators/Exercises/Minesweeper.cs b/generators/Exercises/Minesweeper.cs index 64ee61e5ce..2f39af4ee4 100644 --- a/generators/Exercises/Minesweeper.cs +++ b/generators/Exercises/Minesweeper.cs @@ -37,6 +37,6 @@ private UnescapedValue ToMultiLineString(IEnumerable input) return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); } - protected override HashSet AddAdditionalNamespaces() => new HashSet { typeof(Array).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Array).Namespace }; } } diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index 398f9b4562..c2b104504c 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -23,7 +23,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) private static dynamic ConvertExpected(dynamic expected) => ((Dictionary)expected).ToDictionary(kv => kv.Key[0], kv => int.Parse($"{kv.Value}")); - protected override HashSet AddAdditionalNamespaces() => new HashSet() { typeof(Dictionary).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Dictionary).Namespace }; protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { diff --git a/generators/Exercises/OcrNumbers.cs b/generators/Exercises/OcrNumbers.cs index 2f6d36ee8f..2f51fe1bec 100644 --- a/generators/Exercises/OcrNumbers.cs +++ b/generators/Exercises/OcrNumbers.cs @@ -33,6 +33,6 @@ private UnescapedValue ToDigitStringRepresentation(string[] input) return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); } - protected override HashSet AddAdditionalNamespaces() => new HashSet { typeof(Array).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Array).Namespace }; } } diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index 1260653eb8..340b34f0f2 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -125,7 +125,7 @@ private static string RenderOperation(dynamic operation) protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) => ""; - protected override HashSet AddAdditionalNamespaces() => new HashSet + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(EventHandler).Namespace, "FakeItEasy" diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index 3c76d335a4..3269fda335 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -30,13 +30,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } - protected override HashSet AddAdditionalNamespaces() - { - return new HashSet - { - typeof(System.String).Namespace - }; - } + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(System.String).Namespace }; private IEnumerable> ToTupleCollection(Array array) { diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index 1f453d0c56..997bdd23e8 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -62,6 +62,6 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo return base.RenderTestMethodBodyAssert(testMethodBody); } - protected override HashSet AddAdditionalNamespaces() => new HashSet { typeof(ArgumentException).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(ArgumentException).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/Sublist.cs b/generators/Exercises/Sublist.cs index 39683c6714..66f8784138 100644 --- a/generators/Exercises/Sublist.cs +++ b/generators/Exercises/Sublist.cs @@ -8,7 +8,7 @@ namespace Generators.Exercises { public class Sublist : GeneratorExercise { - protected override HashSet AddAdditionalNamespaces() => new HashSet() { typeof(IList).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(IList).Namespace }; private UnescapedValue InputValues(int[] list) { diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index a6f49a7e1d..6357230e70 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -21,16 +21,13 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } - protected override HashSet AddAdditionalNamespaces() + protected override IEnumerable AdditionalNamespaces() => new[] { - return new HashSet - { - typeof(Array).Namespace, - typeof(System.String).Namespace, - typeof(System.IO.Stream).Namespace, - typeof(System.Text.UTF8Encoding).Namespace - }; - } + typeof(Array).Namespace, + typeof(System.String).Namespace, + typeof(System.IO.Stream).Namespace, + typeof(System.Text.UTF8Encoding).Namespace + }; protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { diff --git a/generators/Exercises/WordCount.cs b/generators/Exercises/WordCount.cs index 9a992819c0..e9d8cac7a6 100644 --- a/generators/Exercises/WordCount.cs +++ b/generators/Exercises/WordCount.cs @@ -19,6 +19,6 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) private static dynamic ConvertExpected(dynamic expected) => ((Dictionary)expected).ToDictionary(kv => kv.Key, kv => int.Parse(kv.Value.ToString())); - protected override HashSet AddAdditionalNamespaces() => new HashSet { typeof(Dictionary).Namespace }; + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Dictionary).Namespace }; } } diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index 65f5ce1f93..ac8303db4a 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -75,7 +75,7 @@ private string FormatPosition(dynamic position) private string FormatCoordinate(dynamic coordinate) => ValueFormatter.Format((coordinate["column"], coordinate["row"])); - protected override HashSet AddAdditionalNamespaces() => new HashSet + protected override IEnumerable AdditionalNamespaces() => new[] { typeof(ValueTuple).Namespace, typeof(Dictionary>).Namespace diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index 53f17c86d7..8f9c2f6603 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -26,10 +26,7 @@ protected virtual void UpdateCanonicalData(CanonicalData canonicalData) { } - protected virtual HashSet AddAdditionalNamespaces() - { - return new HashSet(); - } + protected virtual IEnumerable AdditionalNamespaces() => Enumerable.Empty(); protected virtual string RenderTestMethodBodyArrange(TestMethodBody testMethodBody) => TemplateRenderer.RenderPartial(testMethodBody.ArrangeTemplateName, testMethodBody.ArrangeTemplateParameters); @@ -52,7 +49,7 @@ private HashSet GetUsingNamespaces() foreach (var canonicalDataCase in _canonicalData.Cases.Where(canonicalDataCase => canonicalDataCase.ExceptionThrown != null)) usingNamespaces.Add(canonicalDataCase.ExceptionThrown.Namespace); - usingNamespaces.UnionWith(AddAdditionalNamespaces()); + usingNamespaces.UnionWith(AdditionalNamespaces()); return usingNamespaces; } From 2ae70ffd101172748addd40722a2bd3ae47e2614 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 17 Jun 2018 16:46:26 +0200 Subject: [PATCH 03/97] exercises: Update to latest canonical data --- exercises/allergies/AllergiesTest.cs | 59 ++- exercises/anagram/AnagramTest.cs | 113 +++++- exercises/isbn-verifier/IsbnVerifierTest.cs | 8 +- exercises/luhn/LuhnTest.cs | 8 +- exercises/poker/PokerTest.cs | 339 +++++++++++++++--- .../scale-generator/ScaleGeneratorTest.cs | 195 +++++++++- exercises/word-search/WordSearchTest.cs | 2 +- generators/Exercises/PascalsTriangle.cs | 4 +- generators/Exercises/Poker.cs | 1 + generators/Exercises/SaddlePoints.cs | 11 +- 10 files changed, 636 insertions(+), 104 deletions(-) diff --git a/exercises/allergies/AllergiesTest.cs b/exercises/allergies/AllergiesTest.cs index 5f40f39dcf..4d46cd3b9b 100644 --- a/exercises/allergies/AllergiesTest.cs +++ b/exercises/allergies/AllergiesTest.cs @@ -40,7 +40,10 @@ public void No_allergies_at_all() public void Allergic_to_just_eggs() { var sut = new Allergies(1); - var expected = new[] { "eggs" }; + var expected = new[] + { + "eggs" + }; Assert.Equal(expected, sut.List()); } @@ -48,7 +51,10 @@ public void Allergic_to_just_eggs() public void Allergic_to_just_peanuts() { var sut = new Allergies(2); - var expected = new[] { "peanuts" }; + var expected = new[] + { + "peanuts" + }; Assert.Equal(expected, sut.List()); } @@ -56,7 +62,10 @@ public void Allergic_to_just_peanuts() public void Allergic_to_just_strawberries() { var sut = new Allergies(8); - var expected = new[] { "strawberries" }; + var expected = new[] + { + "strawberries" + }; Assert.Equal(expected, sut.List()); } @@ -64,7 +73,11 @@ public void Allergic_to_just_strawberries() public void Allergic_to_eggs_and_peanuts() { var sut = new Allergies(3); - var expected = new[] { "eggs", "peanuts" }; + var expected = new[] + { + "eggs", + "peanuts" + }; Assert.Equal(expected, sut.List()); } @@ -72,7 +85,11 @@ public void Allergic_to_eggs_and_peanuts() public void Allergic_to_more_than_eggs_but_not_peanuts() { var sut = new Allergies(5); - var expected = new[] { "eggs", "shellfish" }; + var expected = new[] + { + "eggs", + "shellfish" + }; Assert.Equal(expected, sut.List()); } @@ -80,7 +97,14 @@ public void Allergic_to_more_than_eggs_but_not_peanuts() public void Allergic_to_lots_of_stuff() { var sut = new Allergies(248); - var expected = new[] { "strawberries", "tomatoes", "chocolate", "pollen", "cats" }; + var expected = new[] + { + "strawberries", + "tomatoes", + "chocolate", + "pollen", + "cats" + }; Assert.Equal(expected, sut.List()); } @@ -88,7 +112,17 @@ public void Allergic_to_lots_of_stuff() public void Allergic_to_everything() { var sut = new Allergies(255); - var expected = new[] { "eggs", "peanuts", "shellfish", "strawberries", "tomatoes", "chocolate", "pollen", "cats" }; + var expected = new[] + { + "eggs", + "peanuts", + "shellfish", + "strawberries", + "tomatoes", + "chocolate", + "pollen", + "cats" + }; Assert.Equal(expected, sut.List()); } @@ -96,7 +130,16 @@ public void Allergic_to_everything() public void Ignore_non_allergen_score_parts() { var sut = new Allergies(509); - var expected = new[] { "eggs", "shellfish", "strawberries", "tomatoes", "chocolate", "pollen", "cats" }; + var expected = new[] + { + "eggs", + "shellfish", + "strawberries", + "tomatoes", + "chocolate", + "pollen", + "cats" + }; Assert.Equal(expected, sut.List()); } } \ No newline at end of file diff --git a/exercises/anagram/AnagramTest.cs b/exercises/anagram/AnagramTest.cs index 5b6e4f7b7c..f943df9d6c 100644 --- a/exercises/anagram/AnagramTest.cs +++ b/exercises/anagram/AnagramTest.cs @@ -7,7 +7,13 @@ public class AnagramTest [Fact] public void No_matches() { - var candidates = new[] { "hello", "world", "zombies", "pants" }; + var candidates = new[] + { + "hello", + "world", + "zombies", + "pants" + }; var sut = new Anagram("diaper"); Assert.Empty(sut.Anagrams(candidates)); } @@ -15,16 +21,29 @@ public void No_matches() [Fact(Skip = "Remove to run test")] public void Detects_two_anagrams() { - var candidates = new[] { "stream", "pigeon", "maters" }; + var candidates = new[] + { + "stream", + "pigeon", + "maters" + }; var sut = new Anagram("master"); - var expected = new[] { "stream", "maters" }; + var expected = new[] + { + "stream", + "maters" + }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Does_not_detect_anagram_subsets() { - var candidates = new[] { "dog", "goody" }; + var candidates = new[] + { + "dog", + "goody" + }; var sut = new Anagram("good"); Assert.Empty(sut.Anagrams(candidates)); } @@ -32,25 +51,50 @@ public void Does_not_detect_anagram_subsets() [Fact(Skip = "Remove to run test")] public void Detects_anagram() { - var candidates = new[] { "enlists", "google", "inlets", "banana" }; + var candidates = new[] + { + "enlists", + "google", + "inlets", + "banana" + }; var sut = new Anagram("listen"); - var expected = new[] { "inlets" }; + var expected = new[] + { + "inlets" + }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Detects_three_anagrams() { - var candidates = new[] { "gallery", "ballerina", "regally", "clergy", "largely", "leading" }; + var candidates = new[] + { + "gallery", + "ballerina", + "regally", + "clergy", + "largely", + "leading" + }; var sut = new Anagram("allergy"); - var expected = new[] { "gallery", "regally", "largely" }; + var expected = new[] + { + "gallery", + "regally", + "largely" + }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Does_not_detect_non_anagrams_with_identical_checksum() { - var candidates = new[] { "last" }; + var candidates = new[] + { + "last" + }; var sut = new Anagram("mass"); Assert.Empty(sut.Anagrams(candidates)); } @@ -58,34 +102,61 @@ public void Does_not_detect_non_anagrams_with_identical_checksum() [Fact(Skip = "Remove to run test")] public void Detects_anagrams_case_insensitively() { - var candidates = new[] { "cashregister", "Carthorse", "radishes" }; + var candidates = new[] + { + "cashregister", + "Carthorse", + "radishes" + }; var sut = new Anagram("Orchestra"); - var expected = new[] { "Carthorse" }; + var expected = new[] + { + "Carthorse" + }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Detects_anagrams_using_case_insensitive_subject() { - var candidates = new[] { "cashregister", "carthorse", "radishes" }; + var candidates = new[] + { + "cashregister", + "carthorse", + "radishes" + }; var sut = new Anagram("Orchestra"); - var expected = new[] { "carthorse" }; + var expected = new[] + { + "carthorse" + }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Detects_anagrams_using_case_insensitive_possible_matches() { - var candidates = new[] { "cashregister", "Carthorse", "radishes" }; + var candidates = new[] + { + "cashregister", + "Carthorse", + "radishes" + }; var sut = new Anagram("orchestra"); - var expected = new[] { "Carthorse" }; + var expected = new[] + { + "Carthorse" + }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Does_not_detect_a_anagram_if_the_original_word_is_repeated() { - var candidates = new[] { "go Go GO" }; + var candidates = new[] + { + "go Go GO" + }; var sut = new Anagram("go"); Assert.Empty(sut.Anagrams(candidates)); } @@ -93,7 +164,10 @@ public void Does_not_detect_a_anagram_if_the_original_word_is_repeated() [Fact(Skip = "Remove to run test")] public void Anagrams_must_use_all_letters_exactly_once() { - var candidates = new[] { "patter" }; + var candidates = new[] + { + "patter" + }; var sut = new Anagram("tapper"); Assert.Empty(sut.Anagrams(candidates)); } @@ -101,7 +175,10 @@ public void Anagrams_must_use_all_letters_exactly_once() [Fact(Skip = "Remove to run test")] public void Capital_word_is_not_own_anagram() { - var candidates = new[] { "Banana" }; + var candidates = new[] + { + "Banana" + }; var sut = new Anagram("BANANA"); Assert.Empty(sut.Anagrams(candidates)); } diff --git a/exercises/isbn-verifier/IsbnVerifierTest.cs b/exercises/isbn-verifier/IsbnVerifierTest.cs index 2d5999111c..39c112fc46 100644 --- a/exercises/isbn-verifier/IsbnVerifierTest.cs +++ b/exercises/isbn-verifier/IsbnVerifierTest.cs @@ -1,4 +1,4 @@ -// This file was auto-generated based on version 2.4.0 of the canonical data. +// This file was auto-generated based on version 2.5.0 of the canonical data. using Xunit; @@ -93,4 +93,10 @@ public void Input_is_9_characters() { Assert.False(IsbnVerifier.IsValid("134456729")); } + + [Fact(Skip = "Remove to run test")] + public void Invalid_characters_are_not_ignored() + { + Assert.False(IsbnVerifier.IsValid("3132P34035")); + } } \ No newline at end of file diff --git a/exercises/luhn/LuhnTest.cs b/exercises/luhn/LuhnTest.cs index cd5a0215c8..49035f01b7 100644 --- a/exercises/luhn/LuhnTest.cs +++ b/exercises/luhn/LuhnTest.cs @@ -1,4 +1,4 @@ -// This file was auto-generated based on version 1.1.0 of the canonical data. +// This file was auto-generated based on version 1.2.0 of the canonical data. using Xunit; @@ -81,4 +81,10 @@ public void Input_digit_9_is_correctly_converted_to_output_digit_9() { Assert.True(Luhn.IsValid("091")); } + + [Fact(Skip = "Remove to run test")] + public void Strings_with_non_digits_is_invalid() + { + Assert.False(Luhn.IsValid(":9")); + } } \ No newline at end of file diff --git a/exercises/poker/PokerTest.cs b/exercises/poker/PokerTest.cs index 3f4001855c..8428d26757 100644 --- a/exercises/poker/PokerTest.cs +++ b/exercises/poker/PokerTest.cs @@ -7,224 +7,451 @@ public class PokerTest [Fact] public void Single_hand_always_wins() { - var actual = Poker.BestHands(new[] { "4S 5S 7H 8D JC" }); - var expected = new[] { "4S 5S 7H 8D JC" }; + var hands = new[] + { + "4S 5S 7H 8D JC" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "4S 5S 7H 8D JC" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Highest_card_out_of_all_hands_wins() { - var actual = Poker.BestHands(new[] { "4D 5S 6S 8D 3C", "2S 4C 7S 9H 10H", "3S 4S 5D 6H JH" }); - var expected = new[] { "3S 4S 5D 6H JH" }; + var hands = new[] + { + "4D 5S 6S 8D 3C", + "2S 4C 7S 9H 10H", + "3S 4S 5D 6H JH" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "3S 4S 5D 6H JH" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void A_tie_has_multiple_winners() { - var actual = Poker.BestHands(new[] { "4D 5S 6S 8D 3C", "2S 4C 7S 9H 10H", "3S 4S 5D 6H JH", "3H 4H 5C 6C JD" }); - var expected = new[] { "3S 4S 5D 6H JH", "3H 4H 5C 6C JD" }; + var hands = new[] + { + "4D 5S 6S 8D 3C", + "2S 4C 7S 9H 10H", + "3S 4S 5D 6H JH", + "3H 4H 5C 6C JD" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "3S 4S 5D 6H JH", + "3H 4H 5C 6C JD" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Multiple_hands_with_the_same_high_cards_tie_compares_next_highest_ranked_down_to_last_card() { - var actual = Poker.BestHands(new[] { "3S 5H 6S 8D 7H", "2S 5D 6D 8C 7S" }); - var expected = new[] { "3S 5H 6S 8D 7H" }; + var hands = new[] + { + "3S 5H 6S 8D 7H", + "2S 5D 6D 8C 7S" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "3S 5H 6S 8D 7H" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void One_pair_beats_high_card() { - var actual = Poker.BestHands(new[] { "4S 5H 6C 8D KH", "2S 4H 6S 4D JH" }); - var expected = new[] { "2S 4H 6S 4D JH" }; + var hands = new[] + { + "4S 5H 6C 8D KH", + "2S 4H 6S 4D JH" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "2S 4H 6S 4D JH" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Highest_pair_wins() { - var actual = Poker.BestHands(new[] { "4S 2H 6S 2D JH", "2S 4H 6C 4D JD" }); - var expected = new[] { "2S 4H 6C 4D JD" }; + var hands = new[] + { + "4S 2H 6S 2D JH", + "2S 4H 6C 4D JD" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "2S 4H 6C 4D JD" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Two_pairs_beats_one_pair() { - var actual = Poker.BestHands(new[] { "2S 8H 6S 8D JH", "4S 5H 4C 8C 5C" }); - var expected = new[] { "4S 5H 4C 8C 5C" }; + var hands = new[] + { + "2S 8H 6S 8D JH", + "4S 5H 4C 8C 5C" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "4S 5H 4C 8C 5C" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_two_pairs_highest_ranked_pair_wins() { - var actual = Poker.BestHands(new[] { "2S 8H 2D 8D 3H", "4S 5H 4C 8S 5D" }); - var expected = new[] { "2S 8H 2D 8D 3H" }; + var hands = new[] + { + "2S 8H 2D 8D 3H", + "4S 5H 4C 8S 5D" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "2S 8H 2D 8D 3H" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_two_pairs_with_the_same_highest_ranked_pair_tie_goes_to_low_pair() { - var actual = Poker.BestHands(new[] { "2S QS 2C QD JH", "JD QH JS 8D QC" }); - var expected = new[] { "JD QH JS 8D QC" }; + var hands = new[] + { + "2S QS 2C QD JH", + "JD QH JS 8D QC" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "JD QH JS 8D QC" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_two_identically_ranked_pairs_tie_goes_to_remaining_card_kicker_() { - var actual = Poker.BestHands(new[] { "JD QH JS 8D QC", "JS QS JC 2D QD" }); - var expected = new[] { "JD QH JS 8D QC" }; + var hands = new[] + { + "JD QH JS 8D QC", + "JS QS JC 2D QD" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "JD QH JS 8D QC" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Three_of_a_kind_beats_two_pair() { - var actual = Poker.BestHands(new[] { "2S 8H 2H 8D JH", "4S 5H 4C 8S 4H" }); - var expected = new[] { "4S 5H 4C 8S 4H" }; + var hands = new[] + { + "2S 8H 2H 8D JH", + "4S 5H 4C 8S 4H" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "4S 5H 4C 8S 4H" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_three_of_a_kind_tie_goes_to_highest_ranked_triplet() { - var actual = Poker.BestHands(new[] { "2S 2H 2C 8D JH", "4S AH AS 8C AD" }); - var expected = new[] { "4S AH AS 8C AD" }; + var hands = new[] + { + "2S 2H 2C 8D JH", + "4S AH AS 8C AD" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "4S AH AS 8C AD" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void With_multiple_decks_two_players_can_have_same_three_of_a_kind_ties_go_to_highest_remaining_cards() { - var actual = Poker.BestHands(new[] { "4S AH AS 7C AD", "4S AH AS 8C AD" }); - var expected = new[] { "4S AH AS 8C AD" }; + var hands = new[] + { + "4S AH AS 7C AD", + "4S AH AS 8C AD" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "4S AH AS 8C AD" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void A_straight_beats_three_of_a_kind() { - var actual = Poker.BestHands(new[] { "4S 5H 4C 8D 4H", "3S 4D 2S 6D 5C" }); - var expected = new[] { "3S 4D 2S 6D 5C" }; + var hands = new[] + { + "4S 5H 4C 8D 4H", + "3S 4D 2S 6D 5C" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "3S 4D 2S 6D 5C" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Aces_can_end_a_straight_10_j_q_k_a_() { - var actual = Poker.BestHands(new[] { "4S 5H 4C 8D 4H", "10D JH QS KD AC" }); - var expected = new[] { "10D JH QS KD AC" }; + var hands = new[] + { + "4S 5H 4C 8D 4H", + "10D JH QS KD AC" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "10D JH QS KD AC" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Aces_can_start_a_straight_a_2_3_4_5_() { - var actual = Poker.BestHands(new[] { "4S 5H 4C 8D 4H", "4D AH 3S 2D 5C" }); - var expected = new[] { "4D AH 3S 2D 5C" }; + var hands = new[] + { + "4S 5H 4C 8D 4H", + "4D AH 3S 2D 5C" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "4D AH 3S 2D 5C" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_with_a_straight_tie_goes_to_highest_ranked_card() { - var actual = Poker.BestHands(new[] { "4S 6C 7S 8D 5H", "5S 7H 8S 9D 6H" }); - var expected = new[] { "5S 7H 8S 9D 6H" }; + var hands = new[] + { + "4S 6C 7S 8D 5H", + "5S 7H 8S 9D 6H" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "5S 7H 8S 9D 6H" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Even_though_an_ace_is_usually_high_a_5_high_straight_is_the_lowest_scoring_straight() { - var actual = Poker.BestHands(new[] { "2H 3C 4D 5D 6H", "4S AH 3S 2D 5H" }); - var expected = new[] { "2H 3C 4D 5D 6H" }; + var hands = new[] + { + "2H 3C 4D 5D 6H", + "4S AH 3S 2D 5H" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "2H 3C 4D 5D 6H" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Flush_beats_a_straight() { - var actual = Poker.BestHands(new[] { "4C 6H 7D 8D 5H", "2S 4S 5S 6S 7S" }); - var expected = new[] { "2S 4S 5S 6S 7S" }; + var hands = new[] + { + "4C 6H 7D 8D 5H", + "2S 4S 5S 6S 7S" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "2S 4S 5S 6S 7S" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_a_flush_tie_goes_to_high_card_down_to_the_last_one_if_necessary() { - var actual = Poker.BestHands(new[] { "4H 7H 8H 9H 6H", "2S 4S 5S 6S 7S" }); - var expected = new[] { "4H 7H 8H 9H 6H" }; + var hands = new[] + { + "4H 7H 8H 9H 6H", + "2S 4S 5S 6S 7S" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "4H 7H 8H 9H 6H" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Full_house_beats_a_flush() { - var actual = Poker.BestHands(new[] { "3H 6H 7H 8H 5H", "4S 5H 4C 5D 4H" }); - var expected = new[] { "4S 5H 4C 5D 4H" }; + var hands = new[] + { + "3H 6H 7H 8H 5H", + "4S 5H 4C 5D 4H" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "4S 5H 4C 5D 4H" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_a_full_house_tie_goes_to_highest_ranked_triplet() { - var actual = Poker.BestHands(new[] { "4H 4S 4D 9S 9D", "5H 5S 5D 8S 8D" }); - var expected = new[] { "5H 5S 5D 8S 8D" }; + var hands = new[] + { + "4H 4S 4D 9S 9D", + "5H 5S 5D 8S 8D" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "5H 5S 5D 8S 8D" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void With_multiple_decks_both_hands_have_a_full_house_with_the_same_triplet_tie_goes_to_the_pair() { - var actual = Poker.BestHands(new[] { "5H 5S 5D 9S 9D", "5H 5S 5D 8S 8D" }); - var expected = new[] { "5H 5S 5D 9S 9D" }; + var hands = new[] + { + "5H 5S 5D 9S 9D", + "5H 5S 5D 8S 8D" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "5H 5S 5D 9S 9D" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Four_of_a_kind_beats_a_full_house() { - var actual = Poker.BestHands(new[] { "4S 5H 4D 5D 4H", "3S 3H 2S 3D 3C" }); - var expected = new[] { "3S 3H 2S 3D 3C" }; + var hands = new[] + { + "4S 5H 4D 5D 4H", + "3S 3H 2S 3D 3C" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "3S 3H 2S 3D 3C" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_four_of_a_kind_tie_goes_to_high_quad() { - var actual = Poker.BestHands(new[] { "2S 2H 2C 8D 2D", "4S 5H 5S 5D 5C" }); - var expected = new[] { "4S 5H 5S 5D 5C" }; + var hands = new[] + { + "2S 2H 2C 8D 2D", + "4S 5H 5S 5D 5C" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "4S 5H 5S 5D 5C" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void With_multiple_decks_both_hands_with_identical_four_of_a_kind_tie_determined_by_kicker() { - var actual = Poker.BestHands(new[] { "3S 3H 2S 3D 3C", "3S 3H 4S 3D 3C" }); - var expected = new[] { "3S 3H 4S 3D 3C" }; + var hands = new[] + { + "3S 3H 2S 3D 3C", + "3S 3H 4S 3D 3C" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "3S 3H 4S 3D 3C" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Straight_flush_beats_four_of_a_kind() { - var actual = Poker.BestHands(new[] { "4S 5H 5S 5D 5C", "7S 8S 9S 6S 10S" }); - var expected = new[] { "7S 8S 9S 6S 10S" }; + var hands = new[] + { + "4S 5H 5S 5D 5C", + "7S 8S 9S 6S 10S" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "7S 8S 9S 6S 10S" + }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_straight_flush_tie_goes_to_highest_ranked_card() { - var actual = Poker.BestHands(new[] { "4H 6H 7H 8H 5H", "5S 7S 8S 9S 6S" }); - var expected = new[] { "5S 7S 8S 9S 6S" }; + var hands = new[] + { + "4H 6H 7H 8H 5H", + "5S 7S 8S 9S 6S" + }; + var actual = Poker.BestHands(hands); + var expected = new[] + { + "5S 7S 8S 9S 6S" + }; Assert.Equal(expected, actual); } } \ No newline at end of file diff --git a/exercises/scale-generator/ScaleGeneratorTest.cs b/exercises/scale-generator/ScaleGeneratorTest.cs index 3f5e9e0870..20062b30bf 100644 --- a/exercises/scale-generator/ScaleGeneratorTest.cs +++ b/exercises/scale-generator/ScaleGeneratorTest.cs @@ -7,119 +7,280 @@ public class ScaleGeneratorTest [Fact] public void Chromatic_scale_with_sharps() { - var expected = new[] { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; + var expected = new[] + { + "C", + "C#", + "D", + "D#", + "E", + "F", + "F#", + "G", + "G#", + "A", + "A#", + "B" + }; Assert.Equal(expected, ScaleGenerator.Pitches("C")); } [Fact(Skip = "Remove to run test")] public void Chromatic_scale_with_flats() { - var expected = new[] { "F", "Gb", "G", "Ab", "A", "Bb", "B", "C", "Db", "D", "Eb", "E" }; + var expected = new[] + { + "F", + "Gb", + "G", + "Ab", + "A", + "Bb", + "B", + "C", + "Db", + "D", + "Eb", + "E" + }; Assert.Equal(expected, ScaleGenerator.Pitches("F")); } [Fact(Skip = "Remove to run test")] public void Simple_major_scale() { - var expected = new[] { "C", "D", "E", "F", "G", "A", "B" }; + var expected = new[] + { + "C", + "D", + "E", + "F", + "G", + "A", + "B" + }; Assert.Equal(expected, ScaleGenerator.Pitches("C", "MMmMMMm")); } [Fact(Skip = "Remove to run test")] public void Major_scale_with_sharps() { - var expected = new[] { "G", "A", "B", "C", "D", "E", "F#" }; + var expected = new[] + { + "G", + "A", + "B", + "C", + "D", + "E", + "F#" + }; Assert.Equal(expected, ScaleGenerator.Pitches("G", "MMmMMMm")); } [Fact(Skip = "Remove to run test")] public void Major_scale_with_flats() { - var expected = new[] { "F", "G", "A", "Bb", "C", "D", "E" }; + var expected = new[] + { + "F", + "G", + "A", + "Bb", + "C", + "D", + "E" + }; Assert.Equal(expected, ScaleGenerator.Pitches("F", "MMmMMMm")); } [Fact(Skip = "Remove to run test")] public void Minor_scale_with_sharps() { - var expected = new[] { "F#", "G#", "A", "B", "C#", "D", "E" }; + var expected = new[] + { + "F#", + "G#", + "A", + "B", + "C#", + "D", + "E" + }; Assert.Equal(expected, ScaleGenerator.Pitches("f#", "MmMMmMM")); } [Fact(Skip = "Remove to run test")] public void Minor_scale_with_flats() { - var expected = new[] { "Bb", "C", "Db", "Eb", "F", "Gb", "Ab" }; + var expected = new[] + { + "Bb", + "C", + "Db", + "Eb", + "F", + "Gb", + "Ab" + }; Assert.Equal(expected, ScaleGenerator.Pitches("bb", "MmMMmMM")); } [Fact(Skip = "Remove to run test")] public void Dorian_mode() { - var expected = new[] { "D", "E", "F", "G", "A", "B", "C" }; + var expected = new[] + { + "D", + "E", + "F", + "G", + "A", + "B", + "C" + }; Assert.Equal(expected, ScaleGenerator.Pitches("d", "MmMMMmM")); } [Fact(Skip = "Remove to run test")] public void Mixolydian_mode() { - var expected = new[] { "Eb", "F", "G", "Ab", "Bb", "C", "Db" }; + var expected = new[] + { + "Eb", + "F", + "G", + "Ab", + "Bb", + "C", + "Db" + }; Assert.Equal(expected, ScaleGenerator.Pitches("Eb", "MMmMMmM")); } [Fact(Skip = "Remove to run test")] public void Lydian_mode() { - var expected = new[] { "A", "B", "C#", "D#", "E", "F#", "G#" }; + var expected = new[] + { + "A", + "B", + "C#", + "D#", + "E", + "F#", + "G#" + }; Assert.Equal(expected, ScaleGenerator.Pitches("a", "MMMmMMm")); } [Fact(Skip = "Remove to run test")] public void Phrygian_mode() { - var expected = new[] { "E", "F", "G", "A", "B", "C", "D" }; + var expected = new[] + { + "E", + "F", + "G", + "A", + "B", + "C", + "D" + }; Assert.Equal(expected, ScaleGenerator.Pitches("e", "mMMMmMM")); } [Fact(Skip = "Remove to run test")] public void Locrian_mode() { - var expected = new[] { "G", "Ab", "Bb", "C", "Db", "Eb", "F" }; + var expected = new[] + { + "G", + "Ab", + "Bb", + "C", + "Db", + "Eb", + "F" + }; Assert.Equal(expected, ScaleGenerator.Pitches("g", "mMMmMMM")); } [Fact(Skip = "Remove to run test")] public void Harmonic_minor() { - var expected = new[] { "D", "E", "F", "G", "A", "Bb", "Db" }; + var expected = new[] + { + "D", + "E", + "F", + "G", + "A", + "Bb", + "Db" + }; Assert.Equal(expected, ScaleGenerator.Pitches("d", "MmMMmAm")); } [Fact(Skip = "Remove to run test")] public void Octatonic() { - var expected = new[] { "C", "D", "D#", "F", "F#", "G#", "A", "B" }; + var expected = new[] + { + "C", + "D", + "D#", + "F", + "F#", + "G#", + "A", + "B" + }; Assert.Equal(expected, ScaleGenerator.Pitches("C", "MmMmMmMm")); } [Fact(Skip = "Remove to run test")] public void Hexatonic() { - var expected = new[] { "Db", "Eb", "F", "G", "A", "B" }; + var expected = new[] + { + "Db", + "Eb", + "F", + "G", + "A", + "B" + }; Assert.Equal(expected, ScaleGenerator.Pitches("Db", "MMMMMM")); } [Fact(Skip = "Remove to run test")] public void Pentatonic() { - var expected = new[] { "A", "B", "C#", "E", "F#" }; + var expected = new[] + { + "A", + "B", + "C#", + "E", + "F#" + }; Assert.Equal(expected, ScaleGenerator.Pitches("A", "MMAMA")); } [Fact(Skip = "Remove to run test")] public void Enigmatic() { - var expected = new[] { "G", "G#", "B", "C#", "D#", "F", "F#" }; + var expected = new[] + { + "G", + "G#", + "B", + "C#", + "D#", + "F", + "F#" + }; Assert.Equal(expected, ScaleGenerator.Pitches("G", "mAMMMmm")); } } \ No newline at end of file diff --git a/exercises/word-search/WordSearchTest.cs b/exercises/word-search/WordSearchTest.cs index c032ae9cad..219a0db813 100644 --- a/exercises/word-search/WordSearchTest.cs +++ b/exercises/word-search/WordSearchTest.cs @@ -1,4 +1,4 @@ -// This file was auto-generated based on version 1.2.0 of the canonical data. +// This file was auto-generated based on version 1.2.1 of the canonical data. using Xunit; using System; diff --git a/generators/Exercises/PascalsTriangle.cs b/generators/Exercises/PascalsTriangle.cs index 3b573694cf..bdc6dc4d6a 100644 --- a/generators/Exercises/PascalsTriangle.cs +++ b/generators/Exercises/PascalsTriangle.cs @@ -13,7 +13,9 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) { canonicalDataCase.UseVariableForExpected = true; canonicalDataCase.Property = "calculate"; - if (!(canonicalDataCase.Expected is JArray)) + if (canonicalDataCase.Expected is JArray jArray) + canonicalDataCase.Expected = jArray.ToObject(); + else canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } diff --git a/generators/Exercises/Poker.cs b/generators/Exercises/Poker.cs index 668e5dd3f2..d296ffaa6b 100644 --- a/generators/Exercises/Poker.cs +++ b/generators/Exercises/Poker.cs @@ -8,6 +8,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) { foreach (var canonicalDataCase in canonicalData.Cases) { + canonicalDataCase.UseVariablesForInput = true; canonicalDataCase.UseVariableForExpected = true; canonicalDataCase.UseVariableForTested = true; } diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index 3269fda335..e02743c57b 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -19,7 +19,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) canonicalDataCase.UseVariableForTested = true; canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Input["matrix"] = (canonicalDataCase.Input["matrix"] as JArray).ToObject(); + canonicalDataCase.Input["matrix"] = ToMultiDimensionalArray(canonicalDataCase.Input["matrix"]); var array = canonicalDataCase.Expected as Array; @@ -32,6 +32,15 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) protected override IEnumerable AdditionalNamespaces() => new[] { typeof(System.String).Namespace }; + private static dynamic ToMultiDimensionalArray(dynamic array) + { + var jArray = (JArray)array; + if (jArray.Count == 1 && ((JArray)jArray[0]).Count == 0) + return new int[0, 0]; + + return jArray.ToObject(); + } + private IEnumerable> ToTupleCollection(Array array) { for (int x = 0; x < array.GetLength(0); x++) From 5123f65bd1decda71b4eb8c30030a03df1da9352 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 07:56:24 +0200 Subject: [PATCH 04/97] exercises: Use Array.Empty instead of new T[0] --- exercises/all-your-base/AllYourBaseTest.cs | 4 ++-- exercises/binary-search/BinarySearchTest.cs | 3 ++- exercises/book-store/BookStoreTest.cs | 3 ++- exercises/bowling/BowlingTest.cs | 6 +++--- exercises/go-counting/GoCountingTest.cs | 12 ++++++------ exercises/minesweeper/MinesweeperTest.cs | 4 ++-- exercises/proverb/ProverbTest.cs | 3 ++- exercises/rectangles/RectanglesTest.cs | 3 ++- exercises/sum-of-multiples/SumOfMultiplesTest.cs | 3 ++- generators/Exercises/AllYourBase.cs | 2 ++ generators/Exercises/Alphametics.cs | 2 +- generators/Exercises/BinarySearch.cs | 6 +++++- generators/Exercises/BinarySearchTree.cs | 7 ++----- generators/Exercises/BookStore.cs | 6 +++++- generators/Exercises/Bowling.cs | 8 ++++++-- generators/Exercises/CircularBuffer.cs | 2 +- generators/Exercises/ComplexNumbers.cs | 2 +- generators/Exercises/Dominoes.cs | 2 +- generators/Exercises/Etl.cs | 2 +- generators/Exercises/Gigasecond.cs | 2 +- generators/Exercises/GoCounting.cs | 2 +- generators/Exercises/Grep.cs | 2 +- generators/Exercises/ListOps.cs | 2 +- generators/Exercises/Meetup.cs | 2 +- generators/Exercises/Minesweeper.cs | 7 ++----- generators/Exercises/NucleotideCount.cs | 2 +- generators/Exercises/OcrNumbers.cs | 2 +- generators/Exercises/Proverb.cs | 6 +++++- generators/Exercises/React.cs | 2 +- generators/Exercises/Rectangles.cs | 8 ++++++-- generators/Exercises/SaddlePoints.cs | 2 +- generators/Exercises/SimpleCipher.cs | 2 +- generators/Exercises/Sublist.cs | 2 +- generators/Exercises/SumOfMultiples.cs | 6 +++++- generators/Exercises/Tournament.cs | 2 +- generators/Exercises/VariableLengthQuantity.cs | 7 ++----- generators/Exercises/WordCount.cs | 2 +- generators/Exercises/WordSearch.cs | 2 +- generators/GeneratorExercise.cs | 12 +++++------- generators/Output/ValueFormatter.cs | 10 +++++----- 40 files changed, 92 insertions(+), 72 deletions(-) diff --git a/exercises/all-your-base/AllYourBaseTest.cs b/exercises/all-your-base/AllYourBaseTest.cs index abfaf4e897..c7ed9acdde 100644 --- a/exercises/all-your-base/AllYourBaseTest.cs +++ b/exercises/all-your-base/AllYourBaseTest.cs @@ -89,7 +89,7 @@ public void Number_15_bit_integer() public void Empty_list() { var inputBase = 2; - var digits = new int[0]; + var digits = Array.Empty(); var outputBase = 10; var expected = new[] { 0 }; Assert.Equal(expected, AllYourBase.Rebase(inputBase, digits, outputBase)); @@ -138,7 +138,7 @@ public void Input_base_is_one() public void Input_base_is_zero() { var inputBase = 0; - var digits = new int[0]; + var digits = Array.Empty(); var outputBase = 10; Assert.Throws(() => AllYourBase.Rebase(inputBase, digits, outputBase)); } diff --git a/exercises/binary-search/BinarySearchTest.cs b/exercises/binary-search/BinarySearchTest.cs index 0a8c69597e..33dae2e239 100644 --- a/exercises/binary-search/BinarySearchTest.cs +++ b/exercises/binary-search/BinarySearchTest.cs @@ -1,6 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. using Xunit; +using System; public class BinarySearchTest { @@ -79,7 +80,7 @@ public void A_value_larger_than_the_arrays_largest_value_is_not_included() [Fact(Skip = "Remove to run test")] public void Nothing_is_included_in_an_empty_array() { - var array = new int[0]; + var array = Array.Empty(); var sut = new BinarySearch(array); Assert.Equal(-1, sut.Find(1)); } diff --git a/exercises/book-store/BookStoreTest.cs b/exercises/book-store/BookStoreTest.cs index c6332e5edd..78b8e8a871 100644 --- a/exercises/book-store/BookStoreTest.cs +++ b/exercises/book-store/BookStoreTest.cs @@ -1,6 +1,7 @@ // This file was auto-generated based on version 1.3.0 of the canonical data. using Xunit; +using System; public class BookStoreTest { @@ -21,7 +22,7 @@ public void Two_of_the_same_book() [Fact(Skip = "Remove to run test")] public void Empty_basket() { - var basket = new int[0]; + var basket = Array.Empty(); Assert.Equal(0, BookStore.Total(basket)); } diff --git a/exercises/bowling/BowlingTest.cs b/exercises/bowling/BowlingTest.cs index e936ffd8e4..8851cda911 100644 --- a/exercises/bowling/BowlingTest.cs +++ b/exercises/bowling/BowlingTest.cs @@ -150,7 +150,7 @@ public void All_strikes_is_a_perfect_game() public void Rolls_cannot_score_negative_points() { var sut = new BowlingGame(); - var previousRolls = new int[0]; + var previousRolls = Array.Empty(); DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(-1)); } @@ -159,7 +159,7 @@ public void Rolls_cannot_score_negative_points() public void A_roll_cannot_score_more_than_10_points() { var sut = new BowlingGame(); - var previousRolls = new int[0]; + var previousRolls = Array.Empty(); DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(11)); } @@ -223,7 +223,7 @@ public void Second_bonus_roll_after_a_strike_in_the_last_frame_cannot_score_more public void An_unstarted_game_cannot_be_scored() { var sut = new BowlingGame(); - var previousRolls = new int[0]; + var previousRolls = Array.Empty(); DoRoll(previousRolls, sut); Assert.Throws(() => sut.Score()); } diff --git a/exercises/go-counting/GoCountingTest.cs b/exercises/go-counting/GoCountingTest.cs index 083efe7ac1..30c7faebec 100644 --- a/exercises/go-counting/GoCountingTest.cs +++ b/exercises/go-counting/GoCountingTest.cs @@ -69,7 +69,7 @@ public void A_stone_and_not_a_territory_on_5x5_board() " W "; var sut = new GoCounting(board); var actual = sut.Territory(coordinate); - var expected = (Owner.None, new ValueTuple[0]); + var expected = (Owner.None, Array.Empty>()); Assert.Equal(expected.Item1, actual.Item1); Assert.Equal(expected.Item2, actual.Item2); } @@ -138,8 +138,8 @@ public void One_territory_is_the_whole_board() var actual = sut.Territories(); var expected = new Dictionary[]> { - [Owner.Black] = new ValueTuple[0], - [Owner.White] = new ValueTuple[0], + [Owner.Black] = Array.Empty>(), + [Owner.White] = Array.Empty>(), [Owner.None] = new[] { (0, 0) } }; Assert.Equal(expected.Keys, actual.Keys); @@ -160,7 +160,7 @@ public void Two_territory_rectangular_board() { [Owner.Black] = new[] { (0, 0), (0, 1) }, [Owner.White] = new[] { (3, 0), (3, 1) }, - [Owner.None] = new ValueTuple[0] + [Owner.None] = Array.Empty>() }; Assert.Equal(expected.Keys, actual.Keys); Assert.Equal(expected[Owner.Black], actual[Owner.Black]); @@ -177,8 +177,8 @@ public void Two_region_rectangular_board() var expected = new Dictionary[]> { [Owner.Black] = new[] { (0, 0), (2, 0) }, - [Owner.White] = new ValueTuple[0], - [Owner.None] = new ValueTuple[0] + [Owner.White] = Array.Empty>(), + [Owner.None] = Array.Empty>() }; Assert.Equal(expected.Keys, actual.Keys); Assert.Equal(expected[Owner.Black], actual[Owner.Black]); diff --git a/exercises/minesweeper/MinesweeperTest.cs b/exercises/minesweeper/MinesweeperTest.cs index f44f6dad1c..d08846350f 100644 --- a/exercises/minesweeper/MinesweeperTest.cs +++ b/exercises/minesweeper/MinesweeperTest.cs @@ -8,8 +8,8 @@ public class MinesweeperTest [Fact] public void No_rows() { - var minefield = new string[0]; - var expected = new string[0]; + var minefield = Array.Empty(); + var expected = Array.Empty(); Assert.Equal(expected, Minesweeper.Annotate(minefield)); } diff --git a/exercises/proverb/ProverbTest.cs b/exercises/proverb/ProverbTest.cs index 3cbe8a2d80..72a23eea98 100644 --- a/exercises/proverb/ProverbTest.cs +++ b/exercises/proverb/ProverbTest.cs @@ -1,13 +1,14 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. using Xunit; +using System; public class ProverbTest { [Fact] public void Zero_pieces() { - Assert.Empty(Proverb.Recite(new string[0])); + Assert.Empty(Proverb.Recite(Array.Empty())); } [Fact(Skip = "Remove to run test")] diff --git a/exercises/rectangles/RectanglesTest.cs b/exercises/rectangles/RectanglesTest.cs index 94838833c3..115ab5e4eb 100644 --- a/exercises/rectangles/RectanglesTest.cs +++ b/exercises/rectangles/RectanglesTest.cs @@ -1,13 +1,14 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. using Xunit; +using System; public class RectanglesTest { [Fact] public void No_rows() { - var strings = new string[0]; + var strings = Array.Empty(); Assert.Equal(0, Rectangles.Count(strings)); } diff --git a/exercises/sum-of-multiples/SumOfMultiplesTest.cs b/exercises/sum-of-multiples/SumOfMultiplesTest.cs index 46268814f4..3befa60321 100644 --- a/exercises/sum-of-multiples/SumOfMultiplesTest.cs +++ b/exercises/sum-of-multiples/SumOfMultiplesTest.cs @@ -1,6 +1,7 @@ // This file was auto-generated based on version 1.2.0 of the canonical data. using Xunit; +using System; public class SumOfMultiplesTest { @@ -79,6 +80,6 @@ public void Multiples_of_1_up_to_100() [Fact(Skip = "Remove to run test")] public void Multiples_of_an_empty_list_up_to_10000() { - Assert.Equal(0, SumOfMultiples.Sum(new int[0], 10000)); + Assert.Equal(0, SumOfMultiples.Sum(Array.Empty(), 10000)); } } \ No newline at end of file diff --git a/generators/Exercises/AllYourBase.cs b/generators/Exercises/AllYourBase.cs index a75393c626..175d44414a 100644 --- a/generators/Exercises/AllYourBase.cs +++ b/generators/Exercises/AllYourBase.cs @@ -16,5 +16,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) canonicalDataCase.UseVariableForExpected = true; } } + + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/Alphametics.cs b/generators/Exercises/Alphametics.cs index f8f9a67561..de24bf52aa 100644 --- a/generators/Exercises/Alphametics.cs +++ b/generators/Exercises/Alphametics.cs @@ -27,6 +27,6 @@ private static dynamic ConvertExpected(CanonicalDataCase canonicalDataCase) return expected.ToDictionary(kv => kv.Key[0], kv => int.Parse(kv.Value.ToString())); } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Dictionary).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/BinarySearch.cs b/generators/Exercises/BinarySearch.cs index 6ab3860f86..0835fc4510 100644 --- a/generators/Exercises/BinarySearch.cs +++ b/generators/Exercises/BinarySearch.cs @@ -1,4 +1,6 @@ -using Generators.Input; +using System; +using System.Collections.Generic; +using Generators.Input; namespace Generators.Exercises { @@ -13,5 +15,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) canonicalDataCase.SetConstructorInputParameters("array"); } } + + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index 583353453e..7911230efa 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -29,7 +29,7 @@ public IEnumerable TestAsserts(string traverse = "") public class BinarySearchTree : GeneratorExercise { - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(System.Linq.IQueryable).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(System.Linq.IQueryable).Namespace }; private StringBuilder testFactCodeLines; void addCodeLine(string line) => testFactCodeLines.Append(line + "\r\n"); @@ -62,8 +62,5 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo return TemplateRenderer.RenderInline(testFactCodeLines.ToString(), testMethodBody.AssertTemplateParameters); } - } -} - - +} \ No newline at end of file diff --git a/generators/Exercises/BookStore.cs b/generators/Exercises/BookStore.cs index de874c5aa5..f5bf9f6547 100644 --- a/generators/Exercises/BookStore.cs +++ b/generators/Exercises/BookStore.cs @@ -1,4 +1,6 @@ -using Generators.Input; +using System; +using System.Collections.Generic; +using Generators.Input; namespace Generators.Exercises { @@ -14,5 +16,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) canonicalDataCase.UseVariablesForInput = true; } } + + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index d48e5ed2a6..7a8a703541 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -37,7 +37,7 @@ protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodB var array = testMethodBody.CanonicalDataCase.Input[PreviousRolls] as int[]; if (array == null) { - builder.Append("var previousRolls = new int[0];"); + builder.Append("var previousRolls = Array.Empty();"); } else { @@ -112,6 +112,10 @@ public void DoRoll(ICollection rolls, BowlingGame sut) }" }; } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(ICollection<>).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] + { + typeof(Array).Namespace, + typeof(ICollection<>).Namespace + }; } } \ No newline at end of file diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/CircularBuffer.cs index c95824cfbf..2b18091372 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/CircularBuffer.cs @@ -68,6 +68,6 @@ private static string RenderOverwriteOperation(dynamic operation) private static string RenderClearOperation(dynamic operation) => "buffer.Clear();"; - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(InvalidOperationException).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(InvalidOperationException).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 5d1c307126..e42a9dc2bf 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -50,7 +50,7 @@ private static string RenderComplexNumberAssert(TestMethodBody testMethodBody) return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Math).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Math).Namespace }; private static object ConvertToType(dynamic rawValue) { diff --git a/generators/Exercises/Dominoes.cs b/generators/Exercises/Dominoes.cs index 7599cea219..d66b1e44e5 100644 --- a/generators/Exercises/Dominoes.cs +++ b/generators/Exercises/Dominoes.cs @@ -18,7 +18,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Tuple).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Tuple).Namespace }; private UnescapedValue ConvertInput(dynamic input) { diff --git a/generators/Exercises/Etl.cs b/generators/Exercises/Etl.cs index 9f9ab35609..f87f15dd42 100644 --- a/generators/Exercises/Etl.cs +++ b/generators/Exercises/Etl.cs @@ -28,6 +28,6 @@ private static IDictionary ConvertInput(IDictionary int.Parse(kv.Key), kv => (string[])kv.Value) }; - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Dictionary).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; } } diff --git a/generators/Exercises/Gigasecond.cs b/generators/Exercises/Gigasecond.cs index b11b254a1a..d3a21635d7 100644 --- a/generators/Exercises/Gigasecond.cs +++ b/generators/Exercises/Gigasecond.cs @@ -18,7 +18,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(DateTime).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(DateTime).Namespace }; private static string FormatDateTime(DateTime dateTime) { diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index 22ca1955f1..103f535acd 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -86,7 +86,7 @@ private string FormatOwner(dynamic owner) private string FormatTerritory(dynamic territory) => ValueFormatter.Format((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); - protected override IEnumerable AdditionalNamespaces() => new[] + protected override IEnumerable AdditionalNamespaces => new[] { typeof(ArgumentException).Namespace, typeof(Dictionary).Namespace diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index 4ecd131af2..e1b440ccb1 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -39,7 +39,7 @@ protected override TestClass CreateTestClass() return testClass; } - protected override IEnumerable AdditionalNamespaces() => new[] + protected override IEnumerable AdditionalNamespaces => new[] { typeof(IDisposable).Namespace, typeof(System.IO.File).Namespace diff --git a/generators/Exercises/ListOps.cs b/generators/Exercises/ListOps.cs index 855a7641e4..6d2c65a3ee 100644 --- a/generators/Exercises/ListOps.cs +++ b/generators/Exercises/ListOps.cs @@ -114,7 +114,7 @@ private static dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) return value; } - protected override IEnumerable AdditionalNamespaces() => new[] + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Func).Namespace, typeof(List).Namespace diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index fa6620a924..b66f290ac6 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -40,6 +40,6 @@ protected override String RenderTestMethodBodyAssert(TestMethodBody testMethodBo return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(DayOfWeek).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(DayOfWeek).Namespace }; } } diff --git a/generators/Exercises/Minesweeper.cs b/generators/Exercises/Minesweeper.cs index 2f39af4ee4..9fe6cfa659 100644 --- a/generators/Exercises/Minesweeper.cs +++ b/generators/Exercises/Minesweeper.cs @@ -20,10 +20,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } - private UnescapedValue ToMultiLineString(JArray input) - { - return new UnescapedValue("new string[0]"); - } + private UnescapedValue ToMultiLineString(JArray input) => new UnescapedValue("Array.Empty()"); private UnescapedValue ToMultiLineString(IEnumerable input) { @@ -37,6 +34,6 @@ private UnescapedValue ToMultiLineString(IEnumerable input) return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Array).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; } } diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index c2b104504c..d139e73966 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -23,7 +23,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) private static dynamic ConvertExpected(dynamic expected) => ((Dictionary)expected).ToDictionary(kv => kv.Key[0], kv => int.Parse($"{kv.Value}")); - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Dictionary).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { diff --git a/generators/Exercises/OcrNumbers.cs b/generators/Exercises/OcrNumbers.cs index 2f51fe1bec..b7bfde739b 100644 --- a/generators/Exercises/OcrNumbers.cs +++ b/generators/Exercises/OcrNumbers.cs @@ -33,6 +33,6 @@ private UnescapedValue ToDigitStringRepresentation(string[] input) return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Array).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; } } diff --git a/generators/Exercises/Proverb.cs b/generators/Exercises/Proverb.cs index 72a28e1a59..c13df65851 100644 --- a/generators/Exercises/Proverb.cs +++ b/generators/Exercises/Proverb.cs @@ -1,4 +1,6 @@ -using Generators.Input; +using System; +using System.Collections.Generic; +using Generators.Input; using Generators.Output; namespace Generators.Exercises @@ -14,5 +16,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) canonicalDataCase.Expected = ConvertHelper.ToArray(canonicalDataCase.Expected); } } + + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index 340b34f0f2..cc52c3f9a3 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -125,7 +125,7 @@ private static string RenderOperation(dynamic operation) protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) => ""; - protected override IEnumerable AdditionalNamespaces() => new[] + protected override IEnumerable AdditionalNamespaces => new[] { typeof(EventHandler).Namespace, "FakeItEasy" diff --git a/generators/Exercises/Rectangles.cs b/generators/Exercises/Rectangles.cs index 10b48a81df..ec08a685c1 100644 --- a/generators/Exercises/Rectangles.cs +++ b/generators/Exercises/Rectangles.cs @@ -1,4 +1,6 @@ -using Generators.Input; +using System; +using System.Collections.Generic; +using Generators.Input; namespace Generators.Exercises { @@ -9,9 +11,11 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) foreach (var canonicalDataCase in canonicalData.Cases) { canonicalDataCase.Property = "count"; - canonicalDataCase.Input["strings"] = canonicalDataCase.Input["strings"] as string[] ?? new string[0]; + canonicalDataCase.Input["strings"] = canonicalDataCase.Input["strings"] as string[] ?? Array.Empty(); canonicalDataCase.UseVariablesForInput = true; } } + + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index e02743c57b..afa5690443 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -30,7 +30,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(System.String).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(System.String).Namespace }; private static dynamic ToMultiDimensionalArray(dynamic array) { diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index 997bdd23e8..f79c221cc0 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -62,6 +62,6 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo return base.RenderTestMethodBodyAssert(testMethodBody); } - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(ArgumentException).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(ArgumentException).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/Sublist.cs b/generators/Exercises/Sublist.cs index 66f8784138..215641bf5b 100644 --- a/generators/Exercises/Sublist.cs +++ b/generators/Exercises/Sublist.cs @@ -8,7 +8,7 @@ namespace Generators.Exercises { public class Sublist : GeneratorExercise { - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(IList).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(IList).Namespace }; private UnescapedValue InputValues(int[] list) { diff --git a/generators/Exercises/SumOfMultiples.cs b/generators/Exercises/SumOfMultiples.cs index 1d4f4ef797..2884c5feed 100644 --- a/generators/Exercises/SumOfMultiples.cs +++ b/generators/Exercises/SumOfMultiples.cs @@ -1,4 +1,6 @@ -using Generators.Input; +using System; +using System.Collections.Generic; +using Generators.Input; namespace Generators.Exercises { @@ -11,5 +13,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) canonicalDataCase.Input["factors"] = ConvertHelper.ToArray(canonicalDataCase.Input["factors"]); } } + + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; } } \ No newline at end of file diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index 6357230e70..a4c0dad78c 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -21,7 +21,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } - protected override IEnumerable AdditionalNamespaces() => new[] + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace, typeof(System.String).Namespace, diff --git a/generators/Exercises/VariableLengthQuantity.cs b/generators/Exercises/VariableLengthQuantity.cs index 34e22a89ca..4d47604d9e 100644 --- a/generators/Exercises/VariableLengthQuantity.cs +++ b/generators/Exercises/VariableLengthQuantity.cs @@ -24,14 +24,11 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) } } + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + private dynamic FormatUInt32Array(dynamic input) { var numbers = ToUInt32Array(input as IEnumerable); - if (!numbers.Any()) - { - return new UnescapedValue("new uint[0]"); - } - return numbers.Select(number => new UnescapedValue(string.Format("0x{0:X}u", number))).ToArray(); } diff --git a/generators/Exercises/WordCount.cs b/generators/Exercises/WordCount.cs index e9d8cac7a6..461e0e2058 100644 --- a/generators/Exercises/WordCount.cs +++ b/generators/Exercises/WordCount.cs @@ -19,6 +19,6 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) private static dynamic ConvertExpected(dynamic expected) => ((Dictionary)expected).ToDictionary(kv => kv.Key, kv => int.Parse(kv.Value.ToString())); - protected override IEnumerable AdditionalNamespaces() => new[] { typeof(Dictionary).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; } } diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index ac8303db4a..1229911d57 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -75,7 +75,7 @@ private string FormatPosition(dynamic position) private string FormatCoordinate(dynamic coordinate) => ValueFormatter.Format((coordinate["column"], coordinate["row"])); - protected override IEnumerable AdditionalNamespaces() => new[] + protected override IEnumerable AdditionalNamespaces => new[] { typeof(ValueTuple).Namespace, typeof(Dictionary>).Namespace diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index 8f9c2f6603..9d16e52c93 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Generators.Input; using Generators.Output; @@ -26,7 +27,7 @@ protected virtual void UpdateCanonicalData(CanonicalData canonicalData) { } - protected virtual IEnumerable AdditionalNamespaces() => Enumerable.Empty(); + protected virtual IEnumerable AdditionalNamespaces => Enumerable.Empty(); protected virtual string RenderTestMethodBodyArrange(TestMethodBody testMethodBody) => TemplateRenderer.RenderPartial(testMethodBody.ArrangeTemplateName, testMethodBody.ArrangeTemplateParameters); @@ -37,10 +38,7 @@ protected virtual string RenderTestMethodBodyAct(TestMethodBody testMethodBody) protected virtual string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) => TemplateRenderer.RenderPartial(testMethodBody.AssertTemplateName, testMethodBody.AssertTemplateParameters); - protected virtual string[] RenderAdditionalMethods() - { - return new string[] { }; - } + protected virtual string[] RenderAdditionalMethods() => Array.Empty(); private HashSet GetUsingNamespaces() { @@ -49,7 +47,7 @@ private HashSet GetUsingNamespaces() foreach (var canonicalDataCase in _canonicalData.Cases.Where(canonicalDataCase => canonicalDataCase.ExceptionThrown != null)) usingNamespaces.Add(canonicalDataCase.ExceptionThrown.Namespace); - usingNamespaces.UnionWith(AdditionalNamespaces()); + usingNamespaces.UnionWith(AdditionalNamespaces); return usingNamespaces; } diff --git a/generators/Output/ValueFormatter.cs b/generators/Output/ValueFormatter.cs index 0866656f4d..a7da0774da 100644 --- a/generators/Output/ValueFormatter.cs +++ b/generators/Output/ValueFormatter.cs @@ -49,7 +49,7 @@ public static string[] FormatVariable(object val, string name) case IEnumerable strings: if (!strings.Any()) { - return new[] { $"var {name} = new string[0];" }; + return new[] { $"var {name} = Array.Empty();" }; } return FormatMultiLineEnumerable(strings.Select((str, i) => str.Format() + (i < strings.Count() - 1 ? "," : "")), name, "new[]"); @@ -85,13 +85,13 @@ private static string Format(this Tuple tuple) => $"Tuple.Create({tuple.Item1}, {tuple.Item2})"; private static string Format(this IEnumerable ints) => ints.Any() ? - $"new[] {{ {string.Join(", ", ints)} }}" : "new int[0]"; + $"new[] {{ {string.Join(", ", ints)} }}" : "Array.Empty()"; private static string Format(this IEnumerable strings) => - strings.Any() ? $"new[] {{ {string.Join(", ", strings.Select(Format))} }}" : "new string[0]"; + strings.Any() ? $"new[] {{ {string.Join(", ", strings.Select(Format))} }}" : "Array.Empty()"; private static string Format(this IEnumerable objects) => - objects.Any() ? $"new[] {{ {string.Join(", ", objects.Select(Format))} }}" : "new object[0]"; + objects.Any() ? $"new[] {{ {string.Join(", ", objects.Select(Format))} }}" : "Array.Empty()"; private static string Format(this List ints) => ints.Any() ? $"new List {{ {string.Join(", ", ints.Select(Format))} }}" : "new List()"; @@ -103,7 +103,7 @@ private static string Format(this IEnumerable unescapedValues) = $"new[] {{ {string.Join(", ", unescapedValues.Select(Format))} }}"; private static string Format(this IEnumerable> tuples) => tuples.Any() ? - $"new[] {{ {string.Join(", ", tuples)} }}" : "new ValueTuple[0]"; + $"new[] {{ {string.Join(", ", tuples)} }}" : "Array.Empty>()"; private static string Format(this IDictionary dict) => string.Join(", ", dict.Values.Select(Format)); From 5a435602cec1fec36395bf647ff36c382e949abe Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 08:39:47 +0200 Subject: [PATCH 05/97] generators: Use static class --- generators/Output/IndentFilter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/generators/Output/IndentFilter.cs b/generators/Output/IndentFilter.cs index fc3a6d6f44..03251d3159 100644 --- a/generators/Output/IndentFilter.cs +++ b/generators/Output/IndentFilter.cs @@ -3,9 +3,9 @@ namespace Generators.Output { - public class IndentFilter + public static class IndentFilter { - public static string Indent(string input) + public static string Indent(string input) => string.Join(Environment.NewLine, input .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Indent())); From dc72c27e2c6eeb7bba70ccac915a0878a899dcbb Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 10:32:42 +0200 Subject: [PATCH 06/97] generators: Remove unused using statements --- generators/Exercises/BinarySearchTree.cs | 3 +-- generators/Exercises/Etl.cs | 1 - generators/Exercises/Grep.cs | 1 - generators/Exercises/PalindromeProducts.cs | 2 -- generators/Exercises/PascalsTriangle.cs | 1 - generators/Exercises/Pov.cs | 2 -- generators/Exercises/ProteinTranslation.cs | 4 +--- generators/Exercises/Proverb.cs | 1 - generators/Exercises/React.cs | 1 - generators/Exercises/SpiralMatrix.cs | 5 +---- generators/Exercises/Tournament.cs | 1 - generators/Exercises/TwelveDays.cs | 8 +------- generators/Exercises/WordSearch.cs | 2 -- generators/Exercises/Yacht.cs | 3 +-- generators/Exercises/ZebraPuzzle.cs | 3 +-- generators/Exercises/Zipper.cs | 1 - generators/Input/CanonicalDataCase.cs | 2 -- 17 files changed, 6 insertions(+), 35 deletions(-) diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index 7911230efa..8eb35ada05 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Text; using Generators.Output; diff --git a/generators/Exercises/Etl.cs b/generators/Exercises/Etl.cs index f87f15dd42..b9508bf9dd 100644 --- a/generators/Exercises/Etl.cs +++ b/generators/Exercises/Etl.cs @@ -1,5 +1,4 @@ using Generators.Input; -using Generators.Output; using System.Collections.Generic; using System.Linq; diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index e1b440ccb1..b42124b720 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -3,7 +3,6 @@ using System.Linq; using Generators.Input; using Generators.Output; -using Newtonsoft.Json.Linq; namespace Generators.Exercises { diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/PalindromeProducts.cs index 24144cbce2..07fe2495d5 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/PalindromeProducts.cs @@ -1,9 +1,7 @@ using System; -using System.Collections.Generic; using System.Linq; using Generators.Input; using Generators.Output; -using Humanizer; using Newtonsoft.Json.Linq; namespace Generators.Exercises diff --git a/generators/Exercises/PascalsTriangle.cs b/generators/Exercises/PascalsTriangle.cs index bdc6dc4d6a..9944ccdfbc 100644 --- a/generators/Exercises/PascalsTriangle.cs +++ b/generators/Exercises/PascalsTriangle.cs @@ -1,5 +1,4 @@ using System; -using System.Linq; using Generators.Input; using Newtonsoft.Json.Linq; diff --git a/generators/Exercises/Pov.cs b/generators/Exercises/Pov.cs index dd3e6ecaf1..61011491ae 100644 --- a/generators/Exercises/Pov.cs +++ b/generators/Exercises/Pov.cs @@ -3,8 +3,6 @@ using System.Text; using Generators.Input; using Generators.Output; -using Humanizer; -using Newtonsoft.Json.Linq; namespace Generators.Exercises { diff --git a/generators/Exercises/ProteinTranslation.cs b/generators/Exercises/ProteinTranslation.cs index 987d12bc81..932ebe262a 100644 --- a/generators/Exercises/ProteinTranslation.cs +++ b/generators/Exercises/ProteinTranslation.cs @@ -1,6 +1,4 @@ -using Generators.Input; - -namespace Generators.Exercises +namespace Generators.Exercises { public class ProteinTranslation : GeneratorExercise { diff --git a/generators/Exercises/Proverb.cs b/generators/Exercises/Proverb.cs index c13df65851..b8f99b6ce8 100644 --- a/generators/Exercises/Proverb.cs +++ b/generators/Exercises/Proverb.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using Generators.Input; -using Generators.Output; namespace Generators.Exercises { diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index cc52c3f9a3..84ed89642d 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -5,7 +5,6 @@ using System.Text.RegularExpressions; using Generators.Output; using Humanizer; -using Newtonsoft.Json.Linq; namespace Generators.Exercises { diff --git a/generators/Exercises/SpiralMatrix.cs b/generators/Exercises/SpiralMatrix.cs index 15ab185a81..13188f8b17 100644 --- a/generators/Exercises/SpiralMatrix.cs +++ b/generators/Exercises/SpiralMatrix.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using System.Linq; using Generators.Input; -using Generators.Output; using Newtonsoft.Json.Linq; namespace Generators.Exercises diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index a4c0dad78c..cadfb49822 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using Generators.Input; using Generators.Output; -using Newtonsoft.Json.Linq; namespace Generators.Exercises { diff --git a/generators/Exercises/TwelveDays.cs b/generators/Exercises/TwelveDays.cs index fd2bcc3cbc..e2a49bfb14 100644 --- a/generators/Exercises/TwelveDays.cs +++ b/generators/Exercises/TwelveDays.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Generators.Input; -using Generators.Output; -using System.Linq; -using Humanizer; +using Generators.Input; namespace Generators.Exercises { diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index 1229911d57..c3c27b8dbc 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -3,8 +3,6 @@ using System.Linq; using Generators.Input; using Generators.Output; -using Humanizer; -using Newtonsoft.Json.Linq; namespace Generators.Exercises { diff --git a/generators/Exercises/Yacht.cs b/generators/Exercises/Yacht.cs index f79a37c95a..d2ccd9ed13 100644 --- a/generators/Exercises/Yacht.cs +++ b/generators/Exercises/Yacht.cs @@ -1,5 +1,4 @@ -using System; -using Generators.Input; +using Generators.Input; using Generators.Output; using Humanizer; diff --git a/generators/Exercises/ZebraPuzzle.cs b/generators/Exercises/ZebraPuzzle.cs index f0833ea052..bdc12aab8e 100644 --- a/generators/Exercises/ZebraPuzzle.cs +++ b/generators/Exercises/ZebraPuzzle.cs @@ -1,5 +1,4 @@ -using System; -using Generators.Input; +using Generators.Input; using Generators.Output; using Humanizer; diff --git a/generators/Exercises/Zipper.cs b/generators/Exercises/Zipper.cs index b105e7ea48..e2e03e63fd 100644 --- a/generators/Exercises/Zipper.cs +++ b/generators/Exercises/Zipper.cs @@ -3,7 +3,6 @@ using System.Text; using Generators.Output; using Humanizer; -using Newtonsoft.Json.Linq; namespace Generators.Exercises { diff --git a/generators/Input/CanonicalDataCase.cs b/generators/Input/CanonicalDataCase.cs index 1c1b4e243f..15bc299d34 100644 --- a/generators/Input/CanonicalDataCase.cs +++ b/generators/Input/CanonicalDataCase.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; namespace Generators.Input { From 3fa390b5b90cdc07634e7e06268a5f0f008526ca Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 10:55:24 +0200 Subject: [PATCH 07/97] generators: Move exercise field to canonical data case class --- generators/Exercises/ComplexNumbers.cs | 3 +-- generators/Exercises/RunLengthEncoding.cs | 2 +- generators/Exercises/Yacht.cs | 2 +- generators/Input/CanonicalData.cs | 6 ++---- generators/Input/CanonicalDataCase.cs | 3 ++- generators/Input/CanonicalDataParser.cs | 3 +++ generators/Output/TestMethodBodyData.cs | 2 +- 7 files changed, 11 insertions(+), 10 deletions(-) diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index e42a9dc2bf..619bc77f31 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -11,10 +11,9 @@ public class ComplexNumbers : GeneratorExercise { protected override void UpdateCanonicalData(CanonicalData canonicalData) { - canonicalData.Exercise = "complex-number"; - foreach (var canonicalDataCase in canonicalData.Cases) { + canonicalDataCase.Exercise = "complex-number"; canonicalDataCase.UseVariableForExpected = IsComplexNumber(canonicalDataCase.Expected); canonicalDataCase.Expected = ConvertToType(canonicalDataCase.Expected); diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index 9616b3792b..5a4eaa3498 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -31,7 +31,7 @@ private static string RenderConsistencyToAssert(TestMethodBody testMethodBody) var templateParameters = new { ExpectedOutput = testMethodBody.CanonicalDataCase.Expected, - ExerciseName = testMethodBody.CanonicalData.Exercise.ToTestedClassName() + ExerciseName = testMethodBody.CanonicalDataCase.Exercise.ToTestedClassName() }; return TemplateRenderer.RenderInline(template, templateParameters); diff --git a/generators/Exercises/Yacht.cs b/generators/Exercises/Yacht.cs index d2ccd9ed13..be40514db6 100644 --- a/generators/Exercises/Yacht.cs +++ b/generators/Exercises/Yacht.cs @@ -8,9 +8,9 @@ public class Yacht : GeneratorExercise { protected override void UpdateCanonicalData(CanonicalData canonicalData) { - canonicalData.Exercise = "yacht-game"; foreach (var canonicalDataCase in canonicalData.Cases) { + canonicalDataCase.Exercise = "yacht-game"; var category = canonicalDataCase.Input["category"].ToString(); var formattedCategory = StringDehumanizeExtensions.Dehumanize(category); canonicalDataCase.Input["category"] = new UnescapedValue($"YachtCategory.{formattedCategory}"); diff --git a/generators/Input/CanonicalData.cs b/generators/Input/CanonicalData.cs index 1359c97859..19268a61e2 100644 --- a/generators/Input/CanonicalData.cs +++ b/generators/Input/CanonicalData.cs @@ -1,14 +1,12 @@ namespace Generators.Input { - public class CanonicalData + public sealed class CanonicalData { public CanonicalData(string exercise, string version, CanonicalDataCase[] cases) => (Exercise, Version, Cases) = (exercise, version, cases); - public string Exercise { get; set; } - + public string Exercise { get; } public string Version { get; } - public CanonicalDataCase[] Cases { get; } } } \ No newline at end of file diff --git a/generators/Input/CanonicalDataCase.cs b/generators/Input/CanonicalDataCase.cs index 15bc299d34..81834ebca6 100644 --- a/generators/Input/CanonicalDataCase.cs +++ b/generators/Input/CanonicalDataCase.cs @@ -3,12 +3,13 @@ namespace Generators.Input { - public class CanonicalDataCase + public sealed class CanonicalDataCase { public IDictionary Properties { get; set; } public IDictionary Input { get; set; } public dynamic Expected { get; set; } + public string Exercise { get; set; } public string Property { get; set; } public string Description { get; set; } public string[] DescriptionPath { get; set; } diff --git a/generators/Input/CanonicalDataParser.cs b/generators/Input/CanonicalDataParser.cs index 4229b7471e..206af4ac1f 100644 --- a/generators/Input/CanonicalDataParser.cs +++ b/generators/Input/CanonicalDataParser.cs @@ -17,6 +17,9 @@ public CanonicalData Parse(string exercise) var version = ParseVersion(canonicalDataJson); var canonicalDataCases = ParseCanonicalDataCases(canonicalDataJson); + foreach (var canonicalDataCase in canonicalDataCases) + canonicalDataCase.Exercise = name; + return new CanonicalData(name, version, canonicalDataCases); } diff --git a/generators/Output/TestMethodBodyData.cs b/generators/Output/TestMethodBodyData.cs index 5591cd71f8..9d4cd6c406 100644 --- a/generators/Output/TestMethodBodyData.cs +++ b/generators/Output/TestMethodBodyData.cs @@ -23,7 +23,7 @@ public class TestMethodBodyData private CanonicalDataCase CanonicalDataCase => _testMethodBody.CanonicalDataCase; private CanonicalData CanonicalData => _testMethodBody.CanonicalData; - private string TestedClassName => CanonicalData.Exercise.ToTestedClassName(); + private string TestedClassName => CanonicalDataCase.Exercise.ToTestedClassName(); private string TestedMethodName => CanonicalDataCase.Property.ToTestedMethodName(); private IDictionary Input => CanonicalDataCase.InputParameters.ToDictionary(key => key, key => CanonicalDataCase.Input[key]); From 745cc84f3c961c906399f9d096df4d88a0110db5 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 11:20:29 +0200 Subject: [PATCH 08/97] generators: Use environment specific newline --- generators/Exercises/GoCounting.cs | 6 +++--- generators/Exercises/Grep.cs | 2 +- generators/Exercises/PalindromeProducts.cs | 2 +- generators/Exercises/React.cs | 6 +++--- generators/Exercises/WordSearch.cs | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index 103f535acd..c10b1535b5 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -50,7 +50,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) "}" }; - canonicalDataCase.Expected = new UnescapedValue(string.Join("\n", expected)); + canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } } } @@ -64,7 +64,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo if (testMethodBody.CanonicalDataCase.Property == "territories") { - return string.Join("\n", new[] + return string.Join(Environment.NewLine, new[] { "Assert.Equal(expected.Keys, actual.Keys);", "Assert.Equal(expected[Owner.Black], actual[Owner.Black]);", @@ -73,7 +73,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo }); } - return string.Join("\n", new[] + return string.Join(Environment.NewLine, new[] { "Assert.Equal(expected.Item1, actual.Item1);", "Assert.Equal(expected.Item2, actual.Item2);" diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index b42124b720..84532f0842 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -27,7 +27,7 @@ private static dynamic ConvertExpected(dynamic expected) if (arr == null || arr.Length == 0) return ""; - return new UnescapedValue("\n" + string.Join("\n", arr.Select(((x, i) => $" \"{x}\\n\"{(i < arr.Length - 1 ? " +" : "")}")))); + return new UnescapedValue(Environment.NewLine + string.Join(Environment.NewLine, arr.Select(((x, i) => $" \"{x}\\n\"{(i < arr.Length - 1 ? " +" : "")}")))); } protected override TestClass CreateTestClass() diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/PalindromeProducts.cs index 07fe2495d5..9b714a9976 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/PalindromeProducts.cs @@ -32,7 +32,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo return base.RenderTestMethodBodyAssert(testMethodBody); } - return string.Join("\n", new[] + return string.Join(Environment.NewLine, new[] { "Assert.Equal(expected.Item1, actual.Item1);", "Assert.Equal(expected.Item2, actual.Item2);" diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index 84ed89642d..e833797311 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -32,7 +32,7 @@ private static string RenderCells(dynamic cells) } var renderedCells = ((object[])cells).Select(RenderCell); - return string.Join("\n", renderedCells); + return string.Join(Environment.NewLine, renderedCells); } private static string RenderCell(dynamic cell) @@ -73,7 +73,7 @@ private static string RenderOperations(dynamic operations) } var renderedOperations = ((object[])operations).Select(RenderOperation); - return string.Join("\n", renderedOperations); + return string.Join(Environment.NewLine, renderedOperations); } private static string RenderOperation(dynamic operation) @@ -112,7 +112,7 @@ private static string RenderOperation(dynamic operation) return $"Assert.Equal({operation["value"]}, {ToVariableName(operation["cell"])}.Value);"; case "add_callback": var addCallbackName = ToVariableName(operation["name"]); - return $"var {addCallbackName} = A.Fake>();\n" + + return $"var {addCallbackName} = A.Fake>();{Environment.NewLine}" + $"{ToVariableName(operation["cell"])}.Changed += {addCallbackName};"; case "remove_callback": var removeCallbackName = ToVariableName(operation["name"]); diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index c3c27b8dbc..904ef9bfd3 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -32,7 +32,7 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) expected.AddRange(expectedDictionary.Select(((kv, i) => $" [\"{kv.Key}\"] = {FormatPosition(kv.Value)}{(i < expectedDictionary.Count - 1 ? "," : "")}"))); expected.Add("}"); - canonicalDataCase.Expected = new UnescapedValue(string.Join("\n", expected)); + canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } } @@ -47,7 +47,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo assert.Add(RenderTestMethodBodyAssertForSearchWord(kv.Key, kv.Value)); } - return string.Join("\n", assert); + return string.Join(Environment.NewLine, assert); } private string RenderTestMethodBodyAssertForSearchWord(string word, dynamic expected) From 0d08690e7d9fe6959df8389210adc0cd8c7a138e Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 11:40:05 +0200 Subject: [PATCH 09/97] generators: Fix culture-specific output --- .../rational-numbers/RationalNumbersTest.cs | 6 +++--- generators/Exercises/RationalNumbers.cs | 13 +++++++------ generators/Exercises/Triangle.cs | 16 ++++++---------- 3 files changed, 16 insertions(+), 19 deletions(-) diff --git a/exercises/rational-numbers/RationalNumbersTest.cs b/exercises/rational-numbers/RationalNumbersTest.cs index ef44b49e70..0db57b440e 100644 --- a/exercises/rational-numbers/RationalNumbersTest.cs +++ b/exercises/rational-numbers/RationalNumbersTest.cs @@ -169,19 +169,19 @@ public void Raise_a_negative_rational_number_to_the_power_of_zero() [Fact(Skip = "Remove to run test")] public void Raise_a_real_number_to_a_positive_rational_number() { - Assert.Equal(16, 8.Expreal(new RationalNumber(4, 3)),0); + Assert.Equal(16, 8.Expreal(new RationalNumber(4, 3)), 0); } [Fact(Skip = "Remove to run test")] public void Raise_a_real_number_to_a_negative_rational_number() { - Assert.Equal(0.333333333333333, 9.Expreal(new RationalNumber(-1, 2)),15); + Assert.Equal(0.333333333333333, 9.Expreal(new RationalNumber(-1, 2)), 15); } [Fact(Skip = "Remove to run test")] public void Raise_a_real_number_to_a_zero_rational_number() { - Assert.Equal(1, 2.Expreal(new RationalNumber(0, 1)),0); + Assert.Equal(1, 2.Expreal(new RationalNumber(0, 1)), 0); } [Fact(Skip = "Remove to run test")] diff --git a/generators/Exercises/RationalNumbers.cs b/generators/Exercises/RationalNumbers.cs index d26d16823a..e7f68c6d4b 100644 --- a/generators/Exercises/RationalNumbers.cs +++ b/generators/Exercises/RationalNumbers.cs @@ -13,7 +13,7 @@ public RationalNumber(int[] n) public int Numerator { get; } public int Denominator { get; } } - + public class RationalNumbers : GeneratorExercise { protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) @@ -21,7 +21,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo var input = testMethodBody.CanonicalDataCase.Properties["input"] as System.Collections.Generic.Dictionary; var operation = testMethodBody.CanonicalDataCase.Properties["property"].ToString(); var expected = testMethodBody.CanonicalDataCase.Properties["expected"]; - var operationName = char.ToUpper(operation[0]) + operation.Substring(1); + var operationName = char.ToUpper(operation[0]) + operation.Substring(1); string assertCodeLine = ""; string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; string operationCode = operationsWithOverloading.Substring(operationsWithOverloading.IndexOf(operation.ToLower()) + 4, 1); @@ -32,7 +32,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo case "sub": case "mul": case "div": - { + { var r1 = new RationalNumber((int[])input["r1"]); var r2 = new RationalNumber((int[])input["r2"]); var e = new RationalNumber((int[])expected); @@ -59,13 +59,14 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo { var x = input["x"].ToString(); var r = new RationalNumber((int[])input["r"]); - var e = expected; + var e = ValueFormatter.Format(expected); var p = precision(e); - assertCodeLine = "Assert.Equal(" + $"{e}, {x}.{operationName}(new RationalNumber({r.Numerator}, {r.Denominator})),{p});"; + assertCodeLine = "Assert.Equal(" + $"{e}, {x}.{operationName}(new RationalNumber({r.Numerator}, {r.Denominator})), {p});"; } break; } - return TemplateRenderer.RenderInline(assertCodeLine, testMethodBody.AssertTemplateParameters); + + return TemplateRenderer.RenderInline(assertCodeLine, testMethodBody.AssertTemplateParameters); } private static int precision(object rawValue) => rawValue.ToString().Split(new char[] { '.' }).Length <= 1 ? 0 : rawValue.ToString().Split(new char[] { '.' })[1].Length; diff --git a/generators/Exercises/Triangle.cs b/generators/Exercises/Triangle.cs index 24c2d34ef8..ed14009270 100644 --- a/generators/Exercises/Triangle.cs +++ b/generators/Exercises/Triangle.cs @@ -16,18 +16,14 @@ protected override void UpdateCanonicalData(CanonicalData canonicalData) else if (data.Property == "scalene") data.Property = "IsScalene"; - data.Input["sides"] = SplitArrayToValues(data.Input["sides"]); - data.SetInputParameters("sides"); - data.UseFullDescriptionPath = true; + data.Input["x"] = data.Input["sides"][0]; + data.Input["y"] = data.Input["sides"][1]; + data.Input["z"] = data.Input["sides"][2]; + data.Input.Remove("sides"); + data.SetInputParameters("x", "y", "z"); + data.UseFullDescriptionPath = true; } } - - private UnescapedValue SplitArrayToValues(IEnumerable input) - { - const string template = "{% for item in {{input}} %}{{item}}{% if forloop.last == false %}, {% endif %}{% endfor %}"; - - return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); - } } } \ No newline at end of file From 48779f25c66c1e0ac9ed9c2e19db7c987d7b1bc5 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 12:01:01 +0200 Subject: [PATCH 10/97] generators: Replace UpdateCanonicalData with UpdateCanonicalDataCase --- generators/Exercises/AllYourBase.cs | 13 ++-- generators/Exercises/Allergies.cs | 15 ++--- generators/Exercises/Alphametics.cs | 17 ++--- generators/Exercises/Anagram.cs | 11 ++-- generators/Exercises/BeerSong.cs | 9 +-- generators/Exercises/BinarySearch.cs | 11 ++-- generators/Exercises/BookStore.cs | 13 ++-- generators/Exercises/Bowling.cs | 21 +++--- generators/Exercises/BracketPush.cs | 9 +-- generators/Exercises/Change.cs | 13 ++-- generators/Exercises/Clock.cs | 37 +++++------ generators/Exercises/CollatzConjecture.cs | 5 +- generators/Exercises/ComplexNumbers.cs | 29 ++++----- generators/Exercises/Connect.cs | 37 +++++------ generators/Exercises/CryptoSquare.cs | 9 +-- generators/Exercises/CustomSet.cs | 47 +++++++------- generators/Exercises/DifferenceOfSquares.cs | 27 ++++---- generators/Exercises/Dominoes.cs | 9 +-- generators/Exercises/Etl.cs | 15 ++--- generators/Exercises/FlattenArray.cs | 19 +++--- generators/Exercises/FoodChain.cs | 15 ++--- generators/Exercises/Forth.cs | 21 +++--- generators/Exercises/Gigasecond.cs | 12 ++-- generators/Exercises/GoCounting.cs | 65 +++++++++---------- generators/Exercises/Grains.cs | 13 ++-- generators/Exercises/Grep.cs | 15 ++--- generators/Exercises/Hamming.cs | 5 +- generators/Exercises/House.cs | 15 ++--- generators/Exercises/KindergartenGarden.cs | 25 ++++--- generators/Exercises/LargestSeriesProduct.cs | 11 ++-- generators/Exercises/Leap.cs | 5 +- generators/Exercises/ListOps.cs | 43 ++++++------ generators/Exercises/Luhn.cs | 5 +- generators/Exercises/Markdown.cs | 9 +-- generators/Exercises/Matrix.cs | 13 ++-- generators/Exercises/Meetup.cs | 25 ++++--- generators/Exercises/Minesweeper.cs | 13 ++-- generators/Exercises/NthPrime.cs | 5 +- generators/Exercises/NucleotideCount.cs | 13 ++-- generators/Exercises/OcrNumbers.cs | 17 ++--- generators/Exercises/PalindromeProducts.cs | 21 +++--- generators/Exercises/PascalsTriangle.cs | 17 ++--- generators/Exercises/PerfectNumbers.cs | 13 ++-- generators/Exercises/PhoneNumber.cs | 9 +-- generators/Exercises/Poker.cs | 11 ++-- generators/Exercises/Pov.cs | 19 +++--- generators/Exercises/Proverb.cs | 11 ++-- generators/Exercises/QueenAttack.cs | 5 +- generators/Exercises/RailFenceCipher.cs | 11 ++-- generators/Exercises/Rectangles.cs | 13 ++-- generators/Exercises/RnaTranscription.cs | 5 +- generators/Exercises/RobotSimulator.cs | 19 +++--- generators/Exercises/RomanNumerals.cs | 9 +-- generators/Exercises/RunLengthEncoding.cs | 8 +-- generators/Exercises/SaddlePoints.cs | 33 +++++----- generators/Exercises/Say.cs | 9 +-- generators/Exercises/ScaleGenerator.cs | 7 +- generators/Exercises/Sieve.cs | 9 +-- generators/Exercises/SimpleCipher.cs | 49 +++++++------- generators/Exercises/SpaceAge.cs | 11 ++-- generators/Exercises/SpiralMatrix.cs | 11 ++-- generators/Exercises/Sublist.cs | 13 ++-- generators/Exercises/SumOfMultiples.cs | 7 +- generators/Exercises/Tournament.cs | 17 ++--- generators/Exercises/Transpose.cs | 15 ++--- generators/Exercises/Triangle.cs | 32 ++++----- generators/Exercises/TwelveDays.cs | 15 ++--- generators/Exercises/TwoBucket.cs | 13 ++-- generators/Exercises/TwoFer.cs | 9 +-- .../Exercises/VariableLengthQuantity.cs | 19 +++--- generators/Exercises/WordCount.cs | 11 ++-- generators/Exercises/WordSearch.cs | 35 +++++----- generators/Exercises/Wordy.cs | 7 +- generators/Exercises/Yacht.cs | 15 ++--- generators/Exercises/ZebraPuzzle.cs | 11 ++-- generators/GeneratorExercise.cs | 6 +- 76 files changed, 514 insertions(+), 722 deletions(-) diff --git a/generators/Exercises/AllYourBase.cs b/generators/Exercises/AllYourBase.cs index 175d44414a..85dbb70c9e 100644 --- a/generators/Exercises/AllYourBase.cs +++ b/generators/Exercises/AllYourBase.cs @@ -6,15 +6,12 @@ namespace Generators.Exercises { public class AllYourBase : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Input["digits"] = ConvertHelper.ToArray(canonicalDataCase.Input["digits"]); - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is Dictionary ? typeof(ArgumentException) : null; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - } + canonicalDataCase.Input["digits"] = ConvertHelper.ToArray(canonicalDataCase.Input["digits"]); + canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is Dictionary ? typeof(ArgumentException) : null; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Allergies.cs index a34ef1ad01..ca6f5e6a40 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Allergies.cs @@ -5,17 +5,14 @@ namespace Generators.Exercises { public class Allergies : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - if (canonicalDataCase.Property == "allergicTo") - canonicalDataCase.Property = "IsAllergicTo"; - else if (canonicalDataCase.Property == "list") - canonicalDataCase.UseVariableForExpected = true; + if (canonicalDataCase.Property == "allergicTo") + canonicalDataCase.Property = "IsAllergicTo"; + else if (canonicalDataCase.Property == "list") + canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters("score"); - } + canonicalDataCase.SetConstructorInputParameters("score"); } protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/Alphametics.cs b/generators/Exercises/Alphametics.cs index de24bf52aa..d3a413ba67 100644 --- a/generators/Exercises/Alphametics.cs +++ b/generators/Exercises/Alphametics.cs @@ -7,18 +7,15 @@ namespace Generators.Exercises { public class Alphametics : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariableForTested = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.UseVariableForTested = true; - if (canonicalDataCase.Expected == null) - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); - else - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase); - } + if (canonicalDataCase.Expected == null) + canonicalDataCase.ExceptionThrown = typeof(ArgumentException); + else + canonicalDataCase.Expected = ConvertExpected(canonicalDataCase); } private static dynamic ConvertExpected(CanonicalDataCase canonicalDataCase) diff --git a/generators/Exercises/Anagram.cs b/generators/Exercises/Anagram.cs index c59d867808..f60ebc417b 100644 --- a/generators/Exercises/Anagram.cs +++ b/generators/Exercises/Anagram.cs @@ -4,14 +4,11 @@ namespace Generators.Exercises { public class Anagram : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters("subject"); - } + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.SetConstructorInputParameters("subject"); } } } \ No newline at end of file diff --git a/generators/Exercises/BeerSong.cs b/generators/Exercises/BeerSong.cs index 8432c65936..7197f0f200 100644 --- a/generators/Exercises/BeerSong.cs +++ b/generators/Exercises/BeerSong.cs @@ -4,13 +4,10 @@ namespace Generators.Exercises { public class BeerSong : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); - } + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); } } } \ No newline at end of file diff --git a/generators/Exercises/BinarySearch.cs b/generators/Exercises/BinarySearch.cs index 0835fc4510..66ad1a369a 100644 --- a/generators/Exercises/BinarySearch.cs +++ b/generators/Exercises/BinarySearch.cs @@ -6,14 +6,11 @@ namespace Generators.Exercises { public class BinarySearch : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Input["array"] = ConvertHelper.ToArray(canonicalDataCase.Input["array"]); - canonicalDataCase.UseVariablesForConstructorParameters = true; - canonicalDataCase.SetConstructorInputParameters("array"); - } + canonicalDataCase.Input["array"] = ConvertHelper.ToArray(canonicalDataCase.Input["array"]); + canonicalDataCase.UseVariablesForConstructorParameters = true; + canonicalDataCase.SetConstructorInputParameters("array"); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/BookStore.cs b/generators/Exercises/BookStore.cs index f5bf9f6547..4fc2e32148 100644 --- a/generators/Exercises/BookStore.cs +++ b/generators/Exercises/BookStore.cs @@ -6,15 +6,12 @@ namespace Generators.Exercises { public class BookStore : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Expected = canonicalDataCase.Expected / 100.0f; - canonicalDataCase.Input["basket"] = ConvertHelper.ToArray(canonicalDataCase.Input["basket"]); - canonicalDataCase.SetInputParameters("basket"); - canonicalDataCase.UseVariablesForInput = true; - } + canonicalDataCase.Expected = canonicalDataCase.Expected / 100.0f; + canonicalDataCase.Input["basket"] = ConvertHelper.ToArray(canonicalDataCase.Input["basket"]); + canonicalDataCase.SetInputParameters("basket"); + canonicalDataCase.UseVariablesForInput = true; } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index 7a8a703541..1834f65676 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -10,21 +10,18 @@ public class Bowling : GeneratorExercise { private const string PreviousRolls = "previousRolls"; - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) + if (!(canonicalDataCase.Expected is int)) { - if (!(canonicalDataCase.Expected is int)) - { - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); - } - else - { - canonicalDataCase.UseVariableForTested = true; - - } - canonicalDataCase.SetInputParameters(); + canonicalDataCase.ExceptionThrown = typeof(ArgumentException); + } + else + { + canonicalDataCase.UseVariableForTested = true; } + + canonicalDataCase.SetInputParameters(); } protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodBody) diff --git a/generators/Exercises/BracketPush.cs b/generators/Exercises/BracketPush.cs index 086b3c2afa..92eae2005b 100644 --- a/generators/Exercises/BracketPush.cs +++ b/generators/Exercises/BracketPush.cs @@ -4,13 +4,10 @@ namespace Generators.Exercises { public class BracketPush : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Input["value"] = canonicalDataCase.Input["value"].Replace("\\", "\\\\"); - canonicalDataCase.UseVariablesForInput = true; - } + canonicalDataCase.Input["value"] = canonicalDataCase.Input["value"].Replace("\\", "\\\\"); + canonicalDataCase.UseVariablesForInput = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Change.cs b/generators/Exercises/Change.cs index 374ce0c4d1..59e9b68a69 100644 --- a/generators/Exercises/Change.cs +++ b/generators/Exercises/Change.cs @@ -5,16 +5,13 @@ namespace Generators.Exercises { public class Change : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; - if (canonicalDataCase.Expected is int) - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); - } + if (canonicalDataCase.Expected is int) + canonicalDataCase.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Clock.cs index e4f5caa3d4..e3fcb980a2 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Clock.cs @@ -16,30 +16,27 @@ public class Clock : GeneratorExercise private const string PropertyEquals = "equals"; private const string PropertyToString = "to_string"; - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) + if (canonicalDataCase.Property != PropertyEqual) { - if (canonicalDataCase.Property != PropertyEqual) - { - canonicalDataCase.SetConstructorInputParameters(ParamHour, ParamMinute); - } - else - { - canonicalDataCase.SetConstructorInputParameters(ParamClock2); + canonicalDataCase.SetConstructorInputParameters(ParamHour, ParamMinute); + } + else + { + canonicalDataCase.SetConstructorInputParameters(ParamClock2); - var result = (Dictionary)canonicalDataCase.Input[ParamClock1]; - canonicalDataCase.Input[ParamClock1] = new UnescapedValue($"new Clock({result[ParamHour]}, {result[ParamMinute]})"); - } + var result = (Dictionary)canonicalDataCase.Input[ParamClock1]; + canonicalDataCase.Input[ParamClock1] = new UnescapedValue($"new Clock({result[ParamHour]}, {result[ParamMinute]})"); + } - if (canonicalDataCase.Property == PropertyCreate) - { - canonicalDataCase.Property = PropertyToString; - } - else if (canonicalDataCase.Property == PropertyEqual) - { - canonicalDataCase.Property = PropertyEquals; - } + if (canonicalDataCase.Property == PropertyCreate) + { + canonicalDataCase.Property = PropertyToString; + } + else if (canonicalDataCase.Property == PropertyEqual) + { + canonicalDataCase.Property = PropertyEquals; } } diff --git a/generators/Exercises/CollatzConjecture.cs b/generators/Exercises/CollatzConjecture.cs index 88bc717c01..1e6539d9af 100644 --- a/generators/Exercises/CollatzConjecture.cs +++ b/generators/Exercises/CollatzConjecture.cs @@ -5,10 +5,9 @@ namespace Generators.Exercises { public class CollatzConjecture : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - canonicalDataCase.ExceptionThrown = canonicalDataCase.Input["number"] <= 0 ? typeof(ArgumentException) : null; + canonicalDataCase.ExceptionThrown = canonicalDataCase.Input["number"] <= 0 ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 619bc77f31..c2669e27eb 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -9,26 +9,23 @@ namespace Generators.Exercises { public class ComplexNumbers : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) - { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Exercise = "complex-number"; - canonicalDataCase.UseVariableForExpected = IsComplexNumber(canonicalDataCase.Expected); - canonicalDataCase.Expected = ConvertToType(canonicalDataCase.Expected); + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + { + canonicalDataCase.Exercise = "complex-number"; + canonicalDataCase.UseVariableForExpected = IsComplexNumber(canonicalDataCase.Expected); + canonicalDataCase.Expected = ConvertToType(canonicalDataCase.Expected); - var constructorParamName = canonicalDataCase.Input.ContainsKey("z") ? "z" : "z1"; - canonicalDataCase.Input["real"] = ConvertMathDouble(canonicalDataCase.Input[constructorParamName][0]); - canonicalDataCase.Input["imaginary"] = ConvertMathDouble(canonicalDataCase.Input[constructorParamName][1]); + var constructorParamName = canonicalDataCase.Input.ContainsKey("z") ? "z" : "z1"; + canonicalDataCase.Input["real"] = ConvertMathDouble(canonicalDataCase.Input[constructorParamName][0]); + canonicalDataCase.Input["imaginary"] = ConvertMathDouble(canonicalDataCase.Input[constructorParamName][1]); - canonicalDataCase.SetInputParameters(GetInputParameters(canonicalDataCase, constructorParamName)); - canonicalDataCase.SetConstructorInputParameters("real", "imaginary"); + canonicalDataCase.SetInputParameters(GetInputParameters(canonicalDataCase, constructorParamName)); + canonicalDataCase.SetConstructorInputParameters("real", "imaginary"); - var keys = canonicalDataCase.Input.Keys.ToArray(); + var keys = canonicalDataCase.Input.Keys.ToArray(); - foreach (var key in keys) - canonicalDataCase.Input[key] = ConvertToType(canonicalDataCase.Input[key]); - } + foreach (var key in keys) + canonicalDataCase.Input[key] = ConvertToType(canonicalDataCase.Input[key]); } private static string[] GetInputParameters(CanonicalDataCase canonicalDataCase, string constructorParamName) diff --git a/generators/Exercises/Connect.cs b/generators/Exercises/Connect.cs index 4176151aa0..fc7cbbe25c 100644 --- a/generators/Exercises/Connect.cs +++ b/generators/Exercises/Connect.cs @@ -5,28 +5,25 @@ namespace Generators.Exercises { public class Connect : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForConstructorParameters = true; - canonicalDataCase.SetConstructorInputParameters("board"); - canonicalDataCase.Property = "result"; - canonicalDataCase.Input["board"] = ToMultiLineString(canonicalDataCase.Input["board"]); + canonicalDataCase.UseVariablesForConstructorParameters = true; + canonicalDataCase.SetConstructorInputParameters("board"); + canonicalDataCase.Property = "result"; + canonicalDataCase.Input["board"] = ToMultiLineString(canonicalDataCase.Input["board"]); - //convert to enum - switch (canonicalDataCase.Expected) - { - case "X": - canonicalDataCase.Expected = new UnescapedValue("ConnectWinner.Black"); - break; - case "O": - canonicalDataCase.Expected = new UnescapedValue("ConnectWinner.White"); - break; - case "": - canonicalDataCase.Expected = new UnescapedValue("ConnectWinner.None"); - break; - } + //convert to enum + switch (canonicalDataCase.Expected) + { + case "X": + canonicalDataCase.Expected = new UnescapedValue("ConnectWinner.Black"); + break; + case "O": + canonicalDataCase.Expected = new UnescapedValue("ConnectWinner.White"); + break; + case "": + canonicalDataCase.Expected = new UnescapedValue("ConnectWinner.None"); + break; } } diff --git a/generators/Exercises/CryptoSquare.cs b/generators/Exercises/CryptoSquare.cs index 5ddb54e76f..92461c9c4d 100644 --- a/generators/Exercises/CryptoSquare.cs +++ b/generators/Exercises/CryptoSquare.cs @@ -4,13 +4,10 @@ namespace Generators.Exercises { public class CryptoSquare : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - } + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; } } } \ No newline at end of file diff --git a/generators/Exercises/CustomSet.cs b/generators/Exercises/CustomSet.cs index a3e3b4f89d..88eeede4cc 100644 --- a/generators/Exercises/CustomSet.cs +++ b/generators/Exercises/CustomSet.cs @@ -5,39 +5,36 @@ namespace Generators.Exercises { public class CustomSet : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariablesForInput = true; - if (canonicalDataCase.Input.ContainsKey("set")) + if (canonicalDataCase.Input.ContainsKey("set")) + { + if (!(canonicalDataCase.Input["set"] is int[])) { - if (!(canonicalDataCase.Input["set"] is int[])) - { - canonicalDataCase.Input["set"] = new UnescapedValue(""); - } - - canonicalDataCase.SetConstructorInputParameters("set"); + canonicalDataCase.Input["set"] = new UnescapedValue(""); } - else + + canonicalDataCase.SetConstructorInputParameters("set"); + } + else + { + if (!(canonicalDataCase.Input["set1"] is int[])) { - if (!(canonicalDataCase.Input["set1"] is int[])) - { - canonicalDataCase.Input["set1"] = new UnescapedValue(""); - } - - canonicalDataCase.SetConstructorInputParameters("set1"); - canonicalDataCase.Input["set2"] = ConvertCustomSet(canonicalDataCase.Input["set2"]); - - if (canonicalDataCase.Property == "equal") - { - canonicalDataCase.Property = "Equals"; - } + canonicalDataCase.Input["set1"] = new UnescapedValue(""); } - canonicalDataCase.Expected = ConvertCustomSet(canonicalDataCase.Expected); + canonicalDataCase.SetConstructorInputParameters("set1"); + canonicalDataCase.Input["set2"] = ConvertCustomSet(canonicalDataCase.Input["set2"]); + + if (canonicalDataCase.Property == "equal") + { + canonicalDataCase.Property = "Equals"; + } } + + canonicalDataCase.Expected = ConvertCustomSet(canonicalDataCase.Expected); } private static dynamic ConvertCustomSet(dynamic value) diff --git a/generators/Exercises/DifferenceOfSquares.cs b/generators/Exercises/DifferenceOfSquares.cs index 857247b6bb..29e24711af 100644 --- a/generators/Exercises/DifferenceOfSquares.cs +++ b/generators/Exercises/DifferenceOfSquares.cs @@ -4,21 +4,20 @@ namespace Generators.Exercises { public class DifferenceOfSquares : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - switch(canonicalDataCase.Property) - { - case "squareOfSum": - canonicalDataCase.Property = "CalculateSquareOfSum"; - break; - case "sumOfSquares": - canonicalDataCase.Property = "CalculateSumOfSquares"; - break; - case "differenceOfSquares": - canonicalDataCase.Property = "CalculateDifferenceOfSquares"; - break; - } + switch(canonicalDataCase.Property) + { + case "squareOfSum": + canonicalDataCase.Property = "CalculateSquareOfSum"; + break; + case "sumOfSquares": + canonicalDataCase.Property = "CalculateSumOfSquares"; + break; + case "differenceOfSquares": + canonicalDataCase.Property = "CalculateDifferenceOfSquares"; + break; + } } } } diff --git a/generators/Exercises/Dominoes.cs b/generators/Exercises/Dominoes.cs index d66b1e44e5..d6025857b0 100644 --- a/generators/Exercises/Dominoes.cs +++ b/generators/Exercises/Dominoes.cs @@ -9,13 +9,10 @@ namespace Generators.Exercises { public class Dominoes : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.Input["dominoes"] = ConvertInput(canonicalDataCase.Input["dominoes"]); - } + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.Input["dominoes"] = ConvertInput(canonicalDataCase.Input["dominoes"]); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Tuple).Namespace }; diff --git a/generators/Exercises/Etl.cs b/generators/Exercises/Etl.cs index b9508bf9dd..57977c9082 100644 --- a/generators/Exercises/Etl.cs +++ b/generators/Exercises/Etl.cs @@ -6,16 +6,13 @@ namespace Generators.Exercises { public class Etl : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Input = ConvertInput(canonicalDataCase.Input); - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); - canonicalDataCase.SetInputParameters("input"); - } + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Input = ConvertInput(canonicalDataCase.Input); + canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); + canonicalDataCase.SetInputParameters("input"); } private static dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/FlattenArray.cs b/generators/Exercises/FlattenArray.cs index 724d5677d0..2fe998c988 100644 --- a/generators/Exercises/FlattenArray.cs +++ b/generators/Exercises/FlattenArray.cs @@ -5,21 +5,18 @@ namespace Generators.Exercises { public class FlattenArray : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; - var stringInput = canonicalDataCase.Input["array"].ToString(); + var stringInput = canonicalDataCase.Input["array"].ToString(); - // We skip reformatting of pure int arrays. - if (stringInput.Contains("System.Int32")) - continue; + // We skip reformatting of pure int arrays. + if (stringInput.Contains("System.Int32")) + return; - canonicalDataCase.Input["array"] = new UnescapedValue(ToProperObjArray(stringInput)); - } + canonicalDataCase.Input["array"] = new UnescapedValue(ToProperObjArray(stringInput)); } private string ToProperObjArray(string input) diff --git a/generators/Exercises/FoodChain.cs b/generators/Exercises/FoodChain.cs index dd8bd01c4d..b1677af21d 100644 --- a/generators/Exercises/FoodChain.cs +++ b/generators/Exercises/FoodChain.cs @@ -4,17 +4,14 @@ namespace Generators.Exercises { public class FoodChain : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); - canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); + canonicalDataCase.UseVariableForExpected = true; - if (canonicalDataCase.Input["startVerse"] == canonicalDataCase.Input["endVerse"]) - { - canonicalDataCase.SetInputParameters("startVerse"); - } + if (canonicalDataCase.Input["startVerse"] == canonicalDataCase.Input["endVerse"]) + { + canonicalDataCase.SetInputParameters("startVerse"); } } } diff --git a/generators/Exercises/Forth.cs b/generators/Exercises/Forth.cs index 1f4d3ee64f..384ea67bd6 100644 --- a/generators/Exercises/Forth.cs +++ b/generators/Exercises/Forth.cs @@ -5,20 +5,17 @@ namespace Generators.Exercises { public class Forth : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseFullDescriptionPath = true; + canonicalDataCase.UseFullDescriptionPath = true; - if (canonicalDataCase.Expected == null) - { - canonicalDataCase.ExceptionThrown = typeof(InvalidOperationException); - } - else - { - canonicalDataCase.Expected = string.Join(" ", canonicalDataCase.Expected); - } + if (canonicalDataCase.Expected == null) + { + canonicalDataCase.ExceptionThrown = typeof(InvalidOperationException); + } + else + { + canonicalDataCase.Expected = string.Join(" ", canonicalDataCase.Expected); } } } diff --git a/generators/Exercises/Gigasecond.cs b/generators/Exercises/Gigasecond.cs index d3a21635d7..210bb2d3ab 100644 --- a/generators/Exercises/Gigasecond.cs +++ b/generators/Exercises/Gigasecond.cs @@ -7,15 +7,11 @@ namespace Generators.Exercises { public class Gigasecond : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - var input = DateTime.Parse(canonicalDataCase.Input["birthdate"].ToString()); - canonicalDataCase.Input["birthdate"] = new UnescapedValue(FormatDateTime(input)); - - canonicalDataCase.Expected = new UnescapedValue(FormatDateTime((DateTime)canonicalDataCase.Expected)); - } + var input = DateTime.Parse(canonicalDataCase.Input["birthdate"].ToString()); + canonicalDataCase.Input["birthdate"] = new UnescapedValue(FormatDateTime(input)); + canonicalDataCase.Expected = new UnescapedValue(FormatDateTime((DateTime)canonicalDataCase.Expected)); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(DateTime).Namespace }; diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index c10b1535b5..423ddfbcda 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -10,49 +10,46 @@ namespace Generators.Exercises { public class GoCounting : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariablesForConstructorParameters = true; - canonicalDataCase.UseVariableForTested = true; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.UseVariablesForConstructorParameters = true; + canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.Input["board"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["board"]); - canonicalDataCase.SetConstructorInputParameters("board"); + canonicalDataCase.Input["board"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["board"]); + canonicalDataCase.SetConstructorInputParameters("board"); - if (canonicalDataCase.Property == "territory") - { - canonicalDataCase.Input["coordinate"] = (canonicalDataCase.Input["x"], canonicalDataCase.Input["y"]); - canonicalDataCase.SetInputParameters("coordinate"); + if (canonicalDataCase.Property == "territory") + { + canonicalDataCase.Input["coordinate"] = (canonicalDataCase.Input["x"], canonicalDataCase.Input["y"]); + canonicalDataCase.SetInputParameters("coordinate"); - if (canonicalDataCase.Expected.ContainsKey("error")) - { - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); - } - else - { - var owner = FormatOwner(canonicalDataCase.Expected["owner"]); - var territory = FormatTerritory(canonicalDataCase.Expected["territory"]); - canonicalDataCase.Expected = (new UnescapedValue(owner), territory); - } + if (canonicalDataCase.Expected.ContainsKey("error")) + { + canonicalDataCase.ExceptionThrown = typeof(ArgumentException); } else { - var expected = new[] - { - "new Dictionary[]>", - "{", - $" [Owner.Black] = {FormatTerritory(canonicalDataCase.Expected["territoryBlack"])},", - $" [Owner.White] = {FormatTerritory(canonicalDataCase.Expected["territoryWhite"])},", - $" [Owner.None] = {FormatTerritory(canonicalDataCase.Expected["territoryNone"])}", - "}" - }; - - canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); + var owner = FormatOwner(canonicalDataCase.Expected["owner"]); + var territory = FormatTerritory(canonicalDataCase.Expected["territory"]); + canonicalDataCase.Expected = (new UnescapedValue(owner), territory); } } + else + { + var expected = new[] + { + "new Dictionary[]>", + "{", + $" [Owner.Black] = {FormatTerritory(canonicalDataCase.Expected["territoryBlack"])},", + $" [Owner.White] = {FormatTerritory(canonicalDataCase.Expected["territoryWhite"])},", + $" [Owner.None] = {FormatTerritory(canonicalDataCase.Expected["territoryNone"])}", + "}" + }; + + canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); + } } protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/Grains.cs b/generators/Exercises/Grains.cs index b3a4364ce6..95afb17736 100644 --- a/generators/Exercises/Grains.cs +++ b/generators/Exercises/Grains.cs @@ -5,15 +5,12 @@ namespace Generators.Exercises { public class Grains : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - if (ShouldThrowException(canonicalDataCase.Expected)) - canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); - else - canonicalDataCase.Expected = (ulong)canonicalDataCase.Expected; - } + if (ShouldThrowException(canonicalDataCase.Expected)) + canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); + else + canonicalDataCase.Expected = (ulong)canonicalDataCase.Expected; } private static bool ShouldThrowException(dynamic value) => value is int i && i == -1; diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index 84532f0842..3a5fa083a7 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -8,16 +8,13 @@ namespace Generators.Exercises { public class Grep : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = "Match"; - canonicalDataCase.Input["flags"] = string.Join(" ", canonicalDataCase.Input["flags"]); - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - } + canonicalDataCase.Property = "Match"; + canonicalDataCase.Input["flags"] = string.Join(" ", canonicalDataCase.Input["flags"]); + canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; } private static dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/Hamming.cs b/generators/Exercises/Hamming.cs index 2d6c7ed1e2..9be6015fec 100644 --- a/generators/Exercises/Hamming.cs +++ b/generators/Exercises/Hamming.cs @@ -5,10 +5,9 @@ namespace Generators.Exercises { public class Hamming : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is int ? null : typeof(ArgumentException); + canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is int ? null : typeof(ArgumentException); } } } diff --git a/generators/Exercises/House.cs b/generators/Exercises/House.cs index 01ab6c12be..4776fb7d8d 100644 --- a/generators/Exercises/House.cs +++ b/generators/Exercises/House.cs @@ -4,17 +4,14 @@ namespace Generators.Exercises { public class House : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); - if (canonicalDataCase.Input["startVerse"] == canonicalDataCase.Input["endVerse"]) - { - canonicalDataCase.SetInputParameters("startVerse"); - } + if (canonicalDataCase.Input["startVerse"] == canonicalDataCase.Input["endVerse"]) + { + canonicalDataCase.SetInputParameters("startVerse"); } } } diff --git a/generators/Exercises/KindergartenGarden.cs b/generators/Exercises/KindergartenGarden.cs index c00a6507b1..7cb8400bdf 100644 --- a/generators/Exercises/KindergartenGarden.cs +++ b/generators/Exercises/KindergartenGarden.cs @@ -8,23 +8,20 @@ namespace Generators.Exercises { public class KindergartenGarden : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.TestedMethodType = TestedMethodType.Instance; - canonicalDataCase.UseFullDescriptionPath = true; + canonicalDataCase.TestedMethodType = TestedMethodType.Instance; + canonicalDataCase.UseFullDescriptionPath = true; - if (canonicalDataCase.Input.ContainsKey("students")) - canonicalDataCase.SetConstructorInputParameters("diagram", "students"); - else - canonicalDataCase.SetConstructorInputParameters("diagram"); + if (canonicalDataCase.Input.ContainsKey("students")) + canonicalDataCase.SetConstructorInputParameters("diagram", "students"); + else + canonicalDataCase.SetConstructorInputParameters("diagram"); - var plants = (IEnumerable)canonicalDataCase.Expected; - canonicalDataCase.Expected = plants - .Select(x => new UnescapedValue($"Plant.{x.Humanize()}")) - .ToArray(); - } + var plants = (IEnumerable)canonicalDataCase.Expected; + canonicalDataCase.Expected = plants + .Select(x => new UnescapedValue($"Plant.{x.Humanize()}")) + .ToArray(); } } } \ No newline at end of file diff --git a/generators/Exercises/LargestSeriesProduct.cs b/generators/Exercises/LargestSeriesProduct.cs index 48fb03b289..1c44de0093 100644 --- a/generators/Exercises/LargestSeriesProduct.cs +++ b/generators/Exercises/LargestSeriesProduct.cs @@ -4,15 +4,12 @@ namespace Generators.Exercises { public class LargestSeriesProduct : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = "GetLargestProduct"; + canonicalDataCase.Property = "GetLargestProduct"; - var caseInputLessThanZero = (long)canonicalDataCase.Expected == -1; - canonicalDataCase.ExceptionThrown = caseInputLessThanZero ? typeof(System.ArgumentException) : null; - } + var caseInputLessThanZero = (long)canonicalDataCase.Expected == -1; + canonicalDataCase.ExceptionThrown = caseInputLessThanZero ? typeof(System.ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/Leap.cs b/generators/Exercises/Leap.cs index 78567f7d4c..891b364bd7 100644 --- a/generators/Exercises/Leap.cs +++ b/generators/Exercises/Leap.cs @@ -4,10 +4,9 @@ namespace Generators.Exercises { public class Leap : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - canonicalDataCase.Property = "IsLeapYear"; + canonicalDataCase.Property = "IsLeapYear"; } } } \ No newline at end of file diff --git a/generators/Exercises/ListOps.cs b/generators/Exercises/ListOps.cs index 6d2c65a3ee..552f1fb8a9 100644 --- a/generators/Exercises/ListOps.cs +++ b/generators/Exercises/ListOps.cs @@ -10,36 +10,33 @@ namespace Generators.Exercises { public class ListOps : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseFullDescriptionPath = true; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = !(canonicalDataCase.Expected is int); + canonicalDataCase.UseFullDescriptionPath = true; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = !(canonicalDataCase.Expected is int); - if (canonicalDataCase.Input.TryGetValue("list", out var list)) - canonicalDataCase.Input["list"] = ConvertToList(list); + if (canonicalDataCase.Input.TryGetValue("list", out var list)) + canonicalDataCase.Input["list"] = ConvertToList(list); - if (canonicalDataCase.Input.TryGetValue("list1", out var list1)) - canonicalDataCase.Input["list1"] = ConvertToList(list1); + if (canonicalDataCase.Input.TryGetValue("list1", out var list1)) + canonicalDataCase.Input["list1"] = ConvertToList(list1); - if (canonicalDataCase.Input.TryGetValue("list2", out var list2)) - canonicalDataCase.Input["list2"] = ConvertToList(list2); + if (canonicalDataCase.Input.TryGetValue("list2", out var list2)) + canonicalDataCase.Input["list2"] = ConvertToList(list2); - if (canonicalDataCase.Input.TryGetValue("lists", out var lists)) - canonicalDataCase.Input["lists"] = ConvertToNestedList(lists, true); + if (canonicalDataCase.Input.TryGetValue("lists", out var lists)) + canonicalDataCase.Input["lists"] = ConvertToNestedList(lists, true); - if (canonicalDataCase.Input.TryGetValue("function", out var function)) - canonicalDataCase.Input["function"] = ConvertToFunction(canonicalDataCase.Property, function); + if (canonicalDataCase.Input.TryGetValue("function", out var function)) + canonicalDataCase.Input["function"] = ConvertToFunction(canonicalDataCase.Property, function); - if (canonicalDataCase.Expected is IEnumerable) - { - if (canonicalDataCase.Input.ContainsKey("lists")) - canonicalDataCase.Expected = ConvertToNestedList(canonicalDataCase.Expected, false); - else - canonicalDataCase.Expected = ConvertToList(canonicalDataCase.Expected); - } + if (canonicalDataCase.Expected is IEnumerable) + { + if (canonicalDataCase.Input.ContainsKey("lists")) + canonicalDataCase.Expected = ConvertToNestedList(canonicalDataCase.Expected, false); + else + canonicalDataCase.Expected = ConvertToList(canonicalDataCase.Expected); } } diff --git a/generators/Exercises/Luhn.cs b/generators/Exercises/Luhn.cs index d6f6295d73..57d0abc539 100644 --- a/generators/Exercises/Luhn.cs +++ b/generators/Exercises/Luhn.cs @@ -4,10 +4,9 @@ namespace Generators.Exercises { public class Luhn : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - canonicalDataCase.Property = "IsValid"; + canonicalDataCase.Property = "IsValid"; } } } diff --git a/generators/Exercises/Markdown.cs b/generators/Exercises/Markdown.cs index f672275712..53b91bd10d 100644 --- a/generators/Exercises/Markdown.cs +++ b/generators/Exercises/Markdown.cs @@ -5,13 +5,10 @@ namespace Generators.Exercises { public class Markdown : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - } + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; } protected override TestMethod CreateTestMethod(CanonicalDataCase canonicalDataCase, int index) diff --git a/generators/Exercises/Matrix.cs b/generators/Exercises/Matrix.cs index 41b50ceb19..fff768cf71 100644 --- a/generators/Exercises/Matrix.cs +++ b/generators/Exercises/Matrix.cs @@ -4,15 +4,12 @@ namespace Generators.Exercises { public class Matrix : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Properties["string"] = canonicalDataCase.Properties["input"]["string"]; - canonicalDataCase.SetConstructorInputParameters("string"); - canonicalDataCase.Properties["index"] = canonicalDataCase.Properties["input"]["index"]; - canonicalDataCase.SetInputParameters("index"); - } + canonicalDataCase.Properties["string"] = canonicalDataCase.Properties["input"]["string"]; + canonicalDataCase.SetConstructorInputParameters("string"); + canonicalDataCase.Properties["index"] = canonicalDataCase.Properties["input"]["index"]; + canonicalDataCase.SetInputParameters("index"); } } } diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index b66f290ac6..59590a5fdd 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -15,22 +15,19 @@ public class Meetup : GeneratorExercise private const string PropertyDay = "Day"; - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = PropertyDay; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters(ParamMonth, ParamYear); - canonicalDataCase.SetInputParameters(ParamDayOfWeek, ParamWeek); + canonicalDataCase.Property = PropertyDay; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.SetConstructorInputParameters(ParamMonth, ParamYear); + canonicalDataCase.SetInputParameters(ParamDayOfWeek, ParamWeek); - canonicalDataCase.Input[ParamYear] = canonicalDataCase.Input[ParamYear]; - canonicalDataCase.Input[ParamMonth] = canonicalDataCase.Input[ParamMonth]; - canonicalDataCase.Input[ParamWeek] = - new UnescapedValue($"Schedule.{((string)canonicalDataCase.Input[ParamWeek]).Transform(To.SentenceCase)}"); - canonicalDataCase.Input[ParamDayOfWeek] = - new UnescapedValue($"DayOfWeek.{((string)canonicalDataCase.Input[ParamDayOfWeek]).Transform(To.SentenceCase)}"); - } + canonicalDataCase.Input[ParamYear] = canonicalDataCase.Input[ParamYear]; + canonicalDataCase.Input[ParamMonth] = canonicalDataCase.Input[ParamMonth]; + canonicalDataCase.Input[ParamWeek] = + new UnescapedValue($"Schedule.{((string)canonicalDataCase.Input[ParamWeek]).Transform(To.SentenceCase)}"); + canonicalDataCase.Input[ParamDayOfWeek] = + new UnescapedValue($"DayOfWeek.{((string)canonicalDataCase.Input[ParamDayOfWeek]).Transform(To.SentenceCase)}"); } protected override String RenderTestMethodBodyAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/Minesweeper.cs b/generators/Exercises/Minesweeper.cs index 9fe6cfa659..f3378aeee2 100644 --- a/generators/Exercises/Minesweeper.cs +++ b/generators/Exercises/Minesweeper.cs @@ -8,16 +8,13 @@ namespace Generators.Exercises { public class Minesweeper : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Input["minefield"] = ToMultiLineString(canonicalDataCase.Input["minefield"]); - canonicalDataCase.Expected = ToMultiLineString(canonicalDataCase.Expected); - } + canonicalDataCase.Input["minefield"] = ToMultiLineString(canonicalDataCase.Input["minefield"]); + canonicalDataCase.Expected = ToMultiLineString(canonicalDataCase.Expected); } private UnescapedValue ToMultiLineString(JArray input) => new UnescapedValue("Array.Empty()"); diff --git a/generators/Exercises/NthPrime.cs b/generators/Exercises/NthPrime.cs index bcd476ce6f..85c0df11da 100644 --- a/generators/Exercises/NthPrime.cs +++ b/generators/Exercises/NthPrime.cs @@ -6,10 +6,9 @@ namespace Generators.Exercises { public class NthPrime : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is Dictionary ? typeof(ArgumentOutOfRangeException) : null; + canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is Dictionary ? typeof(ArgumentOutOfRangeException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index d139e73966..a9b3d3c88b 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -7,16 +7,13 @@ namespace Generators.Exercises { public class NucleotideCount : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) + if (!((Dictionary)canonicalDataCase.Expected).ContainsKey("error")) { - if (!((Dictionary)canonicalDataCase.Expected).ContainsKey("error")) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters("strand"); - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); - } + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.SetConstructorInputParameters("strand"); + canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); } } diff --git a/generators/Exercises/OcrNumbers.cs b/generators/Exercises/OcrNumbers.cs index b7bfde739b..69b4fe5a5f 100644 --- a/generators/Exercises/OcrNumbers.cs +++ b/generators/Exercises/OcrNumbers.cs @@ -8,16 +8,13 @@ namespace Generators.Exercises { public class OcrNumbers : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) - { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.ExceptionThrown = (canonicalDataCase.Expected is int && canonicalDataCase.Expected <= 0) ? typeof(ArgumentException) : null; - canonicalDataCase.Input["rows"] = ToDigitStringRepresentation(canonicalDataCase.Input["rows"]); - canonicalDataCase.Expected = canonicalDataCase.Expected.ToString(); - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.UseVariablesForInput = true; - } + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + { + canonicalDataCase.ExceptionThrown = (canonicalDataCase.Expected is int && canonicalDataCase.Expected <= 0) ? typeof(ArgumentException) : null; + canonicalDataCase.Input["rows"] = ToDigitStringRepresentation(canonicalDataCase.Input["rows"]); + canonicalDataCase.Expected = canonicalDataCase.Expected.ToString(); + canonicalDataCase.UseVariableForTested = true; + canonicalDataCase.UseVariablesForInput = true; } private UnescapedValue ToMultiLineString(JArray input) diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/PalindromeProducts.cs index 9b714a9976..7880e687de 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/PalindromeProducts.cs @@ -8,20 +8,17 @@ namespace Generators.Exercises { public class PalindromeProducts : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) + if (canonicalDataCase.Expected.ContainsKey("error")) { - if (canonicalDataCase.Expected.ContainsKey("error")) - { - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); - } - else - { - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = (canonicalDataCase.Expected["value"], FormatCoordinates(canonicalDataCase.Expected["factors"])); - } + canonicalDataCase.ExceptionThrown = typeof(ArgumentException); + } + else + { + canonicalDataCase.UseVariableForTested = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Expected = (canonicalDataCase.Expected["value"], FormatCoordinates(canonicalDataCase.Expected["factors"])); } } diff --git a/generators/Exercises/PascalsTriangle.cs b/generators/Exercises/PascalsTriangle.cs index 9944ccdfbc..ccdee62da4 100644 --- a/generators/Exercises/PascalsTriangle.cs +++ b/generators/Exercises/PascalsTriangle.cs @@ -6,17 +6,14 @@ namespace Generators.Exercises { public class PascalsTriangle : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Property = "calculate"; - if (canonicalDataCase.Expected is JArray jArray) - canonicalDataCase.Expected = jArray.ToObject(); - else - canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); - } + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Property = "calculate"; + if (canonicalDataCase.Expected is JArray jArray) + canonicalDataCase.Expected = jArray.ToObject(); + else + canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/PerfectNumbers.cs b/generators/Exercises/PerfectNumbers.cs index 8d0a93865d..fa7ff0da45 100644 --- a/generators/Exercises/PerfectNumbers.cs +++ b/generators/Exercises/PerfectNumbers.cs @@ -7,15 +7,12 @@ namespace Generators.Exercises { public class PerfectNumbers : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - if (canonicalDataCase.Expected is string classificationType) - canonicalDataCase.Expected = new UnescapedValue($"Classification.{classificationType.Transform(To.SentenceCase)}"); - else - canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); - } + if (canonicalDataCase.Expected is string classificationType) + canonicalDataCase.Expected = new UnescapedValue($"Classification.{classificationType.Transform(To.SentenceCase)}"); + else + canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/PhoneNumber.cs b/generators/Exercises/PhoneNumber.cs index 33a22dd6c9..9e42bff160 100644 --- a/generators/Exercises/PhoneNumber.cs +++ b/generators/Exercises/PhoneNumber.cs @@ -5,13 +5,10 @@ namespace Generators.Exercises { public class PhoneNumber : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is null ? typeof(ArgumentException) : null; - } + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is null ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/Poker.cs b/generators/Exercises/Poker.cs index d296ffaa6b..b4231563dd 100644 --- a/generators/Exercises/Poker.cs +++ b/generators/Exercises/Poker.cs @@ -4,14 +4,11 @@ namespace Generators.Exercises { public class Poker : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariableForTested = true; - } + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.UseVariableForTested = true; } } } diff --git a/generators/Exercises/Pov.cs b/generators/Exercises/Pov.cs index 61011491ae..cf95eec5e3 100644 --- a/generators/Exercises/Pov.cs +++ b/generators/Exercises/Pov.cs @@ -8,20 +8,17 @@ namespace Generators.Exercises { public class Pov : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is null ? typeof(ArgumentException) : null; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is null ? typeof(ArgumentException) : null; - canonicalDataCase.Input["tree"] = RenderTree(canonicalDataCase.Input["tree"]); + canonicalDataCase.Input["tree"] = RenderTree(canonicalDataCase.Input["tree"]); - if (canonicalDataCase.Property == "fromPov") - { - canonicalDataCase.Expected = RenderTree(canonicalDataCase.Expected); - } + if (canonicalDataCase.Property == "fromPov") + { + canonicalDataCase.Expected = RenderTree(canonicalDataCase.Expected); } } diff --git a/generators/Exercises/Proverb.cs b/generators/Exercises/Proverb.cs index b8f99b6ce8..aa0baf8675 100644 --- a/generators/Exercises/Proverb.cs +++ b/generators/Exercises/Proverb.cs @@ -6,14 +6,11 @@ namespace Generators.Exercises { public class Proverb : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Input["strings"] = ConvertHelper.ToArray(canonicalDataCase.Input["strings"]); - canonicalDataCase.Expected = ConvertHelper.ToArray(canonicalDataCase.Expected); - } + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Input["strings"] = ConvertHelper.ToArray(canonicalDataCase.Input["strings"]); + canonicalDataCase.Expected = ConvertHelper.ToArray(canonicalDataCase.Expected); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/QueenAttack.cs b/generators/Exercises/QueenAttack.cs index 0e4b288669..b1a7d8d9df 100644 --- a/generators/Exercises/QueenAttack.cs +++ b/generators/Exercises/QueenAttack.cs @@ -1,15 +1,14 @@ using Generators.Input; using Generators.Output; using System; -using System.Linq; namespace Generators.Exercises { public class QueenAttack : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases.Where(canonicalDataCase => canonicalDataCase.Property == "create")) + if (canonicalDataCase.Property == "create") SetCreatePropertyData(canonicalDataCase); } diff --git a/generators/Exercises/RailFenceCipher.cs b/generators/Exercises/RailFenceCipher.cs index d9b1a3de20..601d41e14f 100644 --- a/generators/Exercises/RailFenceCipher.cs +++ b/generators/Exercises/RailFenceCipher.cs @@ -4,14 +4,11 @@ namespace Generators.Exercises { public class RailFenceCipher : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters("rails"); - } + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.SetConstructorInputParameters("rails"); } } } \ No newline at end of file diff --git a/generators/Exercises/Rectangles.cs b/generators/Exercises/Rectangles.cs index ec08a685c1..a73c2e24c0 100644 --- a/generators/Exercises/Rectangles.cs +++ b/generators/Exercises/Rectangles.cs @@ -6,14 +6,11 @@ namespace Generators.Exercises { public class Rectangles : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) - { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = "count"; - canonicalDataCase.Input["strings"] = canonicalDataCase.Input["strings"] as string[] ?? Array.Empty(); - canonicalDataCase.UseVariablesForInput = true; - } + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + { + canonicalDataCase.Property = "count"; + canonicalDataCase.Input["strings"] = canonicalDataCase.Input["strings"] as string[] ?? Array.Empty(); + canonicalDataCase.UseVariablesForInput = true; } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/RnaTranscription.cs b/generators/Exercises/RnaTranscription.cs index cc738d4022..0e80e94fe3 100644 --- a/generators/Exercises/RnaTranscription.cs +++ b/generators/Exercises/RnaTranscription.cs @@ -5,10 +5,9 @@ namespace Generators.Exercises { public class RnaTranscription : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is null ? typeof(ArgumentException) : null; + canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is null ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index ea226e9175..569625fceb 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -8,25 +8,22 @@ namespace Generators.Exercises { public class RobotSimulator : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { const string direction = "direction"; const string position = "position"; const string coordinate = "coordinate"; - foreach (var canonicalDataCase in canonicalData.Cases) - { - var positionVal = new UnescapedValue(GetCoordinateInstance(canonicalDataCase.Input[position])); - var directionVal = new UnescapedValue(GetDirectionEnum(canonicalDataCase.Input[direction])); + var positionVal = new UnescapedValue(GetCoordinateInstance(canonicalDataCase.Input[position])); + var directionVal = new UnescapedValue(GetDirectionEnum(canonicalDataCase.Input[direction])); - canonicalDataCase.Input[direction] = directionVal; - canonicalDataCase.Input[coordinate] = positionVal; + canonicalDataCase.Input[direction] = directionVal; + canonicalDataCase.Input[coordinate] = positionVal; - canonicalDataCase.SetConstructorInputParameters(direction, coordinate); + canonicalDataCase.SetConstructorInputParameters(direction, coordinate); - canonicalDataCase.UseFullDescriptionPath = true; - canonicalDataCase.UseVariableForTested = true; - } + canonicalDataCase.UseFullDescriptionPath = true; + canonicalDataCase.UseVariableForTested = true; } protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodBody) diff --git a/generators/Exercises/RomanNumerals.cs b/generators/Exercises/RomanNumerals.cs index e3f687044a..e835c2c6f3 100644 --- a/generators/Exercises/RomanNumerals.cs +++ b/generators/Exercises/RomanNumerals.cs @@ -4,13 +4,10 @@ namespace Generators.Exercises { public class RomanNumerals : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.TestedMethodType = TestedMethodType.Extension; - canonicalDataCase.Property = "ToRoman"; - } + canonicalDataCase.TestedMethodType = TestedMethodType.Extension; + canonicalDataCase.Property = "ToRoman"; } } } \ No newline at end of file diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index 5a4eaa3498..ff08bc7587 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -5,13 +5,9 @@ namespace Generators.Exercises { public class RunLengthEncoding : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - // Prefix the test name with encode/decode because both functions are tested with the same cases - canonicalDataCase.Description = $"{canonicalDataCase.Property} {canonicalDataCase.Description}"; - } + canonicalDataCase.Description = $"{canonicalDataCase.Property} {canonicalDataCase.Description}"; } protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index afa5690443..e0c6fa9e4c 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -7,26 +7,23 @@ namespace Generators.Exercises { public class SaddlePoints : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) + canonicalDataCase.TestedMethodType = TestedMethodType.Instance; + canonicalDataCase.Property = "Calculate"; + canonicalDataCase.SetConstructorInputParameters("matrix"); + canonicalDataCase.UseVariablesForConstructorParameters = true; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForTested = true; + canonicalDataCase.UseVariableForExpected = true; + + canonicalDataCase.Input["matrix"] = ToMultiDimensionalArray(canonicalDataCase.Input["matrix"]); + + var array = canonicalDataCase.Expected as Array; + + if (array != null) { - canonicalDataCase.TestedMethodType = TestedMethodType.Instance; - canonicalDataCase.Property = "Calculate"; - canonicalDataCase.SetConstructorInputParameters("matrix"); - canonicalDataCase.UseVariablesForConstructorParameters = true; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.UseVariableForExpected = true; - - canonicalDataCase.Input["matrix"] = ToMultiDimensionalArray(canonicalDataCase.Input["matrix"]); - - var array = canonicalDataCase.Expected as Array; - - if (array != null) - { - canonicalDataCase.Expected = ToTupleCollection(array); - } + canonicalDataCase.Expected = ToTupleCollection(array); } } diff --git a/generators/Exercises/Say.cs b/generators/Exercises/Say.cs index 568bc0ca1a..c98372f741 100644 --- a/generators/Exercises/Say.cs +++ b/generators/Exercises/Say.cs @@ -5,13 +5,10 @@ namespace Generators.Exercises { public class Say : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = "InEnglish"; - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is int ? typeof(ArgumentOutOfRangeException) : null; - } + canonicalDataCase.Property = "InEnglish"; + canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is int ? typeof(ArgumentOutOfRangeException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/ScaleGenerator.cs b/generators/Exercises/ScaleGenerator.cs index 9fce86fc5b..c03ed17b1e 100644 --- a/generators/Exercises/ScaleGenerator.cs +++ b/generators/Exercises/ScaleGenerator.cs @@ -4,12 +4,9 @@ namespace Generators.Exercises { public class ScaleGenerator : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - } + canonicalDataCase.UseVariableForExpected = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Sieve.cs b/generators/Exercises/Sieve.cs index e7fabd1b81..9836625a8d 100644 --- a/generators/Exercises/Sieve.cs +++ b/generators/Exercises/Sieve.cs @@ -5,13 +5,10 @@ namespace Generators.Exercises { public class Sieve : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.ExceptionThrown = canonicalDataCase.Input["limit"] < 2 ? typeof(ArgumentOutOfRangeException) : null; - } + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.ExceptionThrown = canonicalDataCase.Input["limit"] < 2 ? typeof(ArgumentOutOfRangeException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index f79c221cc0..3d791d73f6 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -7,42 +7,39 @@ namespace Generators.Exercises { public class SimpleCipher : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) + canonicalDataCase.UseFullDescriptionPath = true; + + if (canonicalDataCase.Property == "new") { - canonicalDataCase.UseFullDescriptionPath = true; + return; + } - if (canonicalDataCase.Property == "new") - { - continue; - } + canonicalDataCase.TestedMethodType = TestedMethodType.Instance; - canonicalDataCase.TestedMethodType = TestedMethodType.Instance; + if (canonicalDataCase.Input.ContainsKey("key")) + { + canonicalDataCase.SetConstructorInputParameters("key"); + } - if (canonicalDataCase.Input.ContainsKey("key")) + if (canonicalDataCase.Input.TryGetValue("ciphertext", out var cipherText)) + { + if (cipherText == "cipher.key") { - canonicalDataCase.SetConstructorInputParameters("key"); + canonicalDataCase.Input["ciphertext"] = new UnescapedValue("sut.Key.Substring(0, 10)"); } - - if (canonicalDataCase.Input.TryGetValue("ciphertext", out var cipherText)) + else if (cipherText == "cipher.encode") { - if (cipherText == "cipher.key") - { - canonicalDataCase.Input["ciphertext"] = new UnescapedValue("sut.Key.Substring(0, 10)"); - } - else if (cipherText == "cipher.encode") - { - var plaintext = ValueFormatter.Format(canonicalDataCase.Input["plaintext"]); - canonicalDataCase.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); - canonicalDataCase.SetInputParameters("ciphertext"); - } + var plaintext = ValueFormatter.Format(canonicalDataCase.Input["plaintext"]); + canonicalDataCase.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); + canonicalDataCase.SetInputParameters("ciphertext"); } + } - if (canonicalDataCase.Expected is string s && s == "cipher.key") - { - canonicalDataCase.Expected = new UnescapedValue("sut.Key.Substring(0, 10)"); - } + if (canonicalDataCase.Expected is string s && s == "cipher.key") + { + canonicalDataCase.Expected = new UnescapedValue("sut.Key.Substring(0, 10)"); } } diff --git a/generators/Exercises/SpaceAge.cs b/generators/Exercises/SpaceAge.cs index fea1592e18..60bb8f8fa7 100644 --- a/generators/Exercises/SpaceAge.cs +++ b/generators/Exercises/SpaceAge.cs @@ -4,14 +4,11 @@ namespace Generators.Exercises { public class SpaceAge : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = $"On_{canonicalDataCase.Input["planet"]}"; - canonicalDataCase.SetInputParameters(); - canonicalDataCase.SetConstructorInputParameters("seconds"); - } + canonicalDataCase.Property = $"On_{canonicalDataCase.Input["planet"]}"; + canonicalDataCase.SetInputParameters(); + canonicalDataCase.SetConstructorInputParameters("seconds"); } } } \ No newline at end of file diff --git a/generators/Exercises/SpiralMatrix.cs b/generators/Exercises/SpiralMatrix.cs index 13188f8b17..a3f098b1d0 100644 --- a/generators/Exercises/SpiralMatrix.cs +++ b/generators/Exercises/SpiralMatrix.cs @@ -6,14 +6,11 @@ namespace Generators.Exercises { public class SpiralMatrix : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = "GetMatrix"; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); - } + canonicalDataCase.Property = "GetMatrix"; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); } private dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/Sublist.cs b/generators/Exercises/Sublist.cs index 215641bf5b..91511d5602 100644 --- a/generators/Exercises/Sublist.cs +++ b/generators/Exercises/Sublist.cs @@ -15,16 +15,13 @@ private UnescapedValue InputValues(int[] list) var template = (list != null) ? string.Join(", ", Array.ConvertAll(list, (x) => { return $"{x}"; })) : ""; return new UnescapedValue($"new List() {{ {template} }}".Replace(" ", " ")); } - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Input["listOne"] = InputValues(canonicalDataCase.Input["listOne"] as int[]); - canonicalDataCase.Input["listTwo"] = InputValues(canonicalDataCase.Input["listTwo"] as int[]); + canonicalDataCase.Input["listOne"] = InputValues(canonicalDataCase.Input["listOne"] as int[]); + canonicalDataCase.Input["listTwo"] = InputValues(canonicalDataCase.Input["listTwo"] as int[]); - canonicalDataCase.Property = "classify"; - canonicalDataCase.Expected = new UnescapedValue($"SublistType.{(canonicalDataCase.Expected as string).Dehumanize()}"); - } + canonicalDataCase.Property = "classify"; + canonicalDataCase.Expected = new UnescapedValue($"SublistType.{(canonicalDataCase.Expected as string).Dehumanize()}"); } } } diff --git a/generators/Exercises/SumOfMultiples.cs b/generators/Exercises/SumOfMultiples.cs index 2884c5feed..bb8499df23 100644 --- a/generators/Exercises/SumOfMultiples.cs +++ b/generators/Exercises/SumOfMultiples.cs @@ -6,12 +6,9 @@ namespace Generators.Exercises { public class SumOfMultiples : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Input["factors"] = ConvertHelper.ToArray(canonicalDataCase.Input["factors"]); - } + canonicalDataCase.Input["factors"] = ConvertHelper.ToArray(canonicalDataCase.Input["factors"]); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index cadfb49822..ad69b02427 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -7,17 +7,14 @@ namespace Generators.Exercises { public class Tournament : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = "RunTally"; - canonicalDataCase.TestedMethodType = TestedMethodType.Static; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Input["rows"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["rows"], ""); - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); - } + canonicalDataCase.Property = "RunTally"; + canonicalDataCase.TestedMethodType = TestedMethodType.Static; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Input["rows"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["rows"], ""); + canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); } protected override IEnumerable AdditionalNamespaces => new[] diff --git a/generators/Exercises/Transpose.cs b/generators/Exercises/Transpose.cs index 166d326659..75a64ad444 100644 --- a/generators/Exercises/Transpose.cs +++ b/generators/Exercises/Transpose.cs @@ -4,17 +4,14 @@ namespace Generators.Exercises { public class Transpose : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = "String"; - canonicalDataCase.Input["lines"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["lines"], ""); - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected, ""); + canonicalDataCase.Property = "String"; + canonicalDataCase.Input["lines"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["lines"], ""); + canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected, ""); - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - } + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForExpected = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Triangle.cs b/generators/Exercises/Triangle.cs index ed14009270..2418b478a8 100644 --- a/generators/Exercises/Triangle.cs +++ b/generators/Exercises/Triangle.cs @@ -1,29 +1,25 @@ -using System.Collections; using Generators.Input; -using Generators.Output; + namespace Generators.Exercises { public class Triangle : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var data in canonicalData.Cases) - { - if (data.Property == "equilateral") - data.Property = "IsEquilateral"; - else if (data.Property == "isosceles") - data.Property = "IsIsosceles"; - else if (data.Property == "scalene") - data.Property = "IsScalene"; + if (canonicalDataCase.Property == "equilateral") + canonicalDataCase.Property = "IsEquilateral"; + else if (canonicalDataCase.Property == "isosceles") + canonicalDataCase.Property = "IsIsosceles"; + else if (canonicalDataCase.Property == "scalene") + canonicalDataCase.Property = "IsScalene"; - data.Input["x"] = data.Input["sides"][0]; - data.Input["y"] = data.Input["sides"][1]; - data.Input["z"] = data.Input["sides"][2]; - data.Input.Remove("sides"); - data.SetInputParameters("x", "y", "z"); + canonicalDataCase.Input["x"] = canonicalDataCase.Input["sides"][0]; + canonicalDataCase.Input["y"] = canonicalDataCase.Input["sides"][1]; + canonicalDataCase.Input["z"] = canonicalDataCase.Input["sides"][2]; + canonicalDataCase.Input.Remove("sides"); + canonicalDataCase.SetInputParameters("x", "y", "z"); - data.UseFullDescriptionPath = true; - } + canonicalDataCase.UseFullDescriptionPath = true; } } } \ No newline at end of file diff --git a/generators/Exercises/TwelveDays.cs b/generators/Exercises/TwelveDays.cs index e2a49bfb14..ccb95be9da 100644 --- a/generators/Exercises/TwelveDays.cs +++ b/generators/Exercises/TwelveDays.cs @@ -4,17 +4,14 @@ namespace Generators.Exercises { public class TwelveDays : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); - if (canonicalDataCase.Input["startVerse"] == canonicalDataCase.Input["endVerse"]) - { - canonicalDataCase.SetInputParameters("startVerse"); - } + if (canonicalDataCase.Input["startVerse"] == canonicalDataCase.Input["endVerse"]) + { + canonicalDataCase.SetInputParameters("startVerse"); } } } diff --git a/generators/Exercises/TwoBucket.cs b/generators/Exercises/TwoBucket.cs index ef3cc54341..e27d792faa 100644 --- a/generators/Exercises/TwoBucket.cs +++ b/generators/Exercises/TwoBucket.cs @@ -5,16 +5,13 @@ namespace Generators.Exercises { public class TwoBucket : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.TestedMethodType = TestedMethodType.Instance; - canonicalDataCase.SetConstructorInputParameters("bucketOne", "bucketTwo", "startBucket"); + canonicalDataCase.TestedMethodType = TestedMethodType.Instance; + canonicalDataCase.SetConstructorInputParameters("bucketOne", "bucketTwo", "startBucket"); - var startBucket = canonicalDataCase.Input["startBucket"]; - canonicalDataCase.Input["startBucket"] = new UnescapedValue(startBucket == "two" ? "Bucket.Two" : "Bucket.One"); - } + var startBucket = canonicalDataCase.Input["startBucket"]; + canonicalDataCase.Input["startBucket"] = new UnescapedValue(startBucket == "two" ? "Bucket.Two" : "Bucket.One"); } protected override string RenderTestMethodBodyAct(TestMethodBody testMethodBody) diff --git a/generators/Exercises/TwoFer.cs b/generators/Exercises/TwoFer.cs index 35c7a86954..b2c4824b97 100644 --- a/generators/Exercises/TwoFer.cs +++ b/generators/Exercises/TwoFer.cs @@ -4,12 +4,9 @@ namespace Generators.Exercises { public class TwoFer : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) - { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Property = "Name"; - } + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + { + canonicalDataCase.Property = "Name"; } } } \ No newline at end of file diff --git a/generators/Exercises/VariableLengthQuantity.cs b/generators/Exercises/VariableLengthQuantity.cs index 4d47604d9e..83380447cc 100644 --- a/generators/Exercises/VariableLengthQuantity.cs +++ b/generators/Exercises/VariableLengthQuantity.cs @@ -9,19 +9,16 @@ namespace Generators.Exercises { public class VariableLengthQuantity : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.Input["integers"] = FormatUInt32Array(canonicalDataCase.Input["integers"]); + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.Input["integers"] = FormatUInt32Array(canonicalDataCase.Input["integers"]); - if (canonicalDataCase.Expected == null) - canonicalDataCase.ExceptionThrown = typeof(InvalidOperationException); - else - canonicalDataCase.Expected = FormatUInt32Array(canonicalDataCase.Expected); - } + if (canonicalDataCase.Expected == null) + canonicalDataCase.ExceptionThrown = typeof(InvalidOperationException); + else + canonicalDataCase.Expected = FormatUInt32Array(canonicalDataCase.Expected); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/WordCount.cs b/generators/Exercises/WordCount.cs index 461e0e2058..bd8a1d37b8 100644 --- a/generators/Exercises/WordCount.cs +++ b/generators/Exercises/WordCount.cs @@ -6,14 +6,11 @@ namespace Generators.Exercises { public class WordCount : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); - } + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.UseVariableForTested = true; + canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); } private static dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index 904ef9bfd3..f8eefb6305 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -8,32 +8,29 @@ namespace Generators.Exercises { public class WordSearch : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariablesForConstructorParameters = true; + canonicalDataCase.UseVariablesForInput = true; + canonicalDataCase.UseVariableForTested = true; + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.UseVariablesForConstructorParameters = true; - canonicalDataCase.SetConstructorInputParameters("grid"); + canonicalDataCase.SetConstructorInputParameters("grid"); - canonicalDataCase.Input["grid"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["grid"]); + canonicalDataCase.Input["grid"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["grid"]); - var expectedDictionary = canonicalDataCase.Expected as IDictionary; + var expectedDictionary = canonicalDataCase.Expected as IDictionary; - var expected = new List - { - "new Dictionary", - "{" - }; + var expected = new List + { + "new Dictionary", + "{" + }; - expected.AddRange(expectedDictionary.Select(((kv, i) => $" [\"{kv.Key}\"] = {FormatPosition(kv.Value)}{(i < expectedDictionary.Count - 1 ? "," : "")}"))); - expected.Add("}"); + expected.AddRange(expectedDictionary.Select(((kv, i) => $" [\"{kv.Key}\"] = {FormatPosition(kv.Value)}{(i < expectedDictionary.Count - 1 ? "," : "")}"))); + expected.Add("}"); - canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); - } + canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/Wordy.cs b/generators/Exercises/Wordy.cs index db683dc31b..f1adfbffc4 100644 --- a/generators/Exercises/Wordy.cs +++ b/generators/Exercises/Wordy.cs @@ -5,10 +5,9 @@ namespace Generators.Exercises { public class Wordy : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) - { - foreach (var canonicalDataCase in canonicalData.Cases) - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is bool ? typeof(ArgumentException) : null; + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + { + canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is bool ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/Yacht.cs b/generators/Exercises/Yacht.cs index be40514db6..4b8c7e1017 100644 --- a/generators/Exercises/Yacht.cs +++ b/generators/Exercises/Yacht.cs @@ -6,15 +6,12 @@ namespace Generators.Exercises { public class Yacht : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) - { - foreach (var canonicalDataCase in canonicalData.Cases) - { - canonicalDataCase.Exercise = "yacht-game"; - var category = canonicalDataCase.Input["category"].ToString(); - var formattedCategory = StringDehumanizeExtensions.Dehumanize(category); - canonicalDataCase.Input["category"] = new UnescapedValue($"YachtCategory.{formattedCategory}"); - } + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + { + canonicalDataCase.Exercise = "yacht-game"; + var category = canonicalDataCase.Input["category"].ToString(); + var formattedCategory = StringDehumanizeExtensions.Dehumanize(category); + canonicalDataCase.Input["category"] = new UnescapedValue($"YachtCategory.{formattedCategory}"); } } } diff --git a/generators/Exercises/ZebraPuzzle.cs b/generators/Exercises/ZebraPuzzle.cs index bdc12aab8e..0e7dfeed2f 100644 --- a/generators/Exercises/ZebraPuzzle.cs +++ b/generators/Exercises/ZebraPuzzle.cs @@ -6,13 +6,10 @@ namespace Generators.Exercises { public class ZebraPuzzle : GeneratorExercise { - protected override void UpdateCanonicalData(CanonicalData canonicalData) - { - foreach (var canonicalDataCase in canonicalData.Cases) - { - var nationality = canonicalDataCase.Expected as string; - canonicalDataCase.Expected = new UnescapedValue($"Nationality.{nationality.Humanize()}"); - } + protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + { + var nationality = canonicalDataCase.Expected as string; + canonicalDataCase.Expected = new UnescapedValue($"Nationality.{nationality.Humanize()}"); } } } \ No newline at end of file diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index 9d16e52c93..af3f5de1ee 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -16,14 +16,16 @@ public abstract class GeneratorExercise : Exercise public void Regenerate(CanonicalData canonicalData) { _canonicalData = canonicalData; - UpdateCanonicalData(canonicalData); + + foreach (var canonicalDataCase in _canonicalData.Cases) + UpdateCanonicalDataCase(canonicalDataCase); ExerciseWriter.WriteToFile(this); } public string Render() => CreateTestClass().Render(); - protected virtual void UpdateCanonicalData(CanonicalData canonicalData) + protected virtual void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { } From 2a6257443487c49f7b6f43db567fc5ed0b017f13 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 16:08:06 +0200 Subject: [PATCH 11/97] generators: Test method body rendering methods return IEnumerable --- generators/Exercises/Allergies.cs | 11 ++++---- generators/Exercises/BinarySearchTree.cs | 7 +++--- generators/Exercises/Bowling.cs | 20 +++++++-------- generators/Exercises/CircularBuffer.cs | 9 +++---- generators/Exercises/Clock.cs | 19 +++++++------- generators/Exercises/ComplexNumbers.cs | 8 +++--- generators/Exercises/GoCounting.cs | 10 ++++---- generators/Exercises/Grep.cs | 2 +- generators/Exercises/Meetup.cs | 4 +-- generators/Exercises/NucleotideCount.cs | 11 ++++---- generators/Exercises/PalindromeProducts.cs | 7 +++--- generators/Exercises/QueenAttack.cs | 7 +++--- generators/Exercises/RationalNumbers.cs | 5 ++-- generators/Exercises/React.cs | 8 +++--- generators/Exercises/RobotSimulator.cs | 24 ++++++------------ generators/Exercises/RunLengthEncoding.cs | 9 ++++--- generators/Exercises/SimpleCipher.cs | 6 ++--- generators/Exercises/Tournament.cs | 7 +++--- generators/Exercises/TwoBucket.cs | 9 ++++--- generators/Exercises/WordSearch.cs | 10 ++------ generators/Exercises/Zipper.cs | 25 +++++++------------ generators/GeneratorExercise.cs | 14 +++++------ .../Output/Templates/_TestMethodBody.liquid | 12 ++++++--- generators/Output/TestMethodBody.cs | 7 +++--- 24 files changed, 121 insertions(+), 130 deletions(-) diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Allergies.cs index ca6f5e6a40..687a87fa03 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Allergies.cs @@ -1,4 +1,5 @@ -using Generators.Input; +using System.Collections.Generic; +using Generators.Input; using Generators.Output; namespace Generators.Exercises @@ -15,7 +16,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.SetConstructorInputParameters("score"); } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.CanonicalDataCase.Property == "IsAllergicTo") return RenderIsAllergicToAssert(testMethodBody); @@ -23,15 +24,15 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo return base.RenderTestMethodBodyAssert(testMethodBody); } - private static string RenderIsAllergicToAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderIsAllergicToAssert(TestMethodBody testMethodBody) { const string template = @"{%- for allergy in Allergies -%} Assert.{% if allergy.result %}True{% else %}False{% endif %}(sut.IsAllergicTo(""{{ allergy.substance }}"")); {%- endfor -%}"; - + var templateParameters = new { Allergies = testMethodBody.CanonicalDataCase.Expected }; - return TemplateRenderer.RenderInline(template, templateParameters); + return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } } } \ No newline at end of file diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index 8eb35ada05..26bf45e23d 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -33,7 +33,7 @@ public class BinarySearchTree : GeneratorExercise private StringBuilder testFactCodeLines; void addCodeLine(string line) => testFactCodeLines.Append(line + "\r\n"); - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { testFactCodeLines = new StringBuilder(); var canonicalDataCase = testMethodBody.CanonicalDataCase; @@ -51,7 +51,8 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo if (expected != null) { var tree = new ExpectedDataBinaryTree(expected as System.Collections.Generic.Dictionary); - foreach (var assert in tree.TestAsserts()) addCodeLine(assert); + foreach (var assert in tree.TestAsserts()) + addCodeLine(assert); } else { @@ -59,7 +60,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo addCodeLine($"Assert.Equal(new[] {{ {expectedArrayString} }}, tree.AsEnumerable());"); } - return TemplateRenderer.RenderInline(testFactCodeLines.ToString(), testMethodBody.AssertTemplateParameters); + return new[] { TemplateRenderer.RenderInline(testFactCodeLines.ToString(), testMethodBody.AssertTemplateParameters) }; } } } \ No newline at end of file diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index 1834f65676..11ba4c2790 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -24,7 +24,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.SetInputParameters(); } - protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) { var builder = new StringBuilder(); builder.AppendLine("var sut = new BowlingGame();"); @@ -44,10 +44,10 @@ protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodB } } - return builder.ToString(); + return new[] { builder.ToString() }; } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { var template = string.Empty; if (testMethodBody.CanonicalDataCase.ExceptionThrown != null && testMethodBody.CanonicalDataCase.Input.ContainsKey("roll")) @@ -57,18 +57,18 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo { RollVal = testMethodBody.CanonicalDataCase.Input["roll"] }; - return TemplateRenderer.RenderInline(template, templateParams); + return new[] { TemplateRenderer.RenderInline(template, templateParams) }; } else if (testMethodBody.CanonicalDataCase.ExceptionThrown != null && testMethodBody.CanonicalDataCase.Property == "score") { template = "Assert.Throws(() => sut.Score());"; - return template; + return new[] { template }; } return base.RenderTestMethodBodyAssert(testMethodBody); } - protected override string RenderTestMethodBodyAct(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) { var template = @"DoRoll(previousRolls, sut); @@ -76,7 +76,7 @@ protected override string RenderTestMethodBodyAct(TestMethodBody testMethodBody) if (testMethodBody.CanonicalDataCase.ExceptionThrown != null) { - return template; + return new[] { template }; } if (testMethodBody.CanonicalDataCase.Input.ContainsKey("roll")) @@ -89,14 +89,14 @@ protected override string RenderTestMethodBodyAct(TestMethodBody testMethodBody) { RolVal = testMethodBody.CanonicalDataCase.Input["roll"] }; - return TemplateRenderer.RenderInline(template, templateParameters); + return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } template += "var actual = sut.Score();"; - return template; + return new[] { template }; } - protected override string[] RenderAdditionalMethods() + protected override IEnumerable RenderAdditionalMethods() { return new string[] { @" diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/CircularBuffer.cs index 2b18091372..b68a5ce773 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/CircularBuffer.cs @@ -8,15 +8,12 @@ namespace Generators.Exercises { public class CircularBuffer : GeneratorExercise { - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var lines = new StringBuilder(); - lines.AppendLine(RenderSut(testMethodBody.CanonicalDataCase)); + yield return RenderSut(testMethodBody.CanonicalDataCase); foreach (var operation in testMethodBody.CanonicalDataCase.Input["operations"]) - lines.AppendLine(RenderOperation(operation)); - - return lines.ToString(); + yield return RenderOperation(operation); } private static string RenderSut(CanonicalDataCase canonicalDataCase) diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Clock.cs index e3fcb980a2..7e33c35ecb 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Clock.cs @@ -40,30 +40,29 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC } } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.CanonicalDataCase.Property == PropertyEquals) { return RenderEqualToAssert(testMethodBody); } - else if (testMethodBody.CanonicalDataCase.Property != PropertyToString) + + if (testMethodBody.CanonicalDataCase.Property != PropertyToString) { return RenderConsistencyToAssert(testMethodBody); } - else - { - return base.RenderTestMethodBodyAssert(testMethodBody); - } + + return base.RenderTestMethodBodyAssert(testMethodBody); } - private static string RenderConsistencyToAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) { var template = $"Assert.Equal({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}}.ToString());"; - return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); + yield return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); } - private static string RenderEqualToAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderEqualToAssert(TestMethodBody testMethodBody) { var expectedParameter = testMethodBody.CanonicalDataCase.Input[ParamClock1]; var testedValue = "sut"; @@ -75,7 +74,7 @@ private static string RenderEqualToAssert(TestMethodBody testMethodBody) ? $"Assert.Equal({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}}); " : $"Assert.NotEqual({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}});"; - return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); + return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; } } } \ No newline at end of file diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index c2669e27eb..25633253f5 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -10,7 +10,7 @@ namespace Generators.Exercises public class ComplexNumbers : GeneratorExercise { protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) - { + { canonicalDataCase.Exercise = "complex-number"; canonicalDataCase.UseVariableForExpected = IsComplexNumber(canonicalDataCase.Expected); canonicalDataCase.Expected = ConvertToType(canonicalDataCase.Expected); @@ -31,7 +31,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC private static string[] GetInputParameters(CanonicalDataCase canonicalDataCase, string constructorParamName) => canonicalDataCase.Input.Keys.Where(x => x != constructorParamName).ToArray(); - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.UseVariableForExpected) return RenderComplexNumberAssert(testMethodBody); @@ -39,11 +39,11 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo return base.RenderTestMethodBodyAssert(testMethodBody); } - private static string RenderComplexNumberAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderComplexNumberAssert(TestMethodBody testMethodBody) { const string template = "Assert.Equal({{ ExpectedParameter }}.Real(), {{ TestedValue }}.Real(), precision: 15);\r\nAssert.Equal({{ ExpectedParameter }}.Imaginary(), {{ TestedValue }}.Imaginary(), precision: 15);"; - return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); + return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Math).Namespace }; diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index 423ddfbcda..3e752e8025 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -52,7 +52,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC } } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.CanonicalDataCase.ExceptionThrown != null) { @@ -61,20 +61,20 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo if (testMethodBody.CanonicalDataCase.Property == "territories") { - return string.Join(Environment.NewLine, new[] + return new[] { "Assert.Equal(expected.Keys, actual.Keys);", "Assert.Equal(expected[Owner.Black], actual[Owner.Black]);", "Assert.Equal(expected[Owner.White], actual[Owner.White]);", "Assert.Equal(expected[Owner.None], actual[Owner.None]);" - }); + }; } - return string.Join(Environment.NewLine, new[] + return new[] { "Assert.Equal(expected.Item1, actual.Item1);", "Assert.Equal(expected.Item2, actual.Item2);" - }); + }; } private string FormatOwner(dynamic owner) diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index 3a5fa083a7..ede8c874ad 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -41,7 +41,7 @@ protected override TestClass CreateTestClass() typeof(System.IO.File).Namespace }; - protected override string[] RenderAdditionalMethods() + protected override IEnumerable RenderAdditionalMethods() { return new[] { diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 59590a5fdd..1c684a7a94 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -30,11 +30,11 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC new UnescapedValue($"DayOfWeek.{((string)canonicalDataCase.Input[ParamDayOfWeek]).Transform(To.SentenceCase)}"); } - protected override String RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { string template = $"Assert.Equal({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}}.ToString(\"yyyy-MM-dd\"));"; - return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); + return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; } protected override IEnumerable AdditionalNamespaces => new[] { typeof(DayOfWeek).Namespace }; diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index a9b3d3c88b..0edeb4cd36 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -22,16 +22,17 @@ private static dynamic ConvertExpected(dynamic expected) protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.UseVariableForExpected) { return RenderEqualBodyAssert(testMethodBody); } + return RenderThrowsBodyAssert(testMethodBody); } - private string RenderEqualBodyAssert(TestMethodBody testMethodBody) + private IEnumerable RenderEqualBodyAssert(TestMethodBody testMethodBody) { const string template = @"Assert.Equal(expected, sut.{{ TestedMethodName }});"; @@ -40,10 +41,10 @@ private string RenderEqualBodyAssert(TestMethodBody testMethodBody) TestedMethodName = testMethodBody.CanonicalDataCase.Property.ToTestedMethodName() }; - return TemplateRenderer.RenderInline(template, templateParameters); + return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private string RenderThrowsBodyAssert(TestMethodBody testMethodBody) + private IEnumerable RenderThrowsBodyAssert(TestMethodBody testMethodBody) { const string template = @"Assert.Throws(() => new NucleotideCount(""{{ Input }}""));"; @@ -52,7 +53,7 @@ private string RenderThrowsBodyAssert(TestMethodBody testMethodBody) Input = testMethodBody.CanonicalDataCase.Input["strand"] }; - return TemplateRenderer.RenderInline(template, templateParameters); + return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } } } diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/PalindromeProducts.cs index 7880e687de..7fb4c4dd7c 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/PalindromeProducts.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using Generators.Input; using Generators.Output; @@ -22,18 +23,18 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC } } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.CanonicalDataCase.ExceptionThrown != null) { return base.RenderTestMethodBodyAssert(testMethodBody); } - return string.Join(Environment.NewLine, new[] + return new[] { "Assert.Equal(expected.Item1, actual.Item1);", "Assert.Equal(expected.Item2, actual.Item2);" - }); + }; } private string FormatCoordinates(dynamic coordinates) diff --git a/generators/Exercises/QueenAttack.cs b/generators/Exercises/QueenAttack.cs index b1a7d8d9df..d5bb6b2d40 100644 --- a/generators/Exercises/QueenAttack.cs +++ b/generators/Exercises/QueenAttack.cs @@ -1,6 +1,7 @@ using Generators.Input; using Generators.Output; using System; +using System.Collections.Generic; namespace Generators.Exercises { @@ -12,13 +13,13 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC SetCreatePropertyData(canonicalDataCase); } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.CanonicalDataCase.Property == "canAttack") - return RenderCanAttackAssert(testMethodBody); + return new[] { RenderCanAttackAssert(testMethodBody) }; if (testMethodBody.UseVariableForTested) - return string.Empty; + return Array.Empty(); return base.RenderTestMethodBodyAssert(testMethodBody); } diff --git a/generators/Exercises/RationalNumbers.cs b/generators/Exercises/RationalNumbers.cs index e7f68c6d4b..9476dae6c7 100644 --- a/generators/Exercises/RationalNumbers.cs +++ b/generators/Exercises/RationalNumbers.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using Generators.Output; namespace Generators.Exercises @@ -16,7 +17,7 @@ public RationalNumber(int[] n) public class RationalNumbers : GeneratorExercise { - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { var input = testMethodBody.CanonicalDataCase.Properties["input"] as System.Collections.Generic.Dictionary; var operation = testMethodBody.CanonicalDataCase.Properties["property"].ToString(); @@ -66,7 +67,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo break; } - return TemplateRenderer.RenderInline(assertCodeLine, testMethodBody.AssertTemplateParameters); + return new[] { TemplateRenderer.RenderInline(assertCodeLine, testMethodBody.AssertTemplateParameters) }; } private static int precision(object rawValue) => rawValue.ToString().Split(new char[] { '.' }).Length <= 1 ? 0 : rawValue.ToString().Split(new char[] { '.' })[1].Length; diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index e833797311..effd73fb98 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -10,7 +10,7 @@ namespace Generators.Exercises { public class React : GeneratorExercise { - protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) { var arrange = new StringBuilder(); arrange.AppendLine("var sut = new Reactor();"); @@ -21,7 +21,7 @@ protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodB var operations = RenderOperations(testMethodBody.CanonicalDataCase.Input["operations"]); arrange.AppendLine(operations); - return arrange.ToString(); + return new[] { arrange.ToString() }; } private static string RenderCells(dynamic cells) @@ -122,7 +122,9 @@ private static string RenderOperation(dynamic operation) } } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) => ""; + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) => new[] { + "" + }; protected override IEnumerable AdditionalNamespaces => new[] { diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index 569625fceb..8acd8a077d 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -23,27 +23,19 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.SetConstructorInputParameters(direction, coordinate); canonicalDataCase.UseFullDescriptionPath = true; - canonicalDataCase.UseVariableForTested = true; } - protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodBody) - { - ((testMethodBody.ArrangeTemplateParameters as dynamic).Variables as List).RemoveAt(1); - - return base.RenderTestMethodBodyArrange(testMethodBody); - } - - protected override string RenderTestMethodBodyAct(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) { switch (testMethodBody.CanonicalDataCase.Property) { - case "create": return string.Empty; + case "create": return Array.Empty(); case "instructions": return RenderInstructionsMethodBodyAct(testMethodBody); default: return RenderDefaultMethodBodyAct(testMethodBody); } } - private string RenderDefaultMethodBodyAct(TestMethodBody testMethodBody) + private IEnumerable RenderDefaultMethodBodyAct(TestMethodBody testMethodBody) { string template = @"sut.{{MethodInvocation}}();"; @@ -52,10 +44,10 @@ private string RenderDefaultMethodBodyAct(TestMethodBody testMethodBody) MethodInvocation = testMethodBody.CanonicalDataCase.Property.ToTestedMethodName() }; - return TemplateRenderer.RenderInline(template, templateParameters); + return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private string RenderInstructionsMethodBodyAct(TestMethodBody testMethodBody) + private IEnumerable RenderInstructionsMethodBodyAct(TestMethodBody testMethodBody) { string template = @"sut.{{MethodInvocation}}(""{{Instructions}}"");"; @@ -65,10 +57,10 @@ private string RenderInstructionsMethodBodyAct(TestMethodBody testMethodBody) Instructions = testMethodBody.CanonicalDataCase.Input["instructions"] }; - return TemplateRenderer.RenderInline(template, templateParameters); + return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { var expected = testMethodBody.CanonicalDataCase.Expected as Dictionary; expected.TryGetValue("position", out dynamic position); @@ -92,7 +84,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo Y = position?["y"] }; - return TemplateRenderer.RenderInline(template.ToString(), templateParameters); + return new[] { TemplateRenderer.RenderInline(template.ToString(), templateParameters) }; } private string GetDirectionEnum(string direction) diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index ff08bc7587..dbaba6cfb9 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -1,4 +1,5 @@ -using Generators.Input; +using System.Collections.Generic; +using Generators.Input; using Generators.Output; namespace Generators.Exercises @@ -10,7 +11,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Description = $"{canonicalDataCase.Property} {canonicalDataCase.Description}"; } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.CanonicalDataCase.Property == "consistency") { @@ -20,7 +21,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo return base.RenderTestMethodBodyAssert(testMethodBody); } - private static string RenderConsistencyToAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) { const string template = @"Assert.Equal(""{{ExpectedOutput}}"", {{ExerciseName}}.Decode({{ExerciseName}}.Encode(""{{ExpectedOutput}}"")));"; @@ -30,7 +31,7 @@ private static string RenderConsistencyToAssert(TestMethodBody testMethodBody) ExerciseName = testMethodBody.CanonicalDataCase.Exercise.ToTestedClassName() }; - return TemplateRenderer.RenderInline(template, templateParameters); + return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } } } \ No newline at end of file diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index 3d791d73f6..a3877ce7d1 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -43,17 +43,17 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC } } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.CanonicalDataCase.Property == "new") { var key = ValueFormatter.Format(testMethodBody.CanonicalDataCase.Input["key"]); - return $"Assert.Throws(() => new SimpleCipher({key}));"; + return new[] { $"Assert.Throws(() => new SimpleCipher({key}));" }; } else if (testMethodBody.CanonicalDataCase.Property == "key") { var pattern = ValueFormatter.Format(testMethodBody.CanonicalDataCase.Expected["match"]); - return $"Assert.Matches({pattern}, sut.Key);"; + return new[] { $"Assert.Matches({pattern}, sut.Key);" }; } return base.RenderTestMethodBodyAssert(testMethodBody); diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index ad69b02427..b6c0b9b24f 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -20,18 +20,17 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace, - typeof(System.String).Namespace, typeof(System.IO.Stream).Namespace, typeof(System.Text.UTF8Encoding).Namespace }; - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { string template = @"Assert.Equal(expected, RunTally(rows));"; - return TemplateRenderer.RenderInline(template, new { }); + return new[] { TemplateRenderer.RenderInline(template, new { }) }; } - protected override string[] RenderAdditionalMethods() + protected override IEnumerable RenderAdditionalMethods() { var methods = @" private string RunTally(string input) diff --git a/generators/Exercises/TwoBucket.cs b/generators/Exercises/TwoBucket.cs index e27d792faa..872882a1a5 100644 --- a/generators/Exercises/TwoBucket.cs +++ b/generators/Exercises/TwoBucket.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using Generators.Input; using Generators.Output; @@ -14,7 +15,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Input["startBucket"] = new UnescapedValue(startBucket == "two" ? "Bucket.Two" : "Bucket.One"); } - protected override string RenderTestMethodBodyAct(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) { const string template = @"var result = {{MethodInvocation}};"; @@ -23,10 +24,10 @@ protected override string RenderTestMethodBodyAct(TestMethodBody testMethodBody) MethodInvocation = testMethodBody.Data.TestedMethodInvocation }; - return TemplateRenderer.RenderInline(template, templateParameters); + return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { const string template = @"Assert.Equal({{MovesExpected}}, result.Moves); @@ -40,7 +41,7 @@ protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBo GoalBucketExpected = testMethodBody.CanonicalDataCase.Expected["goalBucket"], }; - return TemplateRenderer.RenderInline(template, templateParameters); + return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } } } \ No newline at end of file diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index f8eefb6305..3cdcd48046 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -33,18 +33,12 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { var expectedDictionary = testMethodBody.CanonicalDataCase.Properties["expected"] as IDictionary; - var assert = new List(); - foreach (var kv in expectedDictionary) - { - assert.Add(RenderTestMethodBodyAssertForSearchWord(kv.Key, kv.Value)); - } - - return string.Join(Environment.NewLine, assert); + yield return RenderTestMethodBodyAssertForSearchWord(kv.Key, kv.Value); } private string RenderTestMethodBodyAssertForSearchWord(string word, dynamic expected) diff --git a/generators/Exercises/Zipper.cs b/generators/Exercises/Zipper.cs index e2e03e63fd..a16c51bfef 100644 --- a/generators/Exercises/Zipper.cs +++ b/generators/Exercises/Zipper.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Text; using Generators.Output; @@ -8,36 +9,28 @@ namespace Generators.Exercises { public class Zipper : GeneratorExercise { - protected override string RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) { - var arrange = new StringBuilder(); - var tree = RenderTree(testMethodBody.CanonicalDataCase.Input["initialTree"]); - arrange.AppendLine($"var tree = {tree};"); - arrange.AppendLine("var sut = Zipper.FromTree(tree);"); + yield return $"var tree = {tree};"; + yield return "var sut = Zipper.FromTree(tree);"; var operations = RenderOperations(testMethodBody.CanonicalDataCase.Input["operations"]); - arrange.AppendLine($"var actual = sut{operations};"); - - return arrange.ToString(); + yield return $"var actual = sut{operations};"; } - protected override string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var assert = new StringBuilder(); - var expected = RenderExpected(testMethodBody.CanonicalDataCase.Expected); if (expected == null) { - assert.AppendLine("Assert.Null(actual);"); + yield return "Assert.Null(actual);"; } else { - assert.AppendLine($"var expected = {expected};"); - assert.AppendLine("Assert.Equal(expected, actual);"); + yield return $"var expected = {expected};"; + yield return "Assert.Equal(expected, actual);"; } - - return assert.ToString(); } private static string RenderTree(dynamic tree) diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index af3f5de1ee..5c59c53dc0 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -31,16 +31,16 @@ protected virtual void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCa protected virtual IEnumerable AdditionalNamespaces => Enumerable.Empty(); - protected virtual string RenderTestMethodBodyArrange(TestMethodBody testMethodBody) - => TemplateRenderer.RenderPartial(testMethodBody.ArrangeTemplateName, testMethodBody.ArrangeTemplateParameters); + protected virtual IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + => new[] { TemplateRenderer.RenderPartial(testMethodBody.ArrangeTemplateName, testMethodBody.ArrangeTemplateParameters) }; - protected virtual string RenderTestMethodBodyAct(TestMethodBody testMethodBody) - => TemplateRenderer.RenderPartial(testMethodBody.ActTemplateName, testMethodBody.ActTemplateParameters); + protected virtual IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) + => new[] { TemplateRenderer.RenderPartial(testMethodBody.ActTemplateName, testMethodBody.ActTemplateParameters) }; - protected virtual string RenderTestMethodBodyAssert(TestMethodBody testMethodBody) - => TemplateRenderer.RenderPartial(testMethodBody.AssertTemplateName, testMethodBody.AssertTemplateParameters); + protected virtual IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + => new[] { TemplateRenderer.RenderPartial(testMethodBody.AssertTemplateName, testMethodBody.AssertTemplateParameters) }; - protected virtual string[] RenderAdditionalMethods() => Array.Empty(); + protected virtual IEnumerable RenderAdditionalMethods() => Array.Empty(); private HashSet GetUsingNamespaces() { diff --git a/generators/Output/Templates/_TestMethodBody.liquid b/generators/Output/Templates/_TestMethodBody.liquid index 9cf0a0f729..06c3d49ec3 100644 --- a/generators/Output/Templates/_TestMethodBody.liquid +++ b/generators/Output/Templates/_TestMethodBody.liquid @@ -1,3 +1,9 @@ -{{ Arrange }} -{{ Act }} -{{ Assert }} \ No newline at end of file +{%- for arrange in Arrange -%} +{{ arrange }} +{%- endfor -%} +{%- for act in Act -%} +{{ act }} +{%- endfor -%} +{%- for assert in Assert -%} +{{ assert }} +{%- endfor -%} \ No newline at end of file diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index 19d201af4c..930c3182c5 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -1,3 +1,4 @@ +using System.Collections.Generic; using Generators.Input; namespace Generators.Output @@ -33,9 +34,9 @@ protected TestMethodBody(CanonicalDataCase canonicalDataCase, CanonicalData cano public string AssertTemplateName { get; set; } = "AssertEqual"; public object AssertTemplateParameters { get; set; } - public string Act { get; set; } - public string Arrange { get; set; } - public string Assert { get; set; } + public IEnumerable Act { get; set; } + public IEnumerable Arrange { get; set; } + public IEnumerable Assert { get; set; } public virtual string Render() => TemplateRenderer.RenderPartial(TemplateName, new { Arrange, Act, Assert }); From 153376aab023c071c2ade6fb086c49c5ccfcb6a1 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 16:18:10 +0200 Subject: [PATCH 12/97] generators: Use var everywhere --- generators/Exercises/BinarySearchTree.cs | 4 ++-- generators/Exercises/Meetup.cs | 2 +- generators/Exercises/RationalNumbers.cs | 4 ++-- generators/Exercises/RobotSimulator.cs | 10 +++++----- generators/Exercises/SaddlePoints.cs | 2 +- generators/Exercises/Tournament.cs | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index 26bf45e23d..f1a3e173c8 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -43,7 +43,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody if (constructorData.Length == 1) addCodeLine($"var tree = new BinarySearchTree({constructorData[0]});"); else { - string constructorDataString = string.Join(", ", constructorData); + var constructorDataString = string.Join(", ", constructorData); addCodeLine($"var tree = new BinarySearchTree(new[] {{ {constructorDataString} }});"); } @@ -56,7 +56,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody } else { - string expectedArrayString = string.Join(", ", canonicalDataCase.Properties["expected"] as string[]); + var expectedArrayString = string.Join(", ", canonicalDataCase.Properties["expected"] as string[]); addCodeLine($"Assert.Equal(new[] {{ {expectedArrayString} }}, tree.AsEnumerable());"); } diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 1c684a7a94..5891182d44 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -32,7 +32,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - string template = $"Assert.Equal({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}}.ToString(\"yyyy-MM-dd\"));"; + var template = $"Assert.Equal({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}}.ToString(\"yyyy-MM-dd\"));"; return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; } diff --git a/generators/Exercises/RationalNumbers.cs b/generators/Exercises/RationalNumbers.cs index 9476dae6c7..a2f4d9e539 100644 --- a/generators/Exercises/RationalNumbers.cs +++ b/generators/Exercises/RationalNumbers.cs @@ -23,8 +23,8 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody var operation = testMethodBody.CanonicalDataCase.Properties["property"].ToString(); var expected = testMethodBody.CanonicalDataCase.Properties["expected"]; var operationName = char.ToUpper(operation[0]) + operation.Substring(1); - string assertCodeLine = ""; - string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; + var assertCodeLine = ""; + var operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; string operationCode = operationsWithOverloading.Substring(operationsWithOverloading.IndexOf(operation.ToLower()) + 4, 1); switch (operation.ToLower()) diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index 8acd8a077d..6b31451697 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -37,7 +37,7 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te private IEnumerable RenderDefaultMethodBodyAct(TestMethodBody testMethodBody) { - string template = @"sut.{{MethodInvocation}}();"; + var template = @"sut.{{MethodInvocation}}();"; var templateParameters = new { @@ -49,7 +49,7 @@ private IEnumerable RenderDefaultMethodBodyAct(TestMethodBody testMethod private IEnumerable RenderInstructionsMethodBodyAct(TestMethodBody testMethodBody) { - string template = @"sut.{{MethodInvocation}}(""{{Instructions}}"");"; + var template = @"sut.{{MethodInvocation}}(""{{Instructions}}"");"; var templateParameters = new { @@ -63,10 +63,10 @@ private IEnumerable RenderInstructionsMethodBodyAct(TestMethodBody testM protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { var expected = testMethodBody.CanonicalDataCase.Expected as Dictionary; - expected.TryGetValue("position", out dynamic position); - expected.TryGetValue("direction", out dynamic direction); + expected.TryGetValue("position", out var position); + expected.TryGetValue("direction", out var direction); - StringBuilder template = new StringBuilder(); + var template = new StringBuilder(); if (direction != null) template.AppendLine("Assert.Equal({{Direction}}, sut.Direction);"); diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index e0c6fa9e4c..654f56d316 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -40,7 +40,7 @@ private static dynamic ToMultiDimensionalArray(dynamic array) private IEnumerable> ToTupleCollection(Array array) { - for (int x = 0; x < array.GetLength(0); x++) + for (var x = 0; x < array.GetLength(0); x++) { var current = ((Array)array).GetValue(x) as Dictionary; yield return new Tuple(current["row"].ToString(), current["column"].ToString()); diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index b6c0b9b24f..bb75922fc9 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -26,7 +26,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - string template = @"Assert.Equal(expected, RunTally(rows));"; + var template = @"Assert.Equal(expected, RunTally(rows));"; return new[] { TemplateRenderer.RenderInline(template, new { }) }; } From 6f4cc4996297e3b3adf00f5ee3fc6a80c1519c71 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 18:57:03 +0200 Subject: [PATCH 13/97] generator: Code cleanup --- generators/Exercises/Allergies.cs | 7 +- generators/Exercises/BinarySearchTree.cs | 43 ++++++------- generators/Exercises/Bowling.cs | 43 ++++++------- generators/Exercises/CircularBuffer.cs | 23 +++---- generators/Exercises/Clock.cs | 20 +++--- generators/Exercises/CollatzConjecture.cs | 4 +- generators/Exercises/ComplexNumbers.cs | 14 ++-- generators/Exercises/Connect.cs | 6 +- generators/Exercises/CustomSet.cs | 14 ++-- generators/Exercises/Dominoes.cs | 2 +- generators/Exercises/Etl.cs | 4 +- generators/Exercises/FlattenArray.cs | 2 +- generators/Exercises/GoCounting.cs | 4 +- generators/Exercises/Grep.cs | 17 +++-- generators/Exercises/LargestSeriesProduct.cs | 3 +- generators/Exercises/ListOps.cs | 64 ++++++++----------- generators/Exercises/Meetup.cs | 2 +- generators/Exercises/Minesweeper.cs | 4 +- generators/Exercises/NucleotideCount.cs | 31 ++++----- generators/Exercises/OcrNumbers.cs | 11 +--- generators/Exercises/PalindromeProducts.cs | 2 +- generators/Exercises/QueenAttack.cs | 15 ++--- generators/Exercises/RationalNumbers.cs | 17 +++-- generators/Exercises/React.cs | 11 ++-- generators/Exercises/RobotSimulator.cs | 12 ++-- generators/Exercises/RunLengthEncoding.cs | 9 +-- generators/Exercises/SaddlePoints.cs | 10 ++- generators/Exercises/SimpleCipher.cs | 36 +++++------ generators/Exercises/SpiralMatrix.cs | 2 +- generators/Exercises/Sublist.cs | 19 +++--- generators/Exercises/Tournament.cs | 12 ++-- generators/Exercises/TwoBucket.cs | 2 +- .../Exercises/VariableLengthQuantity.cs | 7 +- generators/Exercises/WordCount.cs | 4 +- generators/Exercises/WordSearch.cs | 26 +++----- generators/Exercises/Zipper.cs | 1 - generators/GeneratorExercise.cs | 18 +++--- generators/Input/CanonicalDataCaseParser.cs | 6 +- generators/Input/ConfigFile.cs | 2 +- generators/Input/ConvertHelper.cs | 18 +++--- generators/Output/ExerciseWriter.cs | 2 +- generators/Output/NameExtensions.cs | 5 +- generators/Output/TestClass.cs | 4 +- generators/Output/TestMethodBodyData.cs | 1 - generators/Output/TypesExtensions.cs | 8 --- generators/Output/ValueFormatter.cs | 12 ++-- 46 files changed, 261 insertions(+), 318 deletions(-) diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Allergies.cs index 687a87fa03..176f96f203 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Allergies.cs @@ -18,10 +18,9 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.CanonicalDataCase.Property == "IsAllergicTo") - return RenderIsAllergicToAssert(testMethodBody); - - return base.RenderTestMethodBodyAssert(testMethodBody); + return testMethodBody.CanonicalDataCase.Property == "IsAllergicTo" + ? RenderIsAllergicToAssert(testMethodBody) + : base.RenderTestMethodBodyAssert(testMethodBody); } private static IEnumerable RenderIsAllergicToAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index f1a3e173c8..ffe9b6b410 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using System.Text; using Generators.Output; @@ -6,61 +7,59 @@ namespace Generators.Exercises { public class ExpectedDataBinaryTree { - public ExpectedDataBinaryTree(System.Collections.Generic.Dictionary treeNode) + public ExpectedDataBinaryTree(IReadOnlyDictionary treeNode) { Value = treeNode["data"] as string; - if (treeNode["left"] != null) this.Left = new ExpectedDataBinaryTree(treeNode["left"] as System.Collections.Generic.Dictionary); - if (treeNode["right"] != null) this.Right = new ExpectedDataBinaryTree(treeNode["right"] as System.Collections.Generic.Dictionary); + if (treeNode["left"] != null) Left = new ExpectedDataBinaryTree(treeNode["left"] as Dictionary); + if (treeNode["right"] != null) Right = new ExpectedDataBinaryTree(treeNode["right"] as Dictionary); } - public int Level { get; } public string Value { get; } - public ExpectedDataBinaryTree Left { get; private set; } - public ExpectedDataBinaryTree Right { get; private set; } + public ExpectedDataBinaryTree Left { get; } + public ExpectedDataBinaryTree Right { get; } public IEnumerable TestAsserts(string traverse = "") { - yield return $"Assert.Equal({this.Value}, tree{traverse}.Value);"; - if (this.Left != null) foreach (var assert in this.Left.TestAsserts(traverse + ".Left")) yield return assert; - if (this.Right != null) foreach (var assert in this.Right.TestAsserts(traverse + ".Right")) yield return assert; + yield return $"Assert.Equal({Value}, tree{traverse}.Value);"; + if (Left != null) foreach (var assert in Left.TestAsserts(traverse + ".Left")) yield return assert; + if (Right != null) foreach (var assert in Right.TestAsserts(traverse + ".Right")) yield return assert; } } public class BinarySearchTree : GeneratorExercise { - protected override IEnumerable AdditionalNamespaces => new[] { typeof(System.Linq.IQueryable).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(IQueryable).Namespace }; - private StringBuilder testFactCodeLines; - void addCodeLine(string line) => testFactCodeLines.Append(line + "\r\n"); + private StringBuilder _testFactCodeLines; + private void AddCodeLine(string line) => _testFactCodeLines.Append(line + "\r\n"); protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - testFactCodeLines = new StringBuilder(); + _testFactCodeLines = new StringBuilder(); var canonicalDataCase = testMethodBody.CanonicalDataCase; - var input = canonicalDataCase.Properties["input"] as System.Collections.Generic.Dictionary; + var input = canonicalDataCase.Properties["input"] as Dictionary; var constructorData = input["treeData"] as string[]; - if (constructorData.Length == 1) addCodeLine($"var tree = new BinarySearchTree({constructorData[0]});"); + if (constructorData.Length == 1) AddCodeLine($"var tree = new BinarySearchTree({constructorData[0]});"); else { var constructorDataString = string.Join(", ", constructorData); - addCodeLine($"var tree = new BinarySearchTree(new[] {{ {constructorDataString} }});"); + AddCodeLine($"var tree = new BinarySearchTree(new[] {{ {constructorDataString} }});"); } - var expected = canonicalDataCase.Properties["expected"] as System.Collections.Generic.Dictionary; - if (expected != null) + if (canonicalDataCase.Properties["expected"] is Dictionary expected) { - var tree = new ExpectedDataBinaryTree(expected as System.Collections.Generic.Dictionary); + var tree = new ExpectedDataBinaryTree(expected); foreach (var assert in tree.TestAsserts()) - addCodeLine(assert); + AddCodeLine(assert); } else { var expectedArrayString = string.Join(", ", canonicalDataCase.Properties["expected"] as string[]); - addCodeLine($"Assert.Equal(new[] {{ {expectedArrayString} }}, tree.AsEnumerable());"); + AddCodeLine($"Assert.Equal(new[] {{ {expectedArrayString} }}, tree.AsEnumerable());"); } - return new[] { TemplateRenderer.RenderInline(testFactCodeLines.ToString(), testMethodBody.AssertTemplateParameters) }; + return new[] { TemplateRenderer.RenderInline(_testFactCodeLines.ToString(), testMethodBody.AssertTemplateParameters) }; } } } \ No newline at end of file diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index 11ba4c2790..fc1d4e7eaa 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -1,8 +1,8 @@ using System; +using System.Collections.Generic; using System.Text; using Generators.Input; using Generators.Output; -using System.Collections.Generic; namespace Generators.Exercises { @@ -29,19 +29,18 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod var builder = new StringBuilder(); builder.AppendLine("var sut = new BowlingGame();"); - if (testMethodBody.CanonicalDataCase.Input.ContainsKey(PreviousRolls)) + if (!testMethodBody.CanonicalDataCase.Input.ContainsKey(PreviousRolls)) + return new[] { builder.ToString() }; + + if (testMethodBody.CanonicalDataCase.Input[PreviousRolls] is int[] array) { - var array = testMethodBody.CanonicalDataCase.Input[PreviousRolls] as int[]; - if (array == null) - { - builder.Append("var previousRolls = Array.Empty();"); - } - else - { - builder.Append("var previousRolls = new [] { "); - builder.AppendJoin(", ", array); - builder.AppendLine(" };"); - } + builder.Append("var previousRolls = new [] { "); + builder.AppendJoin(", ", array); + builder.AppendLine(" };"); + } + else + { + builder.Append("var previousRolls = Array.Empty();"); } return new[] { builder.ToString() }; @@ -49,23 +48,23 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var template = string.Empty; if (testMethodBody.CanonicalDataCase.ExceptionThrown != null && testMethodBody.CanonicalDataCase.Input.ContainsKey("roll")) { - template = "Assert.Throws(() => sut.Roll({{RollVal}}));"; + const string template = "Assert.Throws(() => sut.Roll({{RollVal}}));"; var templateParams = new { RollVal = testMethodBody.CanonicalDataCase.Input["roll"] }; return new[] { TemplateRenderer.RenderInline(template, templateParams) }; } - else if (testMethodBody.CanonicalDataCase.ExceptionThrown != null && testMethodBody.CanonicalDataCase.Property == "score") - { - template = "Assert.Throws(() => sut.Score());"; - return new[] { template }; - } - return base.RenderTestMethodBodyAssert(testMethodBody); + if (testMethodBody.CanonicalDataCase.ExceptionThrown == null || + testMethodBody.CanonicalDataCase.Property != "score") + return base.RenderTestMethodBodyAssert(testMethodBody); + + const string throwTemplate = "Assert.Throws(() => sut.Score());"; + return new[] { throwTemplate }; + } protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) @@ -98,7 +97,7 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te protected override IEnumerable RenderAdditionalMethods() { - return new string[] { + return new[] { @" public void DoRoll(ICollection rolls, BowlingGame sut) { diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/CircularBuffer.cs index b68a5ce773..4fea8cff67 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/CircularBuffer.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using Generators.Input; using Generators.Output; @@ -33,7 +32,7 @@ private static string RenderOperation(dynamic operation) case "overwrite": return RenderOverwriteOperation(operation); case "clear": - return RenderClearOperation(operation); + return RenderClearOperation(); default: throw new ArgumentOutOfRangeException($"Unknown operation type: {operation["operation"]}"); } @@ -41,28 +40,22 @@ private static string RenderOperation(dynamic operation) private static string RenderReadOperation(dynamic operation) { - if (operation["should_succeed"]) - { - return $"Assert.Equal({operation["expected"]}, buffer.Read());"; - } - - return "Assert.Throws(() => buffer.Read());"; + return operation["should_succeed"] + ? $"Assert.Equal({operation["expected"]}, buffer.Read());" + : "Assert.Throws(() => buffer.Read());"; } private static string RenderWriteOperation(dynamic operation) { - if (operation["should_succeed"]) - { - return $"buffer.Write({operation["item"]});"; - } - - return $"Assert.Throws(() => buffer.Write({operation["item"]}));"; + return operation["should_succeed"] + ? $"buffer.Write({operation["item"]});" + : $"Assert.Throws(() => buffer.Write({operation["item"]}));"; } private static string RenderOverwriteOperation(dynamic operation) => $"buffer.Overwrite({operation["item"]});"; - private static string RenderClearOperation(dynamic operation) + private static string RenderClearOperation() => "buffer.Clear();"; protected override IEnumerable AdditionalNamespaces => new[] { typeof(InvalidOperationException).Namespace }; diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Clock.cs index 7e33c35ecb..90d6a4ec05 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Clock.cs @@ -47,32 +47,28 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody return RenderEqualToAssert(testMethodBody); } - if (testMethodBody.CanonicalDataCase.Property != PropertyToString) - { - return RenderConsistencyToAssert(testMethodBody); - } - - return base.RenderTestMethodBodyAssert(testMethodBody); + return testMethodBody.CanonicalDataCase.Property != PropertyToString + ? RenderConsistencyToAssert(testMethodBody) + : base.RenderTestMethodBodyAssert(testMethodBody); } private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) { - var template = $"Assert.Equal({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}}.ToString());"; - - yield return TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters); + const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString());"; + return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; } private static IEnumerable RenderEqualToAssert(TestMethodBody testMethodBody) { var expectedParameter = testMethodBody.CanonicalDataCase.Input[ParamClock1]; - var testedValue = "sut"; + const string testedValue = "sut"; var expectedEqual = testMethodBody.CanonicalDataCase.Expected; testMethodBody.AssertTemplateParameters = new { expectedParameter, testedValue }; var template = expectedEqual - ? $"Assert.Equal({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}}); " - : $"Assert.NotEqual({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}});"; + ? "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}); " + : "Assert.NotEqual({{ ExpectedParameter }}, {{ TestedValue }});"; return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; } diff --git a/generators/Exercises/CollatzConjecture.cs b/generators/Exercises/CollatzConjecture.cs index 1e6539d9af..9dd17512b7 100644 --- a/generators/Exercises/CollatzConjecture.cs +++ b/generators/Exercises/CollatzConjecture.cs @@ -1,5 +1,5 @@ -using Generators.Input; -using System; +using System; +using Generators.Input; namespace Generators.Exercises { diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 25633253f5..f9fe6c03ee 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -33,10 +33,9 @@ private static string[] GetInputParameters(CanonicalDataCase canonicalDataCase, protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.UseVariableForExpected) - return RenderComplexNumberAssert(testMethodBody); - - return base.RenderTestMethodBodyAssert(testMethodBody); + return testMethodBody.UseVariableForExpected + ? RenderComplexNumberAssert(testMethodBody) + : base.RenderTestMethodBodyAssert(testMethodBody); } private static IEnumerable RenderComplexNumberAssert(TestMethodBody testMethodBody) @@ -50,10 +49,9 @@ private static IEnumerable RenderComplexNumberAssert(TestMethodBody test private static object ConvertToType(dynamic rawValue) { - if (IsComplexNumber(rawValue)) - return new UnescapedValue($"new ComplexNumber({ValueFormatter.Format(ConvertMathDouble(rawValue[0]))}, {ValueFormatter.Format(ConvertMathDouble(rawValue[1]))})"); - - return rawValue; + return IsComplexNumber(rawValue) + ? new UnescapedValue($"new ComplexNumber({ValueFormatter.Format(ConvertMathDouble(rawValue[0]))}, {ValueFormatter.Format(ConvertMathDouble(rawValue[1]))})") + : rawValue; } private static bool IsComplexNumber(object rawValue) => rawValue is int[] || rawValue is double[] || rawValue is float[] || rawValue is JArray; diff --git a/generators/Exercises/Connect.cs b/generators/Exercises/Connect.cs index fc7cbbe25c..4db2c9ac16 100644 --- a/generators/Exercises/Connect.cs +++ b/generators/Exercises/Connect.cs @@ -1,4 +1,5 @@ -using Generators.Input; +using System.Collections; +using Generators.Input; using Generators.Output; namespace Generators.Exercises @@ -12,7 +13,6 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Property = "result"; canonicalDataCase.Input["board"] = ToMultiLineString(canonicalDataCase.Input["board"]); - //convert to enum switch (canonicalDataCase.Expected) { case "X": @@ -27,7 +27,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC } } - private UnescapedValue ToMultiLineString(string[] input) + private static UnescapedValue ToMultiLineString(IEnumerable input) { const string template = @"new [] diff --git a/generators/Exercises/CustomSet.cs b/generators/Exercises/CustomSet.cs index 88eeede4cc..e9bf267124 100644 --- a/generators/Exercises/CustomSet.cs +++ b/generators/Exercises/CustomSet.cs @@ -39,15 +39,15 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC private static dynamic ConvertCustomSet(dynamic value) { - if (value is bool) - return value; - - if (value is int[] values && values.Length > 0) + switch (value) { - return new UnescapedValue($"new CustomSet({ValueFormatter.Format(values)})"); + case bool _: + return value; + case int[] values when values.Length > 0: + return new UnescapedValue($"new CustomSet({ValueFormatter.Format(values)})"); + default: + return new UnescapedValue("new CustomSet()"); } - - return new UnescapedValue($"new CustomSet()"); } } } \ No newline at end of file diff --git a/generators/Exercises/Dominoes.cs b/generators/Exercises/Dominoes.cs index d6025857b0..f36bf58fff 100644 --- a/generators/Exercises/Dominoes.cs +++ b/generators/Exercises/Dominoes.cs @@ -17,7 +17,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable AdditionalNamespaces => new[] { typeof(Tuple).Namespace }; - private UnescapedValue ConvertInput(dynamic input) + private static UnescapedValue ConvertInput(dynamic input) { var dominoes = (input as JArray).Children(); diff --git a/generators/Exercises/Etl.cs b/generators/Exercises/Etl.cs index 57977c9082..fdaee7d1db 100644 --- a/generators/Exercises/Etl.cs +++ b/generators/Exercises/Etl.cs @@ -1,6 +1,6 @@ -using Generators.Input; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Generators.Input; namespace Generators.Exercises { diff --git a/generators/Exercises/FlattenArray.cs b/generators/Exercises/FlattenArray.cs index 2fe998c988..3a8fedced1 100644 --- a/generators/Exercises/FlattenArray.cs +++ b/generators/Exercises/FlattenArray.cs @@ -19,7 +19,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Input["array"] = new UnescapedValue(ToProperObjArray(stringInput)); } - private string ToProperObjArray(string input) + private static string ToProperObjArray(string input) => input .Replace("System.Int32", "") .Replace("]", "}") diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index 3e752e8025..d46f369e7e 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -77,10 +77,10 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody }; } - private string FormatOwner(dynamic owner) + private static string FormatOwner(dynamic owner) => $"Owner.{(owner as string).ToLowerInvariant().Humanize()}"; - private string FormatTerritory(dynamic territory) + private static string FormatTerritory(dynamic territory) => ValueFormatter.Format((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); protected override IEnumerable AdditionalNamespaces => new[] diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index ede8c874ad..31232e315f 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using Generators.Input; using Generators.Output; @@ -19,12 +20,14 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC private static dynamic ConvertExpected(dynamic expected) { - var arr = expected as object[]; - - if (arr == null || arr.Length == 0) - return ""; - - return new UnescapedValue(Environment.NewLine + string.Join(Environment.NewLine, arr.Select(((x, i) => $" \"{x}\\n\"{(i < arr.Length - 1 ? " +" : "")}")))); + if (expected is object[] arr && arr.Length != 0) + return new UnescapedValue( + Environment.NewLine + + string.Join( + Environment.NewLine, + arr.Select((x, i) => $" \"{x}\\n\"{(i < arr.Length - 1 ? " +" : "")}"))); + + return ""; } protected override TestClass CreateTestClass() @@ -38,7 +41,7 @@ protected override TestClass CreateTestClass() protected override IEnumerable AdditionalNamespaces => new[] { typeof(IDisposable).Namespace, - typeof(System.IO.File).Namespace + typeof(File).Namespace }; protected override IEnumerable RenderAdditionalMethods() diff --git a/generators/Exercises/LargestSeriesProduct.cs b/generators/Exercises/LargestSeriesProduct.cs index 1c44de0093..3149d1d9d6 100644 --- a/generators/Exercises/LargestSeriesProduct.cs +++ b/generators/Exercises/LargestSeriesProduct.cs @@ -1,3 +1,4 @@ +using System; using Generators.Input; namespace Generators.Exercises @@ -9,7 +10,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Property = "GetLargestProduct"; var caseInputLessThanZero = (long)canonicalDataCase.Expected == -1; - canonicalDataCase.ExceptionThrown = caseInputLessThanZero ? typeof(System.ArgumentException) : null; + canonicalDataCase.ExceptionThrown = caseInputLessThanZero ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/ListOps.cs b/generators/Exercises/ListOps.cs index 552f1fb8a9..9b82463118 100644 --- a/generators/Exercises/ListOps.cs +++ b/generators/Exercises/ListOps.cs @@ -33,10 +33,9 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC if (canonicalDataCase.Expected is IEnumerable) { - if (canonicalDataCase.Input.ContainsKey("lists")) - canonicalDataCase.Expected = ConvertToNestedList(canonicalDataCase.Expected, false); - else - canonicalDataCase.Expected = ConvertToList(canonicalDataCase.Expected); + canonicalDataCase.Expected = canonicalDataCase.Input.ContainsKey("lists") + ? ConvertToNestedList(canonicalDataCase.Expected, false) + : ConvertToList(canonicalDataCase.Expected); } } @@ -56,20 +55,16 @@ private static UnescapedValue ConvertToFunction(string property, dynamic functio private static dynamic ConvertToList(dynamic value) { - if (value is JArray jArray) + switch (value) { - if (jArray.Count == 0) + case JArray jArray when jArray.Count == 0: return new List(); - - if (jArray.Any(jToken => jToken.Type == JTokenType.Array)) + case JArray jArray when jArray.Any(jToken => jToken.Type == JTokenType.Array): return jArray.Select(ConvertToList).ToList(); - - return jArray.ToObject().ToList(); - } - - if (value is IEnumerable ints) - { - return ints.ToList(); + case JArray jArray: + return jArray.ToObject().ToList(); + case IEnumerable ints: + return ints.ToList(); } return value; @@ -77,35 +72,30 @@ private static dynamic ConvertToList(dynamic value) private static dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) { - if (value is JArray jArray) + switch (value) { - if (jArray.Count == 0) - { + case JArray jArray when jArray.Count == 0: if (unescapeEmpty) { return new UnescapedValue("new List>()"); } return new List(); - } - - var nestedList = jArray - .Children() - .Select(ConvertToList) - .Select(ValueFormatter.Format) - .Select(formattedValue => new UnescapedValue(formattedValue)) - .ToList(); - - return new UnescapedValue(ValueFormatter.Format(nestedList) - .Replace("", "") - .Replace("new List { new List", "new List> { new List") - .Replace("new[] { new List>", "new List>> { new List>") - .Replace("new[] { new List", "new List> { new List")); - } - - if (value is IEnumerable ints) - { - return new UnescapedValue(ValueFormatter.Format(ints.ToList())); + case JArray jArray: + var nestedList = jArray + .Children() + .Select(ConvertToList) + .Select(ValueFormatter.Format) + .Select(formattedValue => new UnescapedValue(formattedValue)) + .ToList(); + + return new UnescapedValue(ValueFormatter.Format(nestedList) + .Replace("", "") + .Replace("new List { new List", "new List> { new List") + .Replace("new[] { new List>", "new List>> { new List>") + .Replace("new[] { new List", "new List> { new List")); + case IEnumerable ints: + return new UnescapedValue(ValueFormatter.Format(ints.ToList())); } return value; diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 5891182d44..3d94c160ae 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -32,7 +32,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var template = $"Assert.Equal({{{{ ExpectedParameter }}}}, {{{{ TestedValue }}}}.ToString(\"yyyy-MM-dd\"));"; + const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString(\"yyyy-MM-dd\"));"; return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; } diff --git a/generators/Exercises/Minesweeper.cs b/generators/Exercises/Minesweeper.cs index f3378aeee2..cebdaf79f6 100644 --- a/generators/Exercises/Minesweeper.cs +++ b/generators/Exercises/Minesweeper.cs @@ -17,9 +17,9 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Expected = ToMultiLineString(canonicalDataCase.Expected); } - private UnescapedValue ToMultiLineString(JArray input) => new UnescapedValue("Array.Empty()"); + private static UnescapedValue ToMultiLineString(JArray input) => new UnescapedValue("Array.Empty()"); - private UnescapedValue ToMultiLineString(IEnumerable input) + private static UnescapedValue ToMultiLineString(IEnumerable input) { const string template = @"new string[] diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index 0edeb4cd36..aec336717a 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -1,7 +1,7 @@ -using Generators.Input; -using Generators.Output; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Generators.Input; +using Generators.Output; namespace Generators.Exercises { @@ -9,12 +9,12 @@ public class NucleotideCount : GeneratorExercise { protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - if (!((Dictionary)canonicalDataCase.Expected).ContainsKey("error")) - { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters("strand"); - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); - } + if (((Dictionary) canonicalDataCase.Expected).ContainsKey("error")) + return; + + canonicalDataCase.UseVariableForExpected = true; + canonicalDataCase.SetConstructorInputParameters("strand"); + canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); } private static dynamic ConvertExpected(dynamic expected) @@ -24,15 +24,12 @@ private static dynamic ConvertExpected(dynamic expected) protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.UseVariableForExpected) - { - return RenderEqualBodyAssert(testMethodBody); - } - - return RenderThrowsBodyAssert(testMethodBody); + return testMethodBody.UseVariableForExpected + ? RenderEqualBodyAssert(testMethodBody) + : RenderThrowsBodyAssert(testMethodBody); } - private IEnumerable RenderEqualBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderEqualBodyAssert(TestMethodBody testMethodBody) { const string template = @"Assert.Equal(expected, sut.{{ TestedMethodName }});"; @@ -44,7 +41,7 @@ private IEnumerable RenderEqualBodyAssert(TestMethodBody testMethodBody) return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private IEnumerable RenderThrowsBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderThrowsBodyAssert(TestMethodBody testMethodBody) { const string template = @"Assert.Throws(() => new NucleotideCount(""{{ Input }}""));"; diff --git a/generators/Exercises/OcrNumbers.cs b/generators/Exercises/OcrNumbers.cs index 69b4fe5a5f..559fe113af 100644 --- a/generators/Exercises/OcrNumbers.cs +++ b/generators/Exercises/OcrNumbers.cs @@ -1,8 +1,8 @@ using System; +using System.Collections; using System.Collections.Generic; using Generators.Input; using Generators.Output; -using Newtonsoft.Json.Linq; namespace Generators.Exercises { @@ -10,19 +10,14 @@ public class OcrNumbers : GeneratorExercise { protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { - canonicalDataCase.ExceptionThrown = (canonicalDataCase.Expected is int && canonicalDataCase.Expected <= 0) ? typeof(ArgumentException) : null; + canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is int && canonicalDataCase.Expected <= 0 ? typeof(ArgumentException) : null; canonicalDataCase.Input["rows"] = ToDigitStringRepresentation(canonicalDataCase.Input["rows"]); canonicalDataCase.Expected = canonicalDataCase.Expected.ToString(); canonicalDataCase.UseVariableForTested = true; canonicalDataCase.UseVariablesForInput = true; } - private UnescapedValue ToMultiLineString(JArray input) - { - return new UnescapedValue("Array.Empty()"); - } - - private UnescapedValue ToDigitStringRepresentation(string[] input) + private static UnescapedValue ToDigitStringRepresentation(IEnumerable input) { const string template = @" {% for item in {{input}} %}{% if forloop.first == true %}""{{item}}"" + ""\n"" +{% continue %}{% endif %} ""{{item}}""{% if forloop.last == false %} + ""\n"" +{% endif %}{% endfor %}"; diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/PalindromeProducts.cs index 7fb4c4dd7c..64c3b53eb8 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/PalindromeProducts.cs @@ -37,7 +37,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody }; } - private string FormatCoordinates(dynamic coordinates) + private static string FormatCoordinates(dynamic coordinates) => ValueFormatter.Format((coordinates as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); } } \ No newline at end of file diff --git a/generators/Exercises/QueenAttack.cs b/generators/Exercises/QueenAttack.cs index d5bb6b2d40..edd19e4281 100644 --- a/generators/Exercises/QueenAttack.cs +++ b/generators/Exercises/QueenAttack.cs @@ -1,7 +1,7 @@ -using Generators.Input; -using Generators.Output; -using System; +using System; using System.Collections.Generic; +using Generators.Input; +using Generators.Output; namespace Generators.Exercises { @@ -18,10 +18,9 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody if (testMethodBody.CanonicalDataCase.Property == "canAttack") return new[] { RenderCanAttackAssert(testMethodBody) }; - if (testMethodBody.UseVariableForTested) - return Array.Empty(); - - return base.RenderTestMethodBodyAssert(testMethodBody); + return testMethodBody.UseVariableForTested + ? Array.Empty() + : base.RenderTestMethodBodyAssert(testMethodBody); } private static string RenderCanAttackAssert(TestMethodBody testMethodBody) @@ -40,7 +39,7 @@ private static string RenderCanAttackAssert(TestMethodBody testMethodBody) whiteQueenY = whiteQueenPositions.Item2, blackQueenX = blackQueenPositions.Item1, blackQueenY = blackQueenPositions.Item2, - Expected = testMethodBody.CanonicalDataCase.Expected + testMethodBody.CanonicalDataCase.Expected }; return TemplateRenderer.RenderInline(template, templateParameters); diff --git a/generators/Exercises/RationalNumbers.cs b/generators/Exercises/RationalNumbers.cs index a2f4d9e539..e83816cefd 100644 --- a/generators/Exercises/RationalNumbers.cs +++ b/generators/Exercises/RationalNumbers.cs @@ -5,10 +5,10 @@ namespace Generators.Exercises { public struct RationalNumber { - public RationalNumber(int[] n) + public RationalNumber(IReadOnlyList n) { - this.Numerator = n[0]; - this.Denominator = n[1]; + Numerator = n[0]; + Denominator = n[1]; } public int Numerator { get; } @@ -19,12 +19,12 @@ public class RationalNumbers : GeneratorExercise { protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var input = testMethodBody.CanonicalDataCase.Properties["input"] as System.Collections.Generic.Dictionary; + var input = testMethodBody.CanonicalDataCase.Properties["input"] as Dictionary; var operation = testMethodBody.CanonicalDataCase.Properties["property"].ToString(); var expected = testMethodBody.CanonicalDataCase.Properties["expected"]; var operationName = char.ToUpper(operation[0]) + operation.Substring(1); var assertCodeLine = ""; - var operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; + const string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; string operationCode = operationsWithOverloading.Substring(operationsWithOverloading.IndexOf(operation.ToLower()) + 4, 1); switch (operation.ToLower()) @@ -61,7 +61,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody var x = input["x"].ToString(); var r = new RationalNumber((int[])input["r"]); var e = ValueFormatter.Format(expected); - var p = precision(e); + var p = Precision(e); assertCodeLine = "Assert.Equal(" + $"{e}, {x}.{operationName}(new RationalNumber({r.Numerator}, {r.Denominator})), {p});"; } break; @@ -70,6 +70,9 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody return new[] { TemplateRenderer.RenderInline(assertCodeLine, testMethodBody.AssertTemplateParameters) }; } - private static int precision(object rawValue) => rawValue.ToString().Split(new char[] { '.' }).Length <= 1 ? 0 : rawValue.ToString().Split(new char[] { '.' })[1].Length; + private static int Precision(object rawValue) + => rawValue.ToString().Split(new[] { '.' }).Length <= 1 + ? 0 + : rawValue.ToString().Split(new[] { '.' })[1].Length; } } \ No newline at end of file diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index effd73fb98..29671a217e 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -57,12 +57,9 @@ private static string RenderComputeFunction(dynamic computeFunction) { var match = Regex.Match((string)computeFunction, "if (.+) then (.+) else (.+)"); - if (match.Success) - { - return $"{match.Groups[1]} ? {match.Groups[2]} : {match.Groups[3]}"; - } - - return computeFunction; + return match.Success + ? $"{match.Groups[1]} ? {match.Groups[2]} : {match.Groups[3]}" + : (string) computeFunction; } private static string RenderOperations(dynamic operations) @@ -118,7 +115,7 @@ private static string RenderOperation(dynamic operation) var removeCallbackName = ToVariableName(operation["name"]); return $"{ToVariableName(operation["cell"])}.Changed -= {removeCallbackName};"; default: - return $"qweqwe"; + return "qweqwe"; } } diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index 6b31451697..3190aef77d 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -35,9 +35,9 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te } } - private IEnumerable RenderDefaultMethodBodyAct(TestMethodBody testMethodBody) + private static IEnumerable RenderDefaultMethodBodyAct(TestMethodBody testMethodBody) { - var template = @"sut.{{MethodInvocation}}();"; + const string template = @"sut.{{MethodInvocation}}();"; var templateParameters = new { @@ -47,9 +47,9 @@ private IEnumerable RenderDefaultMethodBodyAct(TestMethodBody testMethod return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private IEnumerable RenderInstructionsMethodBodyAct(TestMethodBody testMethodBody) + private static IEnumerable RenderInstructionsMethodBodyAct(TestMethodBody testMethodBody) { - var template = @"sut.{{MethodInvocation}}(""{{Instructions}}"");"; + const string template = @"sut.{{MethodInvocation}}(""{{Instructions}}"");"; var templateParameters = new { @@ -87,7 +87,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody return new[] { TemplateRenderer.RenderInline(template.ToString(), templateParameters) }; } - private string GetDirectionEnum(string direction) + private static string GetDirectionEnum(string direction) { switch (direction) { @@ -100,6 +100,6 @@ private string GetDirectionEnum(string direction) } } - private string GetCoordinateInstance(dynamic coordinates) => $"new Coordinate({coordinates["x"]}, {coordinates["y"]})"; + private static string GetCoordinateInstance(dynamic coordinates) => $"new Coordinate({coordinates["x"]}, {coordinates["y"]})"; } } diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index dbaba6cfb9..731873c6f4 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -13,12 +13,9 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.CanonicalDataCase.Property == "consistency") - { - return RenderConsistencyToAssert(testMethodBody); - } - - return base.RenderTestMethodBodyAssert(testMethodBody); + return testMethodBody.CanonicalDataCase.Property == "consistency" + ? RenderConsistencyToAssert(testMethodBody) + : base.RenderTestMethodBodyAssert(testMethodBody); } private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index 654f56d316..d809e05301 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -19,15 +19,13 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Input["matrix"] = ToMultiDimensionalArray(canonicalDataCase.Input["matrix"]); - var array = canonicalDataCase.Expected as Array; - - if (array != null) + if (canonicalDataCase.Expected is Array array) { canonicalDataCase.Expected = ToTupleCollection(array); } } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(System.String).Namespace }; + protected override IEnumerable AdditionalNamespaces => new[] { typeof(string).Namespace }; private static dynamic ToMultiDimensionalArray(dynamic array) { @@ -38,11 +36,11 @@ private static dynamic ToMultiDimensionalArray(dynamic array) return jArray.ToObject(); } - private IEnumerable> ToTupleCollection(Array array) + private static IEnumerable> ToTupleCollection(Array array) { for (var x = 0; x < array.GetLength(0); x++) { - var current = ((Array)array).GetValue(x) as Dictionary; + var current = array.GetValue(x) as Dictionary; yield return new Tuple(current["row"].ToString(), current["column"].ToString()); } } diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index a3877ce7d1..6d34b19e52 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -25,15 +25,16 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC if (canonicalDataCase.Input.TryGetValue("ciphertext", out var cipherText)) { - if (cipherText == "cipher.key") + switch (cipherText) { - canonicalDataCase.Input["ciphertext"] = new UnescapedValue("sut.Key.Substring(0, 10)"); - } - else if (cipherText == "cipher.encode") - { - var plaintext = ValueFormatter.Format(canonicalDataCase.Input["plaintext"]); - canonicalDataCase.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); - canonicalDataCase.SetInputParameters("ciphertext"); + case "cipher.key": + canonicalDataCase.Input["ciphertext"] = new UnescapedValue("sut.Key.Substring(0, 10)"); + break; + case "cipher.encode": + var plaintext = ValueFormatter.Format(canonicalDataCase.Input["plaintext"]); + canonicalDataCase.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); + canonicalDataCase.SetInputParameters("ciphertext"); + break; } } @@ -45,18 +46,17 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.CanonicalDataCase.Property == "new") + switch (testMethodBody.CanonicalDataCase.Property) { - var key = ValueFormatter.Format(testMethodBody.CanonicalDataCase.Input["key"]); - return new[] { $"Assert.Throws(() => new SimpleCipher({key}));" }; + case "new": + var key = ValueFormatter.Format(testMethodBody.CanonicalDataCase.Input["key"]); + return new[] { $"Assert.Throws(() => new SimpleCipher({key}));" }; + case "key": + var pattern = ValueFormatter.Format(testMethodBody.CanonicalDataCase.Expected["match"]); + return new[] { $"Assert.Matches({pattern}, sut.Key);" }; + default: + return base.RenderTestMethodBodyAssert(testMethodBody); } - else if (testMethodBody.CanonicalDataCase.Property == "key") - { - var pattern = ValueFormatter.Format(testMethodBody.CanonicalDataCase.Expected["match"]); - return new[] { $"Assert.Matches({pattern}, sut.Key);" }; - } - - return base.RenderTestMethodBodyAssert(testMethodBody); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(ArgumentException).Namespace }; diff --git a/generators/Exercises/SpiralMatrix.cs b/generators/Exercises/SpiralMatrix.cs index a3f098b1d0..a003ab14b6 100644 --- a/generators/Exercises/SpiralMatrix.cs +++ b/generators/Exercises/SpiralMatrix.cs @@ -13,7 +13,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); } - private dynamic ConvertExpected(dynamic expected) + private static dynamic ConvertExpected(dynamic expected) { var jArray = (JArray)expected; diff --git a/generators/Exercises/Sublist.cs b/generators/Exercises/Sublist.cs index 91511d5602..db9ba1f4c3 100644 --- a/generators/Exercises/Sublist.cs +++ b/generators/Exercises/Sublist.cs @@ -1,5 +1,5 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; +using System.Linq; using Generators.Input; using Generators.Output; using Humanizer; @@ -8,13 +8,6 @@ namespace Generators.Exercises { public class Sublist : GeneratorExercise { - protected override IEnumerable AdditionalNamespaces => new[] { typeof(IList).Namespace }; - - private UnescapedValue InputValues(int[] list) - { - var template = (list != null) ? string.Join(", ", Array.ConvertAll(list, (x) => { return $"{x}"; })) : ""; - return new UnescapedValue($"new List() {{ {template} }}".Replace(" ", " ")); - } protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) { canonicalDataCase.Input["listOne"] = InputValues(canonicalDataCase.Input["listOne"] as int[]); @@ -23,6 +16,14 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC canonicalDataCase.Property = "classify"; canonicalDataCase.Expected = new UnescapedValue($"SublistType.{(canonicalDataCase.Expected as string).Dehumanize()}"); } + + protected override IEnumerable AdditionalNamespaces => new[] { typeof(IList).Namespace }; + + private static UnescapedValue InputValues(int[] list) + { + var template = list != null ? string.Join(", ", list.Select(x => x.ToString())) : ""; + return new UnescapedValue($"new List() {{ {template} }}".Replace(" ", " ")); + } } } diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index bb75922fc9..abac948bf3 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Text; using Generators.Input; using Generators.Output; @@ -20,19 +22,19 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace, - typeof(System.IO.Stream).Namespace, - typeof(System.Text.UTF8Encoding).Namespace + typeof(Stream).Namespace, + typeof(UTF8Encoding).Namespace }; protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var template = @"Assert.Equal(expected, RunTally(rows));"; + const string template = @"Assert.Equal(expected, RunTally(rows));"; return new[] { TemplateRenderer.RenderInline(template, new { }) }; } protected override IEnumerable RenderAdditionalMethods() { - var methods = @" + const string methods = @" private string RunTally(string input) { var encoding = new UTF8Encoding(); @@ -44,7 +46,7 @@ private string RunTally(string input) return encoding.GetString(outStream.ToArray()); } }"; - return methods.Split("", System.StringSplitOptions.None); + return methods.Split(""); } } } diff --git a/generators/Exercises/TwoBucket.cs b/generators/Exercises/TwoBucket.cs index 872882a1a5..9afced3f1f 100644 --- a/generators/Exercises/TwoBucket.cs +++ b/generators/Exercises/TwoBucket.cs @@ -38,7 +38,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody { MovesExpected = testMethodBody.CanonicalDataCase.Expected["moves"], OtherBucketExpected = testMethodBody.CanonicalDataCase.Expected["otherBucket"], - GoalBucketExpected = testMethodBody.CanonicalDataCase.Expected["goalBucket"], + GoalBucketExpected = testMethodBody.CanonicalDataCase.Expected["goalBucket"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/VariableLengthQuantity.cs b/generators/Exercises/VariableLengthQuantity.cs index 83380447cc..169a9414f1 100644 --- a/generators/Exercises/VariableLengthQuantity.cs +++ b/generators/Exercises/VariableLengthQuantity.cs @@ -23,16 +23,15 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; - private dynamic FormatUInt32Array(dynamic input) + private static dynamic FormatUInt32Array(dynamic input) { var numbers = ToUInt32Array(input as IEnumerable); return numbers.Select(number => new UnescapedValue(string.Format("0x{0:X}u", number))).ToArray(); } - private IEnumerable ToUInt32Array(IEnumerable input) + private static IEnumerable ToUInt32Array(IEnumerable input) { - foreach (var number in input) - yield return Convert.ToUInt32(number.ToString()); + return input.Cast().Select(number => Convert.ToUInt32(number.ToString())); } } } \ No newline at end of file diff --git a/generators/Exercises/WordCount.cs b/generators/Exercises/WordCount.cs index bd8a1d37b8..a45fc634ba 100644 --- a/generators/Exercises/WordCount.cs +++ b/generators/Exercises/WordCount.cs @@ -1,6 +1,6 @@ -using Generators.Input; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; +using Generators.Input; namespace Generators.Exercises { diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index 3cdcd48046..a0ca603c9e 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -27,7 +27,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC "{" }; - expected.AddRange(expectedDictionary.Select(((kv, i) => $" [\"{kv.Key}\"] = {FormatPosition(kv.Value)}{(i < expectedDictionary.Count - 1 ? "," : "")}"))); + expected.AddRange(expectedDictionary.Select((kv, i) => $" [\"{kv.Key}\"] = {FormatPosition(kv.Value)}{(i < expectedDictionary.Count - 1 ? "," : "")}")); expected.Add("}"); canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); @@ -41,27 +41,21 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody yield return RenderTestMethodBodyAssertForSearchWord(kv.Key, kv.Value); } - private string RenderTestMethodBodyAssertForSearchWord(string word, dynamic expected) + private static string RenderTestMethodBodyAssertForSearchWord(string word, dynamic expected) { - if (expected == null) - { - return $"Assert.Null(expected[\"{word}\"]);"; - } - - return $"Assert.Equal(expected[\"{word}\"], actual[\"{word}\"]);"; + return expected == null + ? $"Assert.Null(expected[\"{word}\"]);" + : $"Assert.Equal(expected[\"{word}\"], actual[\"{word}\"]);"; } - private string FormatPosition(dynamic position) + private static string FormatPosition(dynamic position) { - if (position == null) - { - return "null"; - } - - return ValueFormatter.Format((FormatCoordinate(position["start"]), FormatCoordinate(position["end"]))); + return position == null + ? "null" : + ValueFormatter.Format((FormatCoordinate(position["start"]), FormatCoordinate(position["end"]))); } - private string FormatCoordinate(dynamic coordinate) + private static string FormatCoordinate(dynamic coordinate) => ValueFormatter.Format((coordinate["column"], coordinate["row"])); protected override IEnumerable AdditionalNamespaces => new[] diff --git a/generators/Exercises/Zipper.cs b/generators/Exercises/Zipper.cs index a16c51bfef..1793010143 100644 --- a/generators/Exercises/Zipper.cs +++ b/generators/Exercises/Zipper.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using Generators.Output; using Humanizer; diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index 5c59c53dc0..d3f2967c78 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -42,7 +42,7 @@ protected virtual IEnumerable RenderTestMethodBodyAssert(TestMethodBody protected virtual IEnumerable RenderAdditionalMethods() => Array.Empty(); - private HashSet GetUsingNamespaces() + private IEnumerable GetUsingNamespaces() { var usingNamespaces = new HashSet { "Xunit" }; @@ -95,17 +95,15 @@ protected virtual TestMethodBody CreateTestMethodBody(CanonicalDataCase canonica return new TestMethodBodyWithExceptionCheck(canonicalDataCase, _canonicalData); } - if (canonicalDataCase.Expected is bool) + switch (canonicalDataCase.Expected) { - return new TestMethodBodyWithBooleanCheck(canonicalDataCase, _canonicalData); + case bool _: + return new TestMethodBodyWithBooleanCheck(canonicalDataCase, _canonicalData); + case null: + return new TestMethodBodyWithNullCheck(canonicalDataCase, _canonicalData); + default: + return new TestMethodBodyWithEqualityCheck(canonicalDataCase, _canonicalData); } - - if (canonicalDataCase.Expected is null) - { - return new TestMethodBodyWithNullCheck(canonicalDataCase, _canonicalData); - } - - return new TestMethodBodyWithEqualityCheck(canonicalDataCase, _canonicalData); } } } diff --git a/generators/Input/CanonicalDataCaseParser.cs b/generators/Input/CanonicalDataCaseParser.cs index 9452347c82..f9cc25b36b 100644 --- a/generators/Input/CanonicalDataCaseParser.cs +++ b/generators/Input/CanonicalDataCaseParser.cs @@ -120,13 +120,13 @@ private static dynamic ConvertJArray(JArray jArray) return jArray.Select(ConvertJToken).ToArray(); case JTokenType.Integer: var strings = jArray.ToObject(); - if (strings.All(str => int.TryParse(str, out var _))) + if (strings.All(str => int.TryParse(str, out _))) return jArray.ToObject(); - if (strings.All(str => long.TryParse(str, out var _))) + if (strings.All(str => long.TryParse(str, out _))) return jArray.ToObject(); - if (strings.All(str => ulong.TryParse(str, out var _))) + if (strings.All(str => ulong.TryParse(str, out _))) return jArray.ToObject(); return strings; diff --git a/generators/Input/ConfigFile.cs b/generators/Input/ConfigFile.cs index 55fc22fc0d..ce3d77158f 100644 --- a/generators/Input/ConfigFile.cs +++ b/generators/Input/ConfigFile.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using Newtonsoft.Json; using Generators.Output; +using Newtonsoft.Json; namespace Generators.Input { diff --git a/generators/Input/ConvertHelper.cs b/generators/Input/ConvertHelper.cs index 81b0c66216..88e04d1f80 100644 --- a/generators/Input/ConvertHelper.cs +++ b/generators/Input/ConvertHelper.cs @@ -6,22 +6,20 @@ public static class ConvertHelper public static string ToMultiLineString(this object obj, string empty) { - var arr = obj as object[]; + if (obj is object[] arr && arr.Length != 0) + return string.Join("\n", arr); + + return empty; - if (arr == null || arr.Length == 0) - return empty; - - return string.Join("\n", obj as object[]); } public static T[] ToArray(this object obj) { - var arr = obj as T[]; - - if (arr == null || arr.Length == 0) - return new T[0]; + if (obj is T[] arr && arr.Length != 0) + return arr; + + return new T[0]; - return arr; } } } \ No newline at end of file diff --git a/generators/Output/ExerciseWriter.cs b/generators/Output/ExerciseWriter.cs index 728096c1cf..c85da596c2 100644 --- a/generators/Output/ExerciseWriter.cs +++ b/generators/Output/ExerciseWriter.cs @@ -4,7 +4,7 @@ namespace Generators.Output { public class ExerciseWriter { - public virtual void WriteToFile(GeneratorExercise generatorExercise) + public static void WriteToFile(GeneratorExercise generatorExercise) { var testClassFilePath = TestClassFilePath(generatorExercise); var testClassContents = generatorExercise.Render(); diff --git a/generators/Output/NameExtensions.cs b/generators/Output/NameExtensions.cs index e3c7121b23..fa3d5ae768 100644 --- a/generators/Output/NameExtensions.cs +++ b/generators/Output/NameExtensions.cs @@ -26,10 +26,7 @@ public static string ToTestMethodName(this string input) if (char.IsDigit(methodName[0])) return "Number_" + methodName; - if (!char.IsLetter(methodName[0])) - return "Test_"; - - return methodName; + return !char.IsLetter(methodName[0]) ? "Test_" : methodName; } public static string ToTestedMethodName(this string input) => input.Dehumanize(); diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index f02403b7a8..d6597234fb 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -6,8 +6,8 @@ public class TestClass { public string ClassName { get; set; } public string CanonicalDataVersion { get; set; } - public IList Methods { get; set; } - public ISet UsingNamespaces { get; set; } + public IEnumerable Methods { get; set; } + public IEnumerable UsingNamespaces { get; set; } public string TemplateName { get; set; } = "TestClass"; public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { ClassName, CanonicalDataVersion, Methods, UsingNamespaces }); diff --git a/generators/Output/TestMethodBodyData.cs b/generators/Output/TestMethodBodyData.cs index 9d4cd6c406..8527935d27 100644 --- a/generators/Output/TestMethodBodyData.cs +++ b/generators/Output/TestMethodBodyData.cs @@ -21,7 +21,6 @@ public class TestMethodBodyData public string ConstructorParameters => _testMethodBody.UseVariablesForConstructorParameters ? string.Join(", ", CanonicalDataCase.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); private CanonicalDataCase CanonicalDataCase => _testMethodBody.CanonicalDataCase; - private CanonicalData CanonicalData => _testMethodBody.CanonicalData; private string TestedClassName => CanonicalDataCase.Exercise.ToTestedClassName(); private string TestedMethodName => CanonicalDataCase.Property.ToTestedMethodName(); diff --git a/generators/Output/TypesExtensions.cs b/generators/Output/TypesExtensions.cs index 40dae0590a..9880aa684b 100644 --- a/generators/Output/TypesExtensions.cs +++ b/generators/Output/TypesExtensions.cs @@ -4,14 +4,6 @@ namespace Generators.Output { public static class TypesExtensions { - public static IEnumerable SliceColumn(this T[,] array, int column) - { - for (var i = array.GetLowerBound(0); i <= array.GetUpperBound(0); i++) - { - yield return array[i, column]; - } - } - public static IEnumerable SliceRow(this T[,] array, int row) { for (var i = array.GetLowerBound(1); i <= array.GetUpperBound(1); i++) diff --git a/generators/Output/ValueFormatter.cs b/generators/Output/ValueFormatter.cs index a7da0774da..bd973ff969 100644 --- a/generators/Output/ValueFormatter.cs +++ b/generators/Output/ValueFormatter.cs @@ -37,10 +37,10 @@ public static string Format(object val) } } - public static string[] FormatVariables(IDictionary dict) + public static IEnumerable FormatVariables(IDictionary dict) => dict.Keys.SelectMany(key => FormatVariable(dict[key], key.ToVariableName())).ToArray(); - public static string[] FormatVariable(object val, string name) + public static IEnumerable FormatVariable(object val, string name) { switch (val) { @@ -78,7 +78,7 @@ public static string[] FormatVariable(object val, string name) private static string Format(this ulong ulng) => $"{ulng}UL"; - private static string Format(this Enum @enumeration) => + private static string Format(this Enum enumeration) => $"{enumeration.GetType().Name}.{enumeration}"; private static string Format(this Tuple tuple) => @@ -133,7 +133,7 @@ private static string Format(this IEnumerable> tuples) => private static string ToNestedArray(this IEnumerable enumerable) => enumerable.Any() ? $"{{ {string.Join(", ", enumerable)} }}" : string.Empty; - private static string[] FormatMultiLineString(string name, string str) + private static IEnumerable FormatMultiLineString(string name, string str) { var strings = str.Split('\n'); var formattedStrings = strings @@ -144,10 +144,10 @@ private static string[] FormatMultiLineString(string name, string str) return FormatMultiLineVariable(formattedStrings, name); } - private static string[] FormatMultiLineEnumerable(IEnumerable enumerable, string name, string constructor = null) + private static IEnumerable FormatMultiLineEnumerable(IEnumerable enumerable, string name, string constructor = null) => FormatMultiLineVariable(enumerable.Prepend("{").Append("}"), name, constructor); - private static string[] FormatMultiLineVariable(IEnumerable enumerable, string name, string constructor = null) + private static IEnumerable FormatMultiLineVariable(IEnumerable enumerable, string name, string constructor = null) => enumerable.Select(line => line == "{" || line == "}" ? line : line.Indent()) .AddTrailingSemicolon() .Prepend($"var {name} = {constructor}") From ff1f7bca4e58b314e4a236d82f3f6be531272554 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 19:07:53 +0200 Subject: [PATCH 14/97] generators: Remove unused parameter --- generators/GeneratorExercise.cs | 10 +++++----- generators/Output/TestMethodBody.cs | 6 ++---- generators/Output/TestMethodBodyWithBooleanCheck.cs | 2 +- generators/Output/TestMethodBodyWithEqualityCheck.cs | 2 +- generators/Output/TestMethodBodyWithExceptionCheck.cs | 2 +- generators/Output/TestMethodBodyWithNullCheck.cs | 2 +- 6 files changed, 11 insertions(+), 13 deletions(-) diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index d3f2967c78..9887b7c9dc 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -54,7 +54,7 @@ private IEnumerable GetUsingNamespaces() return usingNamespaces; } - private string[] RenderTestMethods() => _canonicalData.Cases.Select(RenderTestMethod).Concat(RenderAdditionalMethods()).ToArray(); + private IEnumerable RenderTestMethods() => _canonicalData.Cases.Select(RenderTestMethod).Concat(RenderAdditionalMethods()).ToArray(); protected virtual TestClass CreateTestClass() => new TestClass { @@ -92,17 +92,17 @@ protected virtual TestMethodBody CreateTestMethodBody(CanonicalDataCase canonica { if (canonicalDataCase.ExceptionThrown != null) { - return new TestMethodBodyWithExceptionCheck(canonicalDataCase, _canonicalData); + return new TestMethodBodyWithExceptionCheck(canonicalDataCase); } switch (canonicalDataCase.Expected) { case bool _: - return new TestMethodBodyWithBooleanCheck(canonicalDataCase, _canonicalData); + return new TestMethodBodyWithBooleanCheck(canonicalDataCase); case null: - return new TestMethodBodyWithNullCheck(canonicalDataCase, _canonicalData); + return new TestMethodBodyWithNullCheck(canonicalDataCase); default: - return new TestMethodBodyWithEqualityCheck(canonicalDataCase, _canonicalData); + return new TestMethodBodyWithEqualityCheck(canonicalDataCase); } } } diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index 930c3182c5..b2f6a3c16b 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -5,11 +5,10 @@ namespace Generators.Output { public abstract class TestMethodBody { - protected TestMethodBody(CanonicalDataCase canonicalDataCase, CanonicalData canonicalData) + protected TestMethodBody(CanonicalDataCase canonicalDataCase) { CanonicalDataCase = canonicalDataCase; - CanonicalData = canonicalData; - + Data = new TestMethodBodyData(this); InitializeTemplateParameters(); } @@ -17,7 +16,6 @@ protected TestMethodBody(CanonicalDataCase canonicalDataCase, CanonicalData cano public string TemplateName { get; set; } = "TestMethodBody"; public CanonicalDataCase CanonicalDataCase { get; } - public CanonicalData CanonicalData { get; } public TestMethodBodyData Data { get; } public virtual bool UseVariablesForInput => CanonicalDataCase.UseVariablesForInput; diff --git a/generators/Output/TestMethodBodyWithBooleanCheck.cs b/generators/Output/TestMethodBodyWithBooleanCheck.cs index 6a8c73d720..a72bf8444d 100644 --- a/generators/Output/TestMethodBodyWithBooleanCheck.cs +++ b/generators/Output/TestMethodBodyWithBooleanCheck.cs @@ -5,7 +5,7 @@ namespace Generators.Output { public class TestMethodBodyWithBooleanCheck : TestMethodBody { - public TestMethodBodyWithBooleanCheck(CanonicalDataCase canonicalDataCase, CanonicalData canonicalData) : base(canonicalDataCase, canonicalData) + public TestMethodBodyWithBooleanCheck(CanonicalDataCase canonicalDataCase) : base(canonicalDataCase) { AssertTemplateName = "AssertBoolean"; AssertTemplateParameters = new { BooleanAssertMethod, Data.TestedValue }; diff --git a/generators/Output/TestMethodBodyWithEqualityCheck.cs b/generators/Output/TestMethodBodyWithEqualityCheck.cs index 5a19020ee6..295513f40b 100644 --- a/generators/Output/TestMethodBodyWithEqualityCheck.cs +++ b/generators/Output/TestMethodBodyWithEqualityCheck.cs @@ -5,7 +5,7 @@ namespace Generators.Output { public class TestMethodBodyWithEqualityCheck : TestMethodBody { - public TestMethodBodyWithEqualityCheck(CanonicalDataCase canonicalDataCase, CanonicalData canonicalData) : base(canonicalDataCase, canonicalData) + public TestMethodBodyWithEqualityCheck(CanonicalDataCase canonicalDataCase) : base(canonicalDataCase) { AssertTemplateName = ExpectedIsEmptyEnumerable ? "AssertEqual_Empty" : "AssertEqual"; AssertTemplateParameters = new { Data.ExpectedParameter, Data.TestedValue }; diff --git a/generators/Output/TestMethodBodyWithExceptionCheck.cs b/generators/Output/TestMethodBodyWithExceptionCheck.cs index 3d61dafa97..3aa62f5e25 100644 --- a/generators/Output/TestMethodBodyWithExceptionCheck.cs +++ b/generators/Output/TestMethodBodyWithExceptionCheck.cs @@ -4,7 +4,7 @@ namespace Generators.Output { public class TestMethodBodyWithExceptionCheck : TestMethodBody { - public TestMethodBodyWithExceptionCheck(CanonicalDataCase canonicalDataCase, CanonicalData canonicalData) : base(canonicalDataCase, canonicalData) + public TestMethodBodyWithExceptionCheck(CanonicalDataCase canonicalDataCase) : base(canonicalDataCase) { AssertTemplateName = "AssertThrowsException"; AssertTemplateParameters = new { ExceptionType, Data.TestedValue }; diff --git a/generators/Output/TestMethodBodyWithNullCheck.cs b/generators/Output/TestMethodBodyWithNullCheck.cs index 03f716f789..6e5cd7f3f7 100644 --- a/generators/Output/TestMethodBodyWithNullCheck.cs +++ b/generators/Output/TestMethodBodyWithNullCheck.cs @@ -4,7 +4,7 @@ namespace Generators.Output { public class TestMethodBodyWithNullCheck : TestMethodBody { - public TestMethodBodyWithNullCheck(CanonicalDataCase canonicalDataCase, CanonicalData canonicalData) : base(canonicalDataCase, canonicalData) + public TestMethodBodyWithNullCheck(CanonicalDataCase canonicalDataCase) : base(canonicalDataCase) { AssertTemplateName = "AssertNull"; AssertTemplateParameters = new { Data.TestedValue }; From 096dcabb5278e72b162c81dd142e1253bb5b147f Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 19 Jun 2018 22:10:40 +0200 Subject: [PATCH 15/97] generators: Move variables data to TestMethodData --- exercises/isbn-verifier/IsbnVerifierTest.cs | 8 +++- generators/Exercises/Allergies.cs | 4 +- generators/Exercises/BinarySearchTree.cs | 2 +- generators/Exercises/Bowling.cs | 18 ++++----- generators/Exercises/CircularBuffer.cs | 4 +- generators/Exercises/Clock.cs | 8 ++-- generators/Exercises/ComplexNumbers.cs | 2 +- generators/Exercises/GoCounting.cs | 4 +- generators/Exercises/NucleotideCount.cs | 6 +-- generators/Exercises/PalindromeProducts.cs | 2 +- generators/Exercises/QueenAttack.cs | 10 ++--- generators/Exercises/RationalNumbers.cs | 6 +-- generators/Exercises/React.cs | 4 +- generators/Exercises/RobotSimulator.cs | 8 ++-- generators/Exercises/RunLengthEncoding.cs | 6 +-- generators/Exercises/SimpleCipher.cs | 6 +-- generators/Exercises/TwoBucket.cs | 6 +-- generators/Exercises/WordSearch.cs | 2 +- generators/Exercises/Zipper.cs | 6 +-- generators/GeneratorExercise.cs | 20 ++++++---- generators/Output/TestMethodBody.cs | 20 +++------- generators/Output/TestMethodBodyData.cs | 37 ++++++++++++------- .../Output/TestMethodBodyWithBooleanCheck.cs | 4 +- .../Output/TestMethodBodyWithEqualityCheck.cs | 11 +++--- .../TestMethodBodyWithExceptionCheck.cs | 15 ++++---- .../Output/TestMethodBodyWithNullCheck.cs | 6 +-- 26 files changed, 118 insertions(+), 107 deletions(-) diff --git a/exercises/isbn-verifier/IsbnVerifierTest.cs b/exercises/isbn-verifier/IsbnVerifierTest.cs index 39c112fc46..b21c789098 100644 --- a/exercises/isbn-verifier/IsbnVerifierTest.cs +++ b/exercises/isbn-verifier/IsbnVerifierTest.cs @@ -1,4 +1,4 @@ -// This file was auto-generated based on version 2.5.0 of the canonical data. +// This file was auto-generated based on version 2.6.0 of the canonical data. using Xunit; @@ -64,6 +64,12 @@ public void Too_long_isbn_and_no_dashes() Assert.False(IsbnVerifier.IsValid("3598215078X")); } + [Fact(Skip = "Remove to run test")] + public void Too_short_isbn() + { + Assert.False(IsbnVerifier.IsValid("00")); + } + [Fact(Skip = "Remove to run test")] public void Isbn_without_check_digit() { diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Allergies.cs index 176f96f203..2d312608d3 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Allergies.cs @@ -18,7 +18,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - return testMethodBody.CanonicalDataCase.Property == "IsAllergicTo" + return testMethodBody.Data.CanonicalDataCase.Property == "IsAllergicTo" ? RenderIsAllergicToAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } @@ -30,7 +30,7 @@ private static IEnumerable RenderIsAllergicToAssert(TestMethodBody testM Assert.{% if allergy.result %}True{% else %}False{% endif %}(sut.IsAllergicTo(""{{ allergy.substance }}"")); {%- endfor -%}"; - var templateParameters = new { Allergies = testMethodBody.CanonicalDataCase.Expected }; + var templateParameters = new { Allergies = testMethodBody.Data.CanonicalDataCase.Expected }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } } diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index ffe9b6b410..c8a4f0d9f0 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -36,7 +36,7 @@ public class BinarySearchTree : GeneratorExercise protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { _testFactCodeLines = new StringBuilder(); - var canonicalDataCase = testMethodBody.CanonicalDataCase; + var canonicalDataCase = testMethodBody.Data.CanonicalDataCase; var input = canonicalDataCase.Properties["input"] as Dictionary; var constructorData = input["treeData"] as string[]; diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index fc1d4e7eaa..c6c5d00bfa 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -29,10 +29,10 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod var builder = new StringBuilder(); builder.AppendLine("var sut = new BowlingGame();"); - if (!testMethodBody.CanonicalDataCase.Input.ContainsKey(PreviousRolls)) + if (!testMethodBody.Data.CanonicalDataCase.Input.ContainsKey(PreviousRolls)) return new[] { builder.ToString() }; - if (testMethodBody.CanonicalDataCase.Input[PreviousRolls] is int[] array) + if (testMethodBody.Data.CanonicalDataCase.Input[PreviousRolls] is int[] array) { builder.Append("var previousRolls = new [] { "); builder.AppendJoin(", ", array); @@ -48,18 +48,18 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.CanonicalDataCase.ExceptionThrown != null && testMethodBody.CanonicalDataCase.Input.ContainsKey("roll")) + if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown != null && testMethodBody.Data.CanonicalDataCase.Input.ContainsKey("roll")) { const string template = "Assert.Throws(() => sut.Roll({{RollVal}}));"; var templateParams = new { - RollVal = testMethodBody.CanonicalDataCase.Input["roll"] + RollVal = testMethodBody.Data.CanonicalDataCase.Input["roll"] }; return new[] { TemplateRenderer.RenderInline(template, templateParams) }; } - if (testMethodBody.CanonicalDataCase.ExceptionThrown == null || - testMethodBody.CanonicalDataCase.Property != "score") + if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown == null || + testMethodBody.Data.CanonicalDataCase.Property != "score") return base.RenderTestMethodBodyAssert(testMethodBody); const string throwTemplate = "Assert.Throws(() => sut.Score());"; @@ -73,12 +73,12 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te @"DoRoll(previousRolls, sut); "; - if (testMethodBody.CanonicalDataCase.ExceptionThrown != null) + if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown != null) { return new[] { template }; } - if (testMethodBody.CanonicalDataCase.Input.ContainsKey("roll")) + if (testMethodBody.Data.CanonicalDataCase.Input.ContainsKey("roll")) { template += @"sut.Roll({{RolVal}}); @@ -86,7 +86,7 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te "; var templateParameters = new { - RolVal = testMethodBody.CanonicalDataCase.Input["roll"] + RolVal = testMethodBody.Data.CanonicalDataCase.Input["roll"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/CircularBuffer.cs index 4fea8cff67..f8f7d1b670 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/CircularBuffer.cs @@ -9,9 +9,9 @@ public class CircularBuffer : GeneratorExercise { protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - yield return RenderSut(testMethodBody.CanonicalDataCase); + yield return RenderSut(testMethodBody.Data.CanonicalDataCase); - foreach (var operation in testMethodBody.CanonicalDataCase.Input["operations"]) + foreach (var operation in testMethodBody.Data.CanonicalDataCase.Input["operations"]) yield return RenderOperation(operation); } diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Clock.cs index 90d6a4ec05..6ca83f8953 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Clock.cs @@ -42,12 +42,12 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.CanonicalDataCase.Property == PropertyEquals) + if (testMethodBody.Data.CanonicalDataCase.Property == PropertyEquals) { return RenderEqualToAssert(testMethodBody); } - return testMethodBody.CanonicalDataCase.Property != PropertyToString + return testMethodBody.Data.CanonicalDataCase.Property != PropertyToString ? RenderConsistencyToAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } @@ -60,9 +60,9 @@ private static IEnumerable RenderConsistencyToAssert(TestMethodBody test private static IEnumerable RenderEqualToAssert(TestMethodBody testMethodBody) { - var expectedParameter = testMethodBody.CanonicalDataCase.Input[ParamClock1]; + var expectedParameter = testMethodBody.Data.CanonicalDataCase.Input[ParamClock1]; const string testedValue = "sut"; - var expectedEqual = testMethodBody.CanonicalDataCase.Expected; + var expectedEqual = testMethodBody.Data.CanonicalDataCase.Expected; testMethodBody.AssertTemplateParameters = new { expectedParameter, testedValue }; diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index f9fe6c03ee..695c880787 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -33,7 +33,7 @@ private static string[] GetInputParameters(CanonicalDataCase canonicalDataCase, protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - return testMethodBody.UseVariableForExpected + return testMethodBody.Data.UseVariableForExpected ? RenderComplexNumberAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index d46f369e7e..fe0a0f113b 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -54,12 +54,12 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.CanonicalDataCase.ExceptionThrown != null) + if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown != null) { return base.RenderTestMethodBodyAssert(testMethodBody); } - if (testMethodBody.CanonicalDataCase.Property == "territories") + if (testMethodBody.Data.CanonicalDataCase.Property == "territories") { return new[] { diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index aec336717a..ea9a3dd1a3 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -24,7 +24,7 @@ private static dynamic ConvertExpected(dynamic expected) protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - return testMethodBody.UseVariableForExpected + return testMethodBody.Data.UseVariableForExpected ? RenderEqualBodyAssert(testMethodBody) : RenderThrowsBodyAssert(testMethodBody); } @@ -35,7 +35,7 @@ private static IEnumerable RenderEqualBodyAssert(TestMethodBody testMeth var templateParameters = new { - TestedMethodName = testMethodBody.CanonicalDataCase.Property.ToTestedMethodName() + TestedMethodName = testMethodBody.Data.CanonicalDataCase.Property.ToTestedMethodName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; @@ -47,7 +47,7 @@ private static IEnumerable RenderThrowsBodyAssert(TestMethodBody testMet var templateParameters = new { - Input = testMethodBody.CanonicalDataCase.Input["strand"] + Input = testMethodBody.Data.CanonicalDataCase.Input["strand"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/PalindromeProducts.cs index 64c3b53eb8..9fc159edd1 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/PalindromeProducts.cs @@ -25,7 +25,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.CanonicalDataCase.ExceptionThrown != null) + if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown != null) { return base.RenderTestMethodBodyAssert(testMethodBody); } diff --git a/generators/Exercises/QueenAttack.cs b/generators/Exercises/QueenAttack.cs index edd19e4281..642e036f5a 100644 --- a/generators/Exercises/QueenAttack.cs +++ b/generators/Exercises/QueenAttack.cs @@ -15,10 +15,10 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.CanonicalDataCase.Property == "canAttack") + if (testMethodBody.Data.CanonicalDataCase.Property == "canAttack") return new[] { RenderCanAttackAssert(testMethodBody) }; - return testMethodBody.UseVariableForTested + return testMethodBody.Data.UseVariableForTested ? Array.Empty() : base.RenderTestMethodBodyAssert(testMethodBody); } @@ -30,8 +30,8 @@ private static string RenderCanAttackAssert(TestMethodBody testMethodBody) var blackQueen = QueenAttack.Create({{blackQueenX}},{{blackQueenY}}); Assert.{% if Expected %}True{% else %}False{% endif %}(QueenAttack.CanAttack(whiteQueen, blackQueen));"; - var whiteQueenPositions = GetCoordinatesFromPosition(testMethodBody.CanonicalDataCase.Input["white_queen"]); - var blackQueenPositions = GetCoordinatesFromPosition(testMethodBody.CanonicalDataCase.Input["black_queen"]); + var whiteQueenPositions = GetCoordinatesFromPosition(testMethodBody.Data.CanonicalDataCase.Input["white_queen"]); + var blackQueenPositions = GetCoordinatesFromPosition(testMethodBody.Data.CanonicalDataCase.Input["black_queen"]); var templateParameters = new { @@ -39,7 +39,7 @@ private static string RenderCanAttackAssert(TestMethodBody testMethodBody) whiteQueenY = whiteQueenPositions.Item2, blackQueenX = blackQueenPositions.Item1, blackQueenY = blackQueenPositions.Item2, - testMethodBody.CanonicalDataCase.Expected + testMethodBody.Data.CanonicalDataCase.Expected }; return TemplateRenderer.RenderInline(template, templateParameters); diff --git a/generators/Exercises/RationalNumbers.cs b/generators/Exercises/RationalNumbers.cs index e83816cefd..e321b0ad50 100644 --- a/generators/Exercises/RationalNumbers.cs +++ b/generators/Exercises/RationalNumbers.cs @@ -19,9 +19,9 @@ public class RationalNumbers : GeneratorExercise { protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var input = testMethodBody.CanonicalDataCase.Properties["input"] as Dictionary; - var operation = testMethodBody.CanonicalDataCase.Properties["property"].ToString(); - var expected = testMethodBody.CanonicalDataCase.Properties["expected"]; + var input = testMethodBody.Data.CanonicalDataCase.Properties["input"] as Dictionary; + var operation = testMethodBody.Data.CanonicalDataCase.Properties["property"].ToString(); + var expected = testMethodBody.Data.CanonicalDataCase.Properties["expected"]; var operationName = char.ToUpper(operation[0]) + operation.Substring(1); var assertCodeLine = ""; const string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index 29671a217e..50609dffbb 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -15,10 +15,10 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod var arrange = new StringBuilder(); arrange.AppendLine("var sut = new Reactor();"); - var cells = RenderCells(testMethodBody.CanonicalDataCase.Input["cells"]); + var cells = RenderCells(testMethodBody.Data.CanonicalDataCase.Input["cells"]); arrange.AppendLine(cells); - var operations = RenderOperations(testMethodBody.CanonicalDataCase.Input["operations"]); + var operations = RenderOperations(testMethodBody.Data.CanonicalDataCase.Input["operations"]); arrange.AppendLine(operations); return new[] { arrange.ToString() }; diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index 3190aef77d..2114cfb8da 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -27,7 +27,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) { - switch (testMethodBody.CanonicalDataCase.Property) + switch (testMethodBody.Data.CanonicalDataCase.Property) { case "create": return Array.Empty(); case "instructions": return RenderInstructionsMethodBodyAct(testMethodBody); @@ -41,7 +41,7 @@ private static IEnumerable RenderDefaultMethodBodyAct(TestMethodBody tes var templateParameters = new { - MethodInvocation = testMethodBody.CanonicalDataCase.Property.ToTestedMethodName() + MethodInvocation = testMethodBody.Data.CanonicalDataCase.Property.ToTestedMethodName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; @@ -54,7 +54,7 @@ private static IEnumerable RenderInstructionsMethodBodyAct(TestMethodBod var templateParameters = new { MethodInvocation = "Simulate", - Instructions = testMethodBody.CanonicalDataCase.Input["instructions"] + Instructions = testMethodBody.Data.CanonicalDataCase.Input["instructions"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; @@ -62,7 +62,7 @@ private static IEnumerable RenderInstructionsMethodBodyAct(TestMethodBod protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var expected = testMethodBody.CanonicalDataCase.Expected as Dictionary; + var expected = testMethodBody.Data.CanonicalDataCase.Expected as Dictionary; expected.TryGetValue("position", out var position); expected.TryGetValue("direction", out var direction); diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index 731873c6f4..446adcae6d 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -13,7 +13,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - return testMethodBody.CanonicalDataCase.Property == "consistency" + return testMethodBody.Data.CanonicalDataCase.Property == "consistency" ? RenderConsistencyToAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } @@ -24,8 +24,8 @@ private static IEnumerable RenderConsistencyToAssert(TestMethodBody test var templateParameters = new { - ExpectedOutput = testMethodBody.CanonicalDataCase.Expected, - ExerciseName = testMethodBody.CanonicalDataCase.Exercise.ToTestedClassName() + ExpectedOutput = testMethodBody.Data.CanonicalDataCase.Expected, + ExerciseName = testMethodBody.Data.CanonicalDataCase.Exercise.ToTestedClassName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index 6d34b19e52..430db51cb2 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -46,13 +46,13 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - switch (testMethodBody.CanonicalDataCase.Property) + switch (testMethodBody.Data.CanonicalDataCase.Property) { case "new": - var key = ValueFormatter.Format(testMethodBody.CanonicalDataCase.Input["key"]); + var key = ValueFormatter.Format(testMethodBody.Data.CanonicalDataCase.Input["key"]); return new[] { $"Assert.Throws(() => new SimpleCipher({key}));" }; case "key": - var pattern = ValueFormatter.Format(testMethodBody.CanonicalDataCase.Expected["match"]); + var pattern = ValueFormatter.Format(testMethodBody.Data.CanonicalDataCase.Expected["match"]); return new[] { $"Assert.Matches({pattern}, sut.Key);" }; default: return base.RenderTestMethodBodyAssert(testMethodBody); diff --git a/generators/Exercises/TwoBucket.cs b/generators/Exercises/TwoBucket.cs index 9afced3f1f..aafc0361b2 100644 --- a/generators/Exercises/TwoBucket.cs +++ b/generators/Exercises/TwoBucket.cs @@ -36,9 +36,9 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody var templateParameters = new { - MovesExpected = testMethodBody.CanonicalDataCase.Expected["moves"], - OtherBucketExpected = testMethodBody.CanonicalDataCase.Expected["otherBucket"], - GoalBucketExpected = testMethodBody.CanonicalDataCase.Expected["goalBucket"] + MovesExpected = testMethodBody.Data.CanonicalDataCase.Expected["moves"], + OtherBucketExpected = testMethodBody.Data.CanonicalDataCase.Expected["otherBucket"], + GoalBucketExpected = testMethodBody.Data.CanonicalDataCase.Expected["goalBucket"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index a0ca603c9e..1b6246d758 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -35,7 +35,7 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var expectedDictionary = testMethodBody.CanonicalDataCase.Properties["expected"] as IDictionary; + var expectedDictionary = testMethodBody.Data.CanonicalDataCase.Properties["expected"] as IDictionary; foreach (var kv in expectedDictionary) yield return RenderTestMethodBodyAssertForSearchWord(kv.Key, kv.Value); diff --git a/generators/Exercises/Zipper.cs b/generators/Exercises/Zipper.cs index 1793010143..68b9766fd4 100644 --- a/generators/Exercises/Zipper.cs +++ b/generators/Exercises/Zipper.cs @@ -10,17 +10,17 @@ public class Zipper : GeneratorExercise { protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) { - var tree = RenderTree(testMethodBody.CanonicalDataCase.Input["initialTree"]); + var tree = RenderTree(testMethodBody.Data.CanonicalDataCase.Input["initialTree"]); yield return $"var tree = {tree};"; yield return "var sut = Zipper.FromTree(tree);"; - var operations = RenderOperations(testMethodBody.CanonicalDataCase.Input["operations"]); + var operations = RenderOperations(testMethodBody.Data.CanonicalDataCase.Input["operations"]); yield return $"var actual = sut{operations};"; } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var expected = RenderExpected(testMethodBody.CanonicalDataCase.Expected); + var expected = RenderExpected(testMethodBody.Data.CanonicalDataCase.Expected); if (expected == null) { yield return "Assert.Null(actual);"; diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index 9887b7c9dc..19f3ac54ac 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -80,29 +80,33 @@ private static string ToTestMethodName(CanonicalDataCase canonicalDataCase) private string RenderTestMethodBody(CanonicalDataCase canonicalDataCase) { - var testMethodBody = CreateTestMethodBody(canonicalDataCase); + var testMethodBodyData = CreateTestMethodBodyData(canonicalDataCase); + var testMethodBody = CreateTestMethodBody(testMethodBodyData); testMethodBody.Arrange = RenderTestMethodBodyArrange(testMethodBody); testMethodBody.Act = RenderTestMethodBodyAct(testMethodBody); testMethodBody.Assert = RenderTestMethodBodyAssert(testMethodBody); return testMethodBody.Render(); } + + protected virtual TestMethodBodyData CreateTestMethodBodyData(CanonicalDataCase canonicalDataCase) + => new TestMethodBodyData(canonicalDataCase); - protected virtual TestMethodBody CreateTestMethodBody(CanonicalDataCase canonicalDataCase) + protected virtual TestMethodBody CreateTestMethodBody(TestMethodBodyData data) { - if (canonicalDataCase.ExceptionThrown != null) + if (data.CanonicalDataCase.ExceptionThrown != null) { - return new TestMethodBodyWithExceptionCheck(canonicalDataCase); + return new TestMethodBodyWithExceptionCheck(data); } - switch (canonicalDataCase.Expected) + switch (data.CanonicalDataCase.Expected) { case bool _: - return new TestMethodBodyWithBooleanCheck(canonicalDataCase); + return new TestMethodBodyWithBooleanCheck(data); case null: - return new TestMethodBodyWithNullCheck(canonicalDataCase); + return new TestMethodBodyWithNullCheck(data); default: - return new TestMethodBodyWithEqualityCheck(canonicalDataCase); + return new TestMethodBodyWithEqualityCheck(data); } } } diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index b2f6a3c16b..6103e6404d 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -5,40 +5,32 @@ namespace Generators.Output { public abstract class TestMethodBody { - protected TestMethodBody(CanonicalDataCase canonicalDataCase) + protected TestMethodBody(TestMethodBodyData data) { - CanonicalDataCase = canonicalDataCase; - - Data = new TestMethodBodyData(this); + Data = data; InitializeTemplateParameters(); } public string TemplateName { get; set; } = "TestMethodBody"; - public CanonicalDataCase CanonicalDataCase { get; } public TestMethodBodyData Data { get; } - public virtual bool UseVariablesForInput => CanonicalDataCase.UseVariablesForInput; - public virtual bool UseVariablesForConstructorParameters => CanonicalDataCase.UseVariablesForConstructorParameters; - public virtual bool UseVariableForExpected => CanonicalDataCase.UseVariableForExpected; - public virtual bool UseVariableForTested => CanonicalDataCase.UseVariableForTested; - public string ArrangeTemplateName { get; set; } = "Arrange"; public object ArrangeTemplateParameters { get; set; } - + public string ActTemplateName { get; set; } = "Act"; public object ActTemplateParameters { get; set; } - + public string AssertTemplateName { get; set; } = "AssertEqual"; public object AssertTemplateParameters { get; set; } public IEnumerable Act { get; set; } public IEnumerable Arrange { get; set; } public IEnumerable Assert { get; set; } - + public virtual string Render() => TemplateRenderer.RenderPartial(TemplateName, new { Arrange, Act, Assert }); - private void InitializeTemplateParameters() + protected void InitializeTemplateParameters() { ArrangeTemplateParameters = new { Data.Variables }; ActTemplateParameters = new { }; diff --git a/generators/Output/TestMethodBodyData.cs b/generators/Output/TestMethodBodyData.cs index 8527935d27..c20d310bed 100644 --- a/generators/Output/TestMethodBodyData.cs +++ b/generators/Output/TestMethodBodyData.cs @@ -5,27 +5,38 @@ namespace Generators.Output { - public class TestMethodBodyData + public sealed class TestMethodBodyData { private const string SutVariableName = "sut"; private const string TestedVariableName = "actual"; private const string ExpectedVariableName = "expected"; - private readonly TestMethodBody _testMethodBody; + public CanonicalDataCase CanonicalDataCase { get; } - public TestMethodBodyData(TestMethodBody testMethodBody) => _testMethodBody = testMethodBody; + public TestMethodBodyData(CanonicalDataCase canonicalDataCase) + { + CanonicalDataCase = canonicalDataCase; + + UseVariablesForInput = CanonicalDataCase.UseVariablesForInput; + UseVariablesForConstructorParameters = CanonicalDataCase.UseVariablesForConstructorParameters; + UseVariableForExpected = CanonicalDataCase.UseVariableForExpected; + UseVariableForTested = CanonicalDataCase.UseVariableForTested; + } - public string TestedValue => _testMethodBody.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; - public string InputParameters => _testMethodBody.UseVariablesForInput ? string.Join(", ", CanonicalDataCase.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); - public string ExpectedParameter => _testMethodBody.UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(CanonicalDataCase.Expected); - public string ConstructorParameters => _testMethodBody.UseVariablesForConstructorParameters ? string.Join(", ", CanonicalDataCase.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); + public bool UseVariablesForInput { get; set; } + public bool UseVariablesForConstructorParameters { get; set; } + public bool UseVariableForExpected { get; set; } + public bool UseVariableForTested { get; set; } - private CanonicalDataCase CanonicalDataCase => _testMethodBody.CanonicalDataCase; + public string TestedValue => UseVariableForTested ? TestedVariableName : TestedMethodInvocation; + public string InputParameters => UseVariablesForInput ? string.Join(", ", CanonicalDataCase.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); + public string ExpectedParameter => UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(CanonicalDataCase.Expected); + public string ConstructorParameters => UseVariablesForConstructorParameters ? string.Join(", ", CanonicalDataCase.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); private string TestedClassName => CanonicalDataCase.Exercise.ToTestedClassName(); private string TestedMethodName => CanonicalDataCase.Property.ToTestedMethodName(); - private IDictionary Input => CanonicalDataCase.InputParameters.ToDictionary(key => key, key => CanonicalDataCase.Input[key]); + private IDictionary Input => CanonicalDataCase.InputParameters.ToDictionary(key => key, key => CanonicalDataCase.Input[key]); private IDictionary ConstructorInput => CanonicalDataCase.ConstructorInputParameters.ToDictionary(key => key, key => CanonicalDataCase.Input[key]); private object Expected => CanonicalDataCase.Expected; @@ -41,19 +52,19 @@ public IEnumerable Variables { var lines = new List(); - if (_testMethodBody.UseVariablesForInput) + if (UseVariablesForInput) lines.AddRange(InputVariablesDeclaration); - if (_testMethodBody.UseVariablesForConstructorParameters) + if (UseVariablesForConstructorParameters) lines.AddRange(ConstructorVariablesDeclaration); if (CanonicalDataCase.TestedMethodType == TestedMethodType.Instance) lines.AddRange(SutVariableDeclaration); - if (_testMethodBody.UseVariableForTested) + if (UseVariableForTested) lines.AddRange(ActualVariableDeclaration); - if (_testMethodBody.UseVariableForExpected) + if (UseVariableForExpected) lines.AddRange(ExpectedVariableDeclaration); return lines; diff --git a/generators/Output/TestMethodBodyWithBooleanCheck.cs b/generators/Output/TestMethodBodyWithBooleanCheck.cs index a72bf8444d..334163bcfa 100644 --- a/generators/Output/TestMethodBodyWithBooleanCheck.cs +++ b/generators/Output/TestMethodBodyWithBooleanCheck.cs @@ -5,12 +5,12 @@ namespace Generators.Output { public class TestMethodBodyWithBooleanCheck : TestMethodBody { - public TestMethodBodyWithBooleanCheck(CanonicalDataCase canonicalDataCase) : base(canonicalDataCase) + public TestMethodBodyWithBooleanCheck(TestMethodBodyData data) : base(data) { AssertTemplateName = "AssertBoolean"; AssertTemplateParameters = new { BooleanAssertMethod, Data.TestedValue }; } - private string BooleanAssertMethod => Convert.ToBoolean(CanonicalDataCase.Expected).ToString(); + private string BooleanAssertMethod => Convert.ToBoolean(Data.CanonicalDataCase.Expected).ToString(); } } \ No newline at end of file diff --git a/generators/Output/TestMethodBodyWithEqualityCheck.cs b/generators/Output/TestMethodBodyWithEqualityCheck.cs index 295513f40b..b06e44996b 100644 --- a/generators/Output/TestMethodBodyWithEqualityCheck.cs +++ b/generators/Output/TestMethodBodyWithEqualityCheck.cs @@ -5,17 +5,18 @@ namespace Generators.Output { public class TestMethodBodyWithEqualityCheck : TestMethodBody { - public TestMethodBodyWithEqualityCheck(CanonicalDataCase canonicalDataCase) : base(canonicalDataCase) + public TestMethodBodyWithEqualityCheck(TestMethodBodyData data) : base(data) { + Data.UseVariableForExpected = Data.UseVariableForExpected && !ExpectedIsEmptyEnumerable; + InitializeTemplateParameters(); + AssertTemplateName = ExpectedIsEmptyEnumerable ? "AssertEqual_Empty" : "AssertEqual"; AssertTemplateParameters = new { Data.ExpectedParameter, Data.TestedValue }; } - public override bool UseVariableForExpected => base.UseVariableForExpected && !ExpectedIsEmptyEnumerable; - private bool ExpectedIsEmptyEnumerable => - !(CanonicalDataCase.Expected is string) && - CanonicalDataCase.Expected is IEnumerable enumerable + !(Data.CanonicalDataCase.Expected is string) && + Data.CanonicalDataCase.Expected is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; } } \ No newline at end of file diff --git a/generators/Output/TestMethodBodyWithExceptionCheck.cs b/generators/Output/TestMethodBodyWithExceptionCheck.cs index 3aa62f5e25..53e7c95746 100644 --- a/generators/Output/TestMethodBodyWithExceptionCheck.cs +++ b/generators/Output/TestMethodBodyWithExceptionCheck.cs @@ -1,18 +1,17 @@ -using Generators.Input; - -namespace Generators.Output +namespace Generators.Output { public class TestMethodBodyWithExceptionCheck : TestMethodBody { - public TestMethodBodyWithExceptionCheck(CanonicalDataCase canonicalDataCase) : base(canonicalDataCase) + public TestMethodBodyWithExceptionCheck(TestMethodBodyData data) : base(data) { + Data.UseVariableForExpected = false; + Data.UseVariableForTested = false; + InitializeTemplateParameters(); + AssertTemplateName = "AssertThrowsException"; AssertTemplateParameters = new { ExceptionType, Data.TestedValue }; } - public override bool UseVariableForExpected => false; - public override bool UseVariableForTested => false; - - private string ExceptionType => CanonicalDataCase.ExceptionThrown.Name; + private string ExceptionType => Data.CanonicalDataCase.ExceptionThrown.Name; } } \ No newline at end of file diff --git a/generators/Output/TestMethodBodyWithNullCheck.cs b/generators/Output/TestMethodBodyWithNullCheck.cs index 6e5cd7f3f7..1cc1a2cc95 100644 --- a/generators/Output/TestMethodBodyWithNullCheck.cs +++ b/generators/Output/TestMethodBodyWithNullCheck.cs @@ -1,10 +1,8 @@ -using Generators.Input; - -namespace Generators.Output +namespace Generators.Output { public class TestMethodBodyWithNullCheck : TestMethodBody { - public TestMethodBodyWithNullCheck(CanonicalDataCase canonicalDataCase) : base(canonicalDataCase) + public TestMethodBodyWithNullCheck(TestMethodBodyData data) : base(data) { AssertTemplateName = "AssertNull"; AssertTemplateParameters = new { Data.TestedValue }; From 67fefe6fc1a13b0ae953252e484478a136740cd3 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Wed, 20 Jun 2018 18:26:37 +0200 Subject: [PATCH 16/97] generators: Make canonical data class immutable --- generators/ExerciseCollection.cs | 2 +- generators/Exercises/AllYourBase.cs | 11 +-- generators/Exercises/Allergies.cs | 19 ++-- generators/Exercises/Alphametics.cs | 16 ++-- generators/Exercises/Anagram.cs | 10 +-- generators/Exercises/BeerSong.cs | 7 +- generators/Exercises/BinarySearch.cs | 9 +- generators/Exercises/BinarySearchTree.cs | 2 +- generators/Exercises/BookStore.cs | 11 +-- generators/Exercises/Bowling.cs | 29 +++--- generators/Exercises/BracketPush.cs | 8 +- generators/Exercises/Change.cs | 12 +-- generators/Exercises/CircularBuffer.cs | 11 ++- generators/Exercises/Clock.cs | 31 ++++--- generators/Exercises/CollatzConjecture.cs | 6 +- generators/Exercises/ComplexNumbers.cs | 25 +++--- generators/Exercises/Connect.cs | 19 ++-- generators/Exercises/CryptoSquare.cs | 8 +- generators/Exercises/CustomSet.cs | 29 +++--- generators/Exercises/DifferenceOfSquares.cs | 12 +-- generators/Exercises/Dominoes.cs | 7 +- generators/Exercises/Etl.cs | 14 +-- generators/Exercises/FlattenArray.cs | 11 ++- generators/Exercises/FoodChain.cs | 11 +-- generators/Exercises/Forth.cs | 12 +-- generators/Exercises/Gigasecond.cs | 9 +- generators/Exercises/GoCounting.cs | 42 ++++----- generators/Exercises/Grains.cs | 10 +-- generators/Exercises/Grep.cs | 17 ++-- generators/Exercises/Hamming.cs | 6 +- generators/Exercises/House.cs | 11 +-- generators/Exercises/KindergartenGarden.cs | 17 ++-- generators/Exercises/LargestSeriesProduct.cs | 12 +-- generators/Exercises/Leap.cs | 6 +- generators/Exercises/ListOps.cs | 37 ++++---- generators/Exercises/Luhn.cs | 6 +- generators/Exercises/Markdown.cs | 11 ++- generators/Exercises/Matrix.cs | 12 +-- generators/Exercises/Meetup.cs | 23 +++-- generators/Exercises/Minesweeper.cs | 11 ++- generators/Exercises/NthPrime.cs | 6 +- generators/Exercises/NucleotideCount.cs | 19 ++-- generators/Exercises/OcrNumbers.cs | 15 ++-- generators/Exercises/PalindromeProducts.cs | 15 ++-- generators/Exercises/PascalsTriangle.cs | 14 +-- generators/Exercises/PerfectNumbers.cs | 9 +- generators/Exercises/PhoneNumber.cs | 8 +- generators/Exercises/Poker.cs | 10 +-- generators/Exercises/Pov.cs | 15 ++-- generators/Exercises/Proverb.cs | 9 +- generators/Exercises/QueenAttack.cs | 21 +++-- generators/Exercises/RailFenceCipher.cs | 10 +-- generators/Exercises/RationalNumbers.cs | 12 +-- generators/Exercises/React.cs | 10 +-- generators/Exercises/Rectangles.cs | 12 +-- generators/Exercises/RnaTranscription.cs | 6 +- generators/Exercises/RobotSimulator.cs | 23 +++-- generators/Exercises/RomanNumerals.cs | 8 +- generators/Exercises/RunLengthEncoding.cs | 13 ++- generators/Exercises/SaddlePoints.cs | 24 ++--- generators/Exercises/Say.cs | 8 +- generators/Exercises/ScaleGenerator.cs | 6 +- generators/Exercises/Sieve.cs | 8 +- generators/Exercises/SimpleCipher.cs | 33 ++++--- generators/Exercises/SpaceAge.cs | 10 +-- generators/Exercises/SpiralMatrix.cs | 10 +-- generators/Exercises/Sublist.cs | 11 ++- generators/Exercises/SumOfMultiples.cs | 5 +- generators/Exercises/Tournament.cs | 14 +-- generators/Exercises/Transpose.cs | 13 +-- generators/Exercises/Triangle.cs | 28 +++--- generators/Exercises/TwelveDays.cs | 11 +-- generators/Exercises/TwoBucket.cs | 17 ++-- generators/Exercises/TwoFer.cs | 8 +- .../Exercises/VariableLengthQuantity.cs | 15 ++-- generators/Exercises/WordCount.cs | 10 +-- generators/Exercises/WordSearch.cs | 28 +++--- generators/Exercises/Wordy.cs | 6 +- generators/Exercises/Yacht.cs | 11 ++- generators/Exercises/ZebraPuzzle.cs | 11 ++- generators/Exercises/Zipper.cs | 6 +- generators/GeneratorExercise.cs | 77 +++++++++------- generators/Input/CanonicalData.cs | 8 +- generators/Input/CanonicalDataCase.cs | 53 +++-------- generators/Input/CanonicalDataCaseParser.cs | 27 +++--- generators/Input/CanonicalDataParser.cs | 15 ++-- generators/Input/ConvertHelper.cs | 1 - .../{ConfigFile.cs => TrackConfigFile.cs} | 2 +- generators/Output/TestMethodBody.cs | 3 +- generators/Output/TestMethodBodyData.cs | 89 +++++++++++++------ .../Output/TestMethodBodyWithBooleanCheck.cs | 5 +- .../Output/TestMethodBodyWithEqualityCheck.cs | 7 +- .../TestMethodBodyWithExceptionCheck.cs | 2 +- 93 files changed, 683 insertions(+), 696 deletions(-) rename generators/Input/{ConfigFile.cs => TrackConfigFile.cs} (95%) diff --git a/generators/ExerciseCollection.cs b/generators/ExerciseCollection.cs index f464a67a9a..bdad8640f5 100644 --- a/generators/ExerciseCollection.cs +++ b/generators/ExerciseCollection.cs @@ -29,7 +29,7 @@ public ExerciseCollection(CanonicalDataFile canonicalDataFile) private IEnumerable GetExercises() { - foreach (var exercise in ConfigFile.GetExercises()) + foreach (var exercise in TrackConfigFile.GetExercises()) { var exerciseName = exercise.Name; if (exercise.Deprecated) diff --git a/generators/Exercises/AllYourBase.cs b/generators/Exercises/AllYourBase.cs index 85dbb70c9e..793275c666 100644 --- a/generators/Exercises/AllYourBase.cs +++ b/generators/Exercises/AllYourBase.cs @@ -1,17 +1,18 @@ using System; using System.Collections.Generic; using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class AllYourBase : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Input["digits"] = ConvertHelper.ToArray(canonicalDataCase.Input["digits"]); - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is Dictionary ? typeof(ArgumentException) : null; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + data.Input["digits"] = ConvertHelper.ToArray(data.Input["digits"]); + data.ExceptionThrown = data.Expected is Dictionary ? typeof(ArgumentException) : null; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Allergies.cs index 2d312608d3..7b202ede6a 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Allergies.cs @@ -1,25 +1,24 @@ using System.Collections.Generic; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class Allergies : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - if (canonicalDataCase.Property == "allergicTo") - canonicalDataCase.Property = "IsAllergicTo"; - else if (canonicalDataCase.Property == "list") - canonicalDataCase.UseVariableForExpected = true; + if (data.Property == "allergicTo") + data.Property = "IsAllergicTo"; + else if (data.Property == "list") + data.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters("score"); + data.SetConstructorInputParameters("score"); } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - return testMethodBody.Data.CanonicalDataCase.Property == "IsAllergicTo" - ? RenderIsAllergicToAssert(testMethodBody) + return testMethodBody.Data.Property == "IsAllergicTo" + ? RenderIsAllergicToAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } @@ -30,7 +29,7 @@ private static IEnumerable RenderIsAllergicToAssert(TestMethodBody testM Assert.{% if allergy.result %}True{% else %}False{% endif %}(sut.IsAllergicTo(""{{ allergy.substance }}"")); {%- endfor -%}"; - var templateParameters = new { Allergies = testMethodBody.Data.CanonicalDataCase.Expected }; + var templateParameters = new { Allergies = testMethodBody.Data.Expected }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } } diff --git a/generators/Exercises/Alphametics.cs b/generators/Exercises/Alphametics.cs index d3a413ba67..e4a7985803 100644 --- a/generators/Exercises/Alphametics.cs +++ b/generators/Exercises/Alphametics.cs @@ -1,24 +1,24 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Alphametics : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariableForTested = true; + data.UseVariableForExpected = true; + data.UseVariableForTested = true; - if (canonicalDataCase.Expected == null) - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); + if (data.Expected == null) + data.ExceptionThrown = typeof(ArgumentException); else - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase); + data.Expected = ConvertExpected(data); } - private static dynamic ConvertExpected(CanonicalDataCase canonicalDataCase) + private static dynamic ConvertExpected(TestMethodBodyData canonicalDataCase) { Dictionary expected = canonicalDataCase.Expected; return expected.ToDictionary(kv => kv.Key[0], kv => int.Parse(kv.Value.ToString())); diff --git a/generators/Exercises/Anagram.cs b/generators/Exercises/Anagram.cs index f60ebc417b..c49f327c92 100644 --- a/generators/Exercises/Anagram.cs +++ b/generators/Exercises/Anagram.cs @@ -1,14 +1,14 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Anagram : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters("subject"); + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; + data.SetConstructorInputParameters("subject"); } } } \ No newline at end of file diff --git a/generators/Exercises/BeerSong.cs b/generators/Exercises/BeerSong.cs index 7197f0f200..d132dd2ed2 100644 --- a/generators/Exercises/BeerSong.cs +++ b/generators/Exercises/BeerSong.cs @@ -1,13 +1,14 @@ using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class BeerSong : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); + data.UseVariableForExpected = true; + data.Expected = ConvertHelper.ToMultiLineString(data.Expected); } } } \ No newline at end of file diff --git a/generators/Exercises/BinarySearch.cs b/generators/Exercises/BinarySearch.cs index 66ad1a369a..862cb1c462 100644 --- a/generators/Exercises/BinarySearch.cs +++ b/generators/Exercises/BinarySearch.cs @@ -1,16 +1,17 @@ using System; using System.Collections.Generic; using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class BinarySearch : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Input["array"] = ConvertHelper.ToArray(canonicalDataCase.Input["array"]); - canonicalDataCase.UseVariablesForConstructorParameters = true; - canonicalDataCase.SetConstructorInputParameters("array"); + data.Input["array"] = ConvertHelper.ToArray(data.Input["array"]); + data.UseVariablesForConstructorParameters = true; + data.SetConstructorInputParameters("array"); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index c8a4f0d9f0..e91c5a2402 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -36,7 +36,7 @@ public class BinarySearchTree : GeneratorExercise protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { _testFactCodeLines = new StringBuilder(); - var canonicalDataCase = testMethodBody.Data.CanonicalDataCase; + var canonicalDataCase = testMethodBody.Data; var input = canonicalDataCase.Properties["input"] as Dictionary; var constructorData = input["treeData"] as string[]; diff --git a/generators/Exercises/BookStore.cs b/generators/Exercises/BookStore.cs index 4fc2e32148..87d2d50a45 100644 --- a/generators/Exercises/BookStore.cs +++ b/generators/Exercises/BookStore.cs @@ -1,17 +1,18 @@ using System; using System.Collections.Generic; using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class BookStore : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Expected = canonicalDataCase.Expected / 100.0f; - canonicalDataCase.Input["basket"] = ConvertHelper.ToArray(canonicalDataCase.Input["basket"]); - canonicalDataCase.SetInputParameters("basket"); - canonicalDataCase.UseVariablesForInput = true; + data.Expected = data.Expected / 100.0f; + data.Input["basket"] = ConvertHelper.ToArray(data.Input["basket"]); + data.SetInputParameters("basket"); + data.UseVariablesForInput = true; } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index c6c5d00bfa..198f1f945e 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Text; -using Generators.Input; using Generators.Output; namespace Generators.Exercises @@ -10,18 +9,18 @@ public class Bowling : GeneratorExercise { private const string PreviousRolls = "previousRolls"; - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - if (!(canonicalDataCase.Expected is int)) + if (!(data.Expected is int)) { - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); + data.ExceptionThrown = typeof(ArgumentException); } else { - canonicalDataCase.UseVariableForTested = true; + data.UseVariableForTested = true; } - canonicalDataCase.SetInputParameters(); + data.SetInputParameters(); } protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) @@ -29,10 +28,10 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod var builder = new StringBuilder(); builder.AppendLine("var sut = new BowlingGame();"); - if (!testMethodBody.Data.CanonicalDataCase.Input.ContainsKey(PreviousRolls)) + if (!testMethodBody.Data.Input.ContainsKey(PreviousRolls)) return new[] { builder.ToString() }; - if (testMethodBody.Data.CanonicalDataCase.Input[PreviousRolls] is int[] array) + if (testMethodBody.Data.Input[PreviousRolls] is int[] array) { builder.Append("var previousRolls = new [] { "); builder.AppendJoin(", ", array); @@ -48,18 +47,18 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown != null && testMethodBody.Data.CanonicalDataCase.Input.ContainsKey("roll")) + if (testMethodBody.Data.ExceptionThrown != null && testMethodBody.Data.Input.ContainsKey("roll")) { const string template = "Assert.Throws(() => sut.Roll({{RollVal}}));"; var templateParams = new { - RollVal = testMethodBody.Data.CanonicalDataCase.Input["roll"] + RollVal = testMethodBody.Data.Input["roll"] }; return new[] { TemplateRenderer.RenderInline(template, templateParams) }; } - if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown == null || - testMethodBody.Data.CanonicalDataCase.Property != "score") + if (testMethodBody.Data.ExceptionThrown == null || + testMethodBody.Data.Property != "score") return base.RenderTestMethodBodyAssert(testMethodBody); const string throwTemplate = "Assert.Throws(() => sut.Score());"; @@ -73,12 +72,12 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te @"DoRoll(previousRolls, sut); "; - if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown != null) + if (testMethodBody.Data.ExceptionThrown != null) { return new[] { template }; } - if (testMethodBody.Data.CanonicalDataCase.Input.ContainsKey("roll")) + if (testMethodBody.Data.Input.ContainsKey("roll")) { template += @"sut.Roll({{RolVal}}); @@ -86,7 +85,7 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te "; var templateParameters = new { - RolVal = testMethodBody.Data.CanonicalDataCase.Input["roll"] + RolVal = testMethodBody.Data.Input["roll"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } diff --git a/generators/Exercises/BracketPush.cs b/generators/Exercises/BracketPush.cs index 92eae2005b..c8f088d813 100644 --- a/generators/Exercises/BracketPush.cs +++ b/generators/Exercises/BracketPush.cs @@ -1,13 +1,13 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class BracketPush : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Input["value"] = canonicalDataCase.Input["value"].Replace("\\", "\\\\"); - canonicalDataCase.UseVariablesForInput = true; + data.Input["value"] = data.Input["value"].Replace("\\", "\\\\"); + data.UseVariablesForInput = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Change.cs b/generators/Exercises/Change.cs index 59e9b68a69..79aa919a39 100644 --- a/generators/Exercises/Change.cs +++ b/generators/Exercises/Change.cs @@ -1,17 +1,17 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Change : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; - if (canonicalDataCase.Expected is int) - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); + if (data.Expected is int) + data.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/CircularBuffer.cs index f8f7d1b670..379806f54b 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/CircularBuffer.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Generators.Input; using Generators.Output; namespace Generators.Exercises @@ -9,13 +8,13 @@ public class CircularBuffer : GeneratorExercise { protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - yield return RenderSut(testMethodBody.Data.CanonicalDataCase); + yield return RenderSut(testMethodBody.Data); - foreach (var operation in testMethodBody.Data.CanonicalDataCase.Input["operations"]) + foreach (var operation in testMethodBody.Data.Input["operations"]) yield return RenderOperation(operation); } - private static string RenderSut(CanonicalDataCase canonicalDataCase) + private static string RenderSut(TestMethodBodyData canonicalDataCase) { var capacity = canonicalDataCase.Input["capacity"]; return $"var buffer = new CircularBuffer(capacity: {capacity});"; @@ -40,8 +39,8 @@ private static string RenderOperation(dynamic operation) private static string RenderReadOperation(dynamic operation) { - return operation["should_succeed"] - ? $"Assert.Equal({operation["expected"]}, buffer.Read());" + return operation["should_succeed"] + ? $"Assert.Equal({operation["expected"]}, buffer.Read());" : "Assert.Throws(() => buffer.Read());"; } diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Clock.cs index 6ca83f8953..e57109d0b7 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Clock.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using Generators.Input; using Generators.Output; namespace Generators.Exercises @@ -16,39 +15,39 @@ public class Clock : GeneratorExercise private const string PropertyEquals = "equals"; private const string PropertyToString = "to_string"; - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - if (canonicalDataCase.Property != PropertyEqual) + if (data.Property != PropertyEqual) { - canonicalDataCase.SetConstructorInputParameters(ParamHour, ParamMinute); + data.SetConstructorInputParameters(ParamHour, ParamMinute); } else { - canonicalDataCase.SetConstructorInputParameters(ParamClock2); + data.SetConstructorInputParameters(ParamClock2); - var result = (Dictionary)canonicalDataCase.Input[ParamClock1]; - canonicalDataCase.Input[ParamClock1] = new UnescapedValue($"new Clock({result[ParamHour]}, {result[ParamMinute]})"); + var result = (Dictionary)data.Input[ParamClock1]; + data.Input[ParamClock1] = new UnescapedValue($"new Clock({result[ParamHour]}, {result[ParamMinute]})"); } - if (canonicalDataCase.Property == PropertyCreate) + if (data.Property == PropertyCreate) { - canonicalDataCase.Property = PropertyToString; + data.Property = PropertyToString; } - else if (canonicalDataCase.Property == PropertyEqual) + else if (data.Property == PropertyEqual) { - canonicalDataCase.Property = PropertyEquals; + data.Property = PropertyEquals; } } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.Data.CanonicalDataCase.Property == PropertyEquals) + if (testMethodBody.Data.Property == PropertyEquals) { return RenderEqualToAssert(testMethodBody); } - return testMethodBody.Data.CanonicalDataCase.Property != PropertyToString - ? RenderConsistencyToAssert(testMethodBody) + return testMethodBody.Data.Property != PropertyToString + ? RenderConsistencyToAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } @@ -60,9 +59,9 @@ private static IEnumerable RenderConsistencyToAssert(TestMethodBody test private static IEnumerable RenderEqualToAssert(TestMethodBody testMethodBody) { - var expectedParameter = testMethodBody.Data.CanonicalDataCase.Input[ParamClock1]; + var expectedParameter = testMethodBody.Data.Input[ParamClock1]; const string testedValue = "sut"; - var expectedEqual = testMethodBody.Data.CanonicalDataCase.Expected; + var expectedEqual = testMethodBody.Data.Expected; testMethodBody.AssertTemplateParameters = new { expectedParameter, testedValue }; diff --git a/generators/Exercises/CollatzConjecture.cs b/generators/Exercises/CollatzConjecture.cs index 9dd17512b7..6e56dabf80 100644 --- a/generators/Exercises/CollatzConjecture.cs +++ b/generators/Exercises/CollatzConjecture.cs @@ -1,13 +1,13 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class CollatzConjecture : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.ExceptionThrown = canonicalDataCase.Input["number"] <= 0 ? typeof(ArgumentException) : null; + data.ExceptionThrown = data.Input["number"] <= 0 ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 695c880787..4593116325 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Input; using Generators.Output; using Newtonsoft.Json.Linq; @@ -9,26 +8,26 @@ namespace Generators.Exercises { public class ComplexNumbers : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Exercise = "complex-number"; - canonicalDataCase.UseVariableForExpected = IsComplexNumber(canonicalDataCase.Expected); - canonicalDataCase.Expected = ConvertToType(canonicalDataCase.Expected); + data.Exercise = "complex-number"; + data.UseVariableForExpected = IsComplexNumber(data.Expected); + data.Expected = ConvertToType(data.Expected); - var constructorParamName = canonicalDataCase.Input.ContainsKey("z") ? "z" : "z1"; - canonicalDataCase.Input["real"] = ConvertMathDouble(canonicalDataCase.Input[constructorParamName][0]); - canonicalDataCase.Input["imaginary"] = ConvertMathDouble(canonicalDataCase.Input[constructorParamName][1]); + var constructorParamName = data.Input.ContainsKey("z") ? "z" : "z1"; + data.Input["real"] = ConvertMathDouble(data.Input[constructorParamName][0]); + data.Input["imaginary"] = ConvertMathDouble(data.Input[constructorParamName][1]); - canonicalDataCase.SetInputParameters(GetInputParameters(canonicalDataCase, constructorParamName)); - canonicalDataCase.SetConstructorInputParameters("real", "imaginary"); + data.SetInputParameters(GetInputParameters(data, constructorParamName)); + data.SetConstructorInputParameters("real", "imaginary"); - var keys = canonicalDataCase.Input.Keys.ToArray(); + var keys = data.Input.Keys.ToArray(); foreach (var key in keys) - canonicalDataCase.Input[key] = ConvertToType(canonicalDataCase.Input[key]); + data.Input[key] = ConvertToType(data.Input[key]); } - private static string[] GetInputParameters(CanonicalDataCase canonicalDataCase, string constructorParamName) + private static string[] GetInputParameters(TestMethodBodyData canonicalDataCase, string constructorParamName) => canonicalDataCase.Input.Keys.Where(x => x != constructorParamName).ToArray(); protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/Connect.cs b/generators/Exercises/Connect.cs index 4db2c9ac16..fc8a21b5bd 100644 --- a/generators/Exercises/Connect.cs +++ b/generators/Exercises/Connect.cs @@ -1,28 +1,27 @@ using System.Collections; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class Connect : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForConstructorParameters = true; - canonicalDataCase.SetConstructorInputParameters("board"); - canonicalDataCase.Property = "result"; - canonicalDataCase.Input["board"] = ToMultiLineString(canonicalDataCase.Input["board"]); + data.UseVariablesForConstructorParameters = true; + data.SetConstructorInputParameters("board"); + data.Property = "result"; + data.Input["board"] = ToMultiLineString(data.Input["board"]); - switch (canonicalDataCase.Expected) + switch (data.Expected) { case "X": - canonicalDataCase.Expected = new UnescapedValue("ConnectWinner.Black"); + data.Expected = new UnescapedValue("ConnectWinner.Black"); break; case "O": - canonicalDataCase.Expected = new UnescapedValue("ConnectWinner.White"); + data.Expected = new UnescapedValue("ConnectWinner.White"); break; case "": - canonicalDataCase.Expected = new UnescapedValue("ConnectWinner.None"); + data.Expected = new UnescapedValue("ConnectWinner.None"); break; } } diff --git a/generators/Exercises/CryptoSquare.cs b/generators/Exercises/CryptoSquare.cs index 92461c9c4d..07d545faf7 100644 --- a/generators/Exercises/CryptoSquare.cs +++ b/generators/Exercises/CryptoSquare.cs @@ -1,13 +1,13 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class CryptoSquare : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; } } } \ No newline at end of file diff --git a/generators/Exercises/CustomSet.cs b/generators/Exercises/CustomSet.cs index e9bf267124..32cf5b5d0f 100644 --- a/generators/Exercises/CustomSet.cs +++ b/generators/Exercises/CustomSet.cs @@ -1,40 +1,39 @@ -using Generators.Input; -using Generators.Output; +using Generators.Output; namespace Generators.Exercises { public class CustomSet : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; + data.UseVariablesForInput = true; - if (canonicalDataCase.Input.ContainsKey("set")) + if (data.Input.ContainsKey("set")) { - if (!(canonicalDataCase.Input["set"] is int[])) + if (!(data.Input["set"] is int[])) { - canonicalDataCase.Input["set"] = new UnescapedValue(""); + data.Input["set"] = new UnescapedValue(""); } - canonicalDataCase.SetConstructorInputParameters("set"); + data.SetConstructorInputParameters("set"); } else { - if (!(canonicalDataCase.Input["set1"] is int[])) + if (!(data.Input["set1"] is int[])) { - canonicalDataCase.Input["set1"] = new UnescapedValue(""); + data.Input["set1"] = new UnescapedValue(""); } - canonicalDataCase.SetConstructorInputParameters("set1"); - canonicalDataCase.Input["set2"] = ConvertCustomSet(canonicalDataCase.Input["set2"]); + data.SetConstructorInputParameters("set1"); + data.Input["set2"] = ConvertCustomSet(data.Input["set2"]); - if (canonicalDataCase.Property == "equal") + if (data.Property == "equal") { - canonicalDataCase.Property = "Equals"; + data.Property = "Equals"; } } - canonicalDataCase.Expected = ConvertCustomSet(canonicalDataCase.Expected); + data.Expected = ConvertCustomSet(data.Expected); } private static dynamic ConvertCustomSet(dynamic value) diff --git a/generators/Exercises/DifferenceOfSquares.cs b/generators/Exercises/DifferenceOfSquares.cs index 29e24711af..b8513b8639 100644 --- a/generators/Exercises/DifferenceOfSquares.cs +++ b/generators/Exercises/DifferenceOfSquares.cs @@ -1,21 +1,21 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class DifferenceOfSquares : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - switch(canonicalDataCase.Property) + switch (data.Property) { case "squareOfSum": - canonicalDataCase.Property = "CalculateSquareOfSum"; + data.Property = "CalculateSquareOfSum"; break; case "sumOfSquares": - canonicalDataCase.Property = "CalculateSumOfSquares"; + data.Property = "CalculateSumOfSquares"; break; case "differenceOfSquares": - canonicalDataCase.Property = "CalculateDifferenceOfSquares"; + data.Property = "CalculateDifferenceOfSquares"; break; } } diff --git a/generators/Exercises/Dominoes.cs b/generators/Exercises/Dominoes.cs index f36bf58fff..bd8e563d9e 100644 --- a/generators/Exercises/Dominoes.cs +++ b/generators/Exercises/Dominoes.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Input; using Generators.Output; using Newtonsoft.Json.Linq; @@ -9,10 +8,10 @@ namespace Generators.Exercises { public class Dominoes : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.Input["dominoes"] = ConvertInput(canonicalDataCase.Input["dominoes"]); + data.UseVariablesForInput = true; + data.Input["dominoes"] = ConvertInput(data.Input["dominoes"]); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Tuple).Namespace }; diff --git a/generators/Exercises/Etl.cs b/generators/Exercises/Etl.cs index fdaee7d1db..0024343974 100644 --- a/generators/Exercises/Etl.cs +++ b/generators/Exercises/Etl.cs @@ -1,18 +1,18 @@ using System.Collections.Generic; using System.Linq; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Etl : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Input = ConvertInput(canonicalDataCase.Input); - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); - canonicalDataCase.SetInputParameters("input"); + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; + data.Input = ConvertInput(data.Input); + data.Expected = ConvertExpected(data.Expected); + data.SetInputParameters("input"); } private static dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/FlattenArray.cs b/generators/Exercises/FlattenArray.cs index 3a8fedced1..f6f1c32d2c 100644 --- a/generators/Exercises/FlattenArray.cs +++ b/generators/Exercises/FlattenArray.cs @@ -1,22 +1,21 @@ -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class FlattenArray : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; - var stringInput = canonicalDataCase.Input["array"].ToString(); + var stringInput = data.Input["array"].ToString(); // We skip reformatting of pure int arrays. if (stringInput.Contains("System.Int32")) return; - canonicalDataCase.Input["array"] = new UnescapedValue(ToProperObjArray(stringInput)); + data.Input["array"] = new UnescapedValue(ToProperObjArray(stringInput)); } private static string ToProperObjArray(string input) diff --git a/generators/Exercises/FoodChain.cs b/generators/Exercises/FoodChain.cs index b1677af21d..9e1fe7ba43 100644 --- a/generators/Exercises/FoodChain.cs +++ b/generators/Exercises/FoodChain.cs @@ -1,17 +1,18 @@ using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class FoodChain : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); - canonicalDataCase.UseVariableForExpected = true; + data.Expected = ConvertHelper.ToMultiLineString(data.Expected); + data.UseVariableForExpected = true; - if (canonicalDataCase.Input["startVerse"] == canonicalDataCase.Input["endVerse"]) + if (data.Input["startVerse"] == data.Input["endVerse"]) { - canonicalDataCase.SetInputParameters("startVerse"); + data.SetInputParameters("startVerse"); } } } diff --git a/generators/Exercises/Forth.cs b/generators/Exercises/Forth.cs index 384ea67bd6..51128fb794 100644 --- a/generators/Exercises/Forth.cs +++ b/generators/Exercises/Forth.cs @@ -1,21 +1,21 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Forth : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseFullDescriptionPath = true; + data.UseFullDescriptionPath = true; - if (canonicalDataCase.Expected == null) + if (data.Expected == null) { - canonicalDataCase.ExceptionThrown = typeof(InvalidOperationException); + data.ExceptionThrown = typeof(InvalidOperationException); } else { - canonicalDataCase.Expected = string.Join(" ", canonicalDataCase.Expected); + data.Expected = string.Join(" ", data.Expected); } } } diff --git a/generators/Exercises/Gigasecond.cs b/generators/Exercises/Gigasecond.cs index 210bb2d3ab..ed50429185 100644 --- a/generators/Exercises/Gigasecond.cs +++ b/generators/Exercises/Gigasecond.cs @@ -1,17 +1,16 @@ using System; using System.Collections.Generic; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class Gigasecond : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - var input = DateTime.Parse(canonicalDataCase.Input["birthdate"].ToString()); - canonicalDataCase.Input["birthdate"] = new UnescapedValue(FormatDateTime(input)); - canonicalDataCase.Expected = new UnescapedValue(FormatDateTime((DateTime)canonicalDataCase.Expected)); + var input = DateTime.Parse(data.Input["birthdate"].ToString()); + data.Input["birthdate"] = new UnescapedValue(FormatDateTime(input)); + data.Expected = new UnescapedValue(FormatDateTime((DateTime)data.Expected)); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(DateTime).Namespace }; diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index fe0a0f113b..114b23c9ed 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -10,30 +10,30 @@ namespace Generators.Exercises { public class GoCounting : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariablesForConstructorParameters = true; - canonicalDataCase.UseVariableForTested = true; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; + data.UseVariablesForConstructorParameters = true; + data.UseVariableForTested = true; - canonicalDataCase.Input["board"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["board"]); - canonicalDataCase.SetConstructorInputParameters("board"); + data.Input["board"] = ConvertHelper.ToMultiLineString(data.Input["board"]); + data.SetConstructorInputParameters("board"); - if (canonicalDataCase.Property == "territory") + if (data.Property == "territory") { - canonicalDataCase.Input["coordinate"] = (canonicalDataCase.Input["x"], canonicalDataCase.Input["y"]); - canonicalDataCase.SetInputParameters("coordinate"); + data.Input["coordinate"] = (data.Input["x"], data.Input["y"]); + data.SetInputParameters("coordinate"); - if (canonicalDataCase.Expected.ContainsKey("error")) + if (data.Expected.ContainsKey("error")) { - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); + data.ExceptionThrown = typeof(ArgumentException); } else { - var owner = FormatOwner(canonicalDataCase.Expected["owner"]); - var territory = FormatTerritory(canonicalDataCase.Expected["territory"]); - canonicalDataCase.Expected = (new UnescapedValue(owner), territory); + var owner = FormatOwner(data.Expected["owner"]); + var territory = FormatTerritory(data.Expected["territory"]); + data.Expected = (new UnescapedValue(owner), territory); } } else @@ -42,24 +42,24 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC { "new Dictionary[]>", "{", - $" [Owner.Black] = {FormatTerritory(canonicalDataCase.Expected["territoryBlack"])},", - $" [Owner.White] = {FormatTerritory(canonicalDataCase.Expected["territoryWhite"])},", - $" [Owner.None] = {FormatTerritory(canonicalDataCase.Expected["territoryNone"])}", + $" [Owner.Black] = {FormatTerritory(data.Expected["territoryBlack"])},", + $" [Owner.White] = {FormatTerritory(data.Expected["territoryWhite"])},", + $" [Owner.None] = {FormatTerritory(data.Expected["territoryNone"])}", "}" }; - canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); + data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown != null) + if (testMethodBody.Data.ExceptionThrown != null) { return base.RenderTestMethodBodyAssert(testMethodBody); } - if (testMethodBody.Data.CanonicalDataCase.Property == "territories") + if (testMethodBody.Data.Property == "territories") { return new[] { diff --git a/generators/Exercises/Grains.cs b/generators/Exercises/Grains.cs index 95afb17736..356910127b 100644 --- a/generators/Exercises/Grains.cs +++ b/generators/Exercises/Grains.cs @@ -1,16 +1,16 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Grains : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - if (ShouldThrowException(canonicalDataCase.Expected)) - canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); + if (ShouldThrowException(data.Expected)) + data.ExceptionThrown = typeof(ArgumentOutOfRangeException); else - canonicalDataCase.Expected = (ulong)canonicalDataCase.Expected; + data.Expected = (ulong)data.Expected; } private static bool ShouldThrowException(dynamic value) => value is int i && i == -1; diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index 31232e315f..3ff0377dfc 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -2,31 +2,30 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class Grep : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = "Match"; - canonicalDataCase.Input["flags"] = string.Join(" ", canonicalDataCase.Input["flags"]); - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + data.Property = "Match"; + data.Input["flags"] = string.Join(" ", data.Input["flags"]); + data.Expected = ConvertExpected(data.Expected); + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; } private static dynamic ConvertExpected(dynamic expected) { if (expected is object[] arr && arr.Length != 0) return new UnescapedValue( - Environment.NewLine + + Environment.NewLine + string.Join( Environment.NewLine, arr.Select((x, i) => $" \"{x}\\n\"{(i < arr.Length - 1 ? " +" : "")}"))); - + return ""; } diff --git a/generators/Exercises/Hamming.cs b/generators/Exercises/Hamming.cs index 9be6015fec..f9b5680966 100644 --- a/generators/Exercises/Hamming.cs +++ b/generators/Exercises/Hamming.cs @@ -1,13 +1,13 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Hamming : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is int ? null : typeof(ArgumentException); + data.ExceptionThrown = data.Expected is int ? null : typeof(ArgumentException); } } } diff --git a/generators/Exercises/House.cs b/generators/Exercises/House.cs index 4776fb7d8d..1fbc71d22d 100644 --- a/generators/Exercises/House.cs +++ b/generators/Exercises/House.cs @@ -1,17 +1,18 @@ using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class House : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); + data.UseVariableForExpected = true; + data.Expected = ConvertHelper.ToMultiLineString(data.Expected); - if (canonicalDataCase.Input["startVerse"] == canonicalDataCase.Input["endVerse"]) + if (data.Input["startVerse"] == data.Input["endVerse"]) { - canonicalDataCase.SetInputParameters("startVerse"); + data.SetInputParameters("startVerse"); } } } diff --git a/generators/Exercises/KindergartenGarden.cs b/generators/Exercises/KindergartenGarden.cs index 7cb8400bdf..88a6981aa6 100644 --- a/generators/Exercises/KindergartenGarden.cs +++ b/generators/Exercises/KindergartenGarden.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Linq; -using Generators.Input; using Generators.Output; using Humanizer; @@ -8,18 +7,18 @@ namespace Generators.Exercises { public class KindergartenGarden : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.TestedMethodType = TestedMethodType.Instance; - canonicalDataCase.UseFullDescriptionPath = true; + data.TestedMethodType = TestedMethodType.Instance; + data.UseFullDescriptionPath = true; - if (canonicalDataCase.Input.ContainsKey("students")) - canonicalDataCase.SetConstructorInputParameters("diagram", "students"); + if (data.Input.ContainsKey("students")) + data.SetConstructorInputParameters("diagram", "students"); else - canonicalDataCase.SetConstructorInputParameters("diagram"); + data.SetConstructorInputParameters("diagram"); - var plants = (IEnumerable)canonicalDataCase.Expected; - canonicalDataCase.Expected = plants + var plants = (IEnumerable)data.Expected; + data.Expected = plants .Select(x => new UnescapedValue($"Plant.{x.Humanize()}")) .ToArray(); } diff --git a/generators/Exercises/LargestSeriesProduct.cs b/generators/Exercises/LargestSeriesProduct.cs index 3149d1d9d6..13b081cc3a 100644 --- a/generators/Exercises/LargestSeriesProduct.cs +++ b/generators/Exercises/LargestSeriesProduct.cs @@ -1,16 +1,16 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class LargestSeriesProduct : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = "GetLargestProduct"; - - var caseInputLessThanZero = (long)canonicalDataCase.Expected == -1; - canonicalDataCase.ExceptionThrown = caseInputLessThanZero ? typeof(ArgumentException) : null; + data.Property = "GetLargestProduct"; + + var caseInputLessThanZero = (long)data.Expected == -1; + data.ExceptionThrown = caseInputLessThanZero ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/Leap.cs b/generators/Exercises/Leap.cs index 891b364bd7..d00488f47b 100644 --- a/generators/Exercises/Leap.cs +++ b/generators/Exercises/Leap.cs @@ -1,12 +1,12 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Leap : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = "IsLeapYear"; + data.Property = "IsLeapYear"; } } } \ No newline at end of file diff --git a/generators/Exercises/ListOps.cs b/generators/Exercises/ListOps.cs index 9b82463118..9b06940fd5 100644 --- a/generators/Exercises/ListOps.cs +++ b/generators/Exercises/ListOps.cs @@ -2,7 +2,6 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -using Generators.Input; using Generators.Output; using Newtonsoft.Json.Linq; @@ -10,32 +9,32 @@ namespace Generators.Exercises { public class ListOps : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseFullDescriptionPath = true; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = !(canonicalDataCase.Expected is int); + data.UseFullDescriptionPath = true; + data.UseVariablesForInput = true; + data.UseVariableForExpected = !(data.Expected is int); - if (canonicalDataCase.Input.TryGetValue("list", out var list)) - canonicalDataCase.Input["list"] = ConvertToList(list); + if (data.Input.TryGetValue("list", out var list)) + data.Input["list"] = ConvertToList(list); - if (canonicalDataCase.Input.TryGetValue("list1", out var list1)) - canonicalDataCase.Input["list1"] = ConvertToList(list1); + if (data.Input.TryGetValue("list1", out var list1)) + data.Input["list1"] = ConvertToList(list1); - if (canonicalDataCase.Input.TryGetValue("list2", out var list2)) - canonicalDataCase.Input["list2"] = ConvertToList(list2); + if (data.Input.TryGetValue("list2", out var list2)) + data.Input["list2"] = ConvertToList(list2); - if (canonicalDataCase.Input.TryGetValue("lists", out var lists)) - canonicalDataCase.Input["lists"] = ConvertToNestedList(lists, true); + if (data.Input.TryGetValue("lists", out var lists)) + data.Input["lists"] = ConvertToNestedList(lists, true); - if (canonicalDataCase.Input.TryGetValue("function", out var function)) - canonicalDataCase.Input["function"] = ConvertToFunction(canonicalDataCase.Property, function); + if (data.Input.TryGetValue("function", out var function)) + data.Input["function"] = ConvertToFunction(data.Property, function); - if (canonicalDataCase.Expected is IEnumerable) + if (data.Expected is IEnumerable) { - canonicalDataCase.Expected = canonicalDataCase.Input.ContainsKey("lists") - ? ConvertToNestedList(canonicalDataCase.Expected, false) - : ConvertToList(canonicalDataCase.Expected); + data.Expected = data.Input.ContainsKey("lists") + ? ConvertToNestedList(data.Expected, false) + : ConvertToList(data.Expected); } } diff --git a/generators/Exercises/Luhn.cs b/generators/Exercises/Luhn.cs index 57d0abc539..4b14e7db63 100644 --- a/generators/Exercises/Luhn.cs +++ b/generators/Exercises/Luhn.cs @@ -1,12 +1,12 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Luhn : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = "IsValid"; + data.Property = "IsValid"; } } } diff --git a/generators/Exercises/Markdown.cs b/generators/Exercises/Markdown.cs index 53b91bd10d..e079dbdfdb 100644 --- a/generators/Exercises/Markdown.cs +++ b/generators/Exercises/Markdown.cs @@ -1,17 +1,16 @@ -using Generators.Input; -using Generators.Output; +using Generators.Output; namespace Generators.Exercises { public class Markdown : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; } - protected override TestMethod CreateTestMethod(CanonicalDataCase canonicalDataCase, int index) + protected override TestMethod CreateTestMethod(TestMethodBodyData canonicalDataCase, int index) { var testMethod = base.CreateTestMethod(canonicalDataCase, index); testMethod.Skip = false; diff --git a/generators/Exercises/Matrix.cs b/generators/Exercises/Matrix.cs index fff768cf71..82a3e4cdb8 100644 --- a/generators/Exercises/Matrix.cs +++ b/generators/Exercises/Matrix.cs @@ -1,15 +1,15 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Matrix : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Properties["string"] = canonicalDataCase.Properties["input"]["string"]; - canonicalDataCase.SetConstructorInputParameters("string"); - canonicalDataCase.Properties["index"] = canonicalDataCase.Properties["input"]["index"]; - canonicalDataCase.SetInputParameters("index"); + data.Properties["string"] = data.Properties["input"]["string"]; + data.SetConstructorInputParameters("string"); + data.Properties["index"] = data.Properties["input"]["index"]; + data.SetInputParameters("index"); } } } diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 3d94c160ae..3cbd8de7f3 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Generators.Input; using Generators.Output; using Humanizer; @@ -15,19 +14,19 @@ public class Meetup : GeneratorExercise private const string PropertyDay = "Day"; - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = PropertyDay; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters(ParamMonth, ParamYear); - canonicalDataCase.SetInputParameters(ParamDayOfWeek, ParamWeek); + data.Property = PropertyDay; + data.UseVariableForExpected = true; + data.SetConstructorInputParameters(ParamMonth, ParamYear); + data.SetInputParameters(ParamDayOfWeek, ParamWeek); - canonicalDataCase.Input[ParamYear] = canonicalDataCase.Input[ParamYear]; - canonicalDataCase.Input[ParamMonth] = canonicalDataCase.Input[ParamMonth]; - canonicalDataCase.Input[ParamWeek] = - new UnescapedValue($"Schedule.{((string)canonicalDataCase.Input[ParamWeek]).Transform(To.SentenceCase)}"); - canonicalDataCase.Input[ParamDayOfWeek] = - new UnescapedValue($"DayOfWeek.{((string)canonicalDataCase.Input[ParamDayOfWeek]).Transform(To.SentenceCase)}"); + data.Input[ParamYear] = data.Input[ParamYear]; + data.Input[ParamMonth] = data.Input[ParamMonth]; + data.Input[ParamWeek] = + new UnescapedValue($"Schedule.{((string)data.Input[ParamWeek]).Transform(To.SentenceCase)}"); + data.Input[ParamDayOfWeek] = + new UnescapedValue($"DayOfWeek.{((string)data.Input[ParamDayOfWeek]).Transform(To.SentenceCase)}"); } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/Minesweeper.cs b/generators/Exercises/Minesweeper.cs index cebdaf79f6..5c4f71e6e2 100644 --- a/generators/Exercises/Minesweeper.cs +++ b/generators/Exercises/Minesweeper.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using Generators.Input; using Generators.Output; using Newtonsoft.Json.Linq; @@ -8,13 +7,13 @@ namespace Generators.Exercises { public class Minesweeper : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; - canonicalDataCase.Input["minefield"] = ToMultiLineString(canonicalDataCase.Input["minefield"]); - canonicalDataCase.Expected = ToMultiLineString(canonicalDataCase.Expected); + data.Input["minefield"] = ToMultiLineString(data.Input["minefield"]); + data.Expected = ToMultiLineString(data.Expected); } private static UnescapedValue ToMultiLineString(JArray input) => new UnescapedValue("Array.Empty()"); diff --git a/generators/Exercises/NthPrime.cs b/generators/Exercises/NthPrime.cs index 85c0df11da..b14cb44ec0 100644 --- a/generators/Exercises/NthPrime.cs +++ b/generators/Exercises/NthPrime.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class NthPrime : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is Dictionary ? typeof(ArgumentOutOfRangeException) : null; + data.ExceptionThrown = data.Expected is Dictionary ? typeof(ArgumentOutOfRangeException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index ea9a3dd1a3..3c5f3f47d6 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -1,20 +1,19 @@ using System.Collections.Generic; using System.Linq; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class NucleotideCount : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - if (((Dictionary) canonicalDataCase.Expected).ContainsKey("error")) + if (((Dictionary)data.Expected).ContainsKey("error")) return; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters("strand"); - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); + data.UseVariableForExpected = true; + data.SetConstructorInputParameters("strand"); + data.Expected = ConvertExpected(data.Expected); } private static dynamic ConvertExpected(dynamic expected) @@ -24,8 +23,8 @@ private static dynamic ConvertExpected(dynamic expected) protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - return testMethodBody.Data.UseVariableForExpected - ? RenderEqualBodyAssert(testMethodBody) + return testMethodBody.Data.UseVariableForExpected + ? RenderEqualBodyAssert(testMethodBody) : RenderThrowsBodyAssert(testMethodBody); } @@ -35,7 +34,7 @@ private static IEnumerable RenderEqualBodyAssert(TestMethodBody testMeth var templateParameters = new { - TestedMethodName = testMethodBody.Data.CanonicalDataCase.Property.ToTestedMethodName() + TestedMethodName = testMethodBody.Data.Property.ToTestedMethodName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; @@ -47,7 +46,7 @@ private static IEnumerable RenderThrowsBodyAssert(TestMethodBody testMet var templateParameters = new { - Input = testMethodBody.Data.CanonicalDataCase.Input["strand"] + Input = testMethodBody.Data.Input["strand"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/OcrNumbers.cs b/generators/Exercises/OcrNumbers.cs index 559fe113af..e6dbcd8c0a 100644 --- a/generators/Exercises/OcrNumbers.cs +++ b/generators/Exercises/OcrNumbers.cs @@ -1,20 +1,19 @@ using System; using System.Collections; using System.Collections.Generic; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class OcrNumbers : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) - { - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is int && canonicalDataCase.Expected <= 0 ? typeof(ArgumentException) : null; - canonicalDataCase.Input["rows"] = ToDigitStringRepresentation(canonicalDataCase.Input["rows"]); - canonicalDataCase.Expected = canonicalDataCase.Expected.ToString(); - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.UseVariablesForInput = true; + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + { + data.ExceptionThrown = data.Expected is int && data.Expected <= 0 ? typeof(ArgumentException) : null; + data.Input["rows"] = ToDigitStringRepresentation(data.Input["rows"]); + data.Expected = data.Expected.ToString(); + data.UseVariableForTested = true; + data.UseVariablesForInput = true; } private static UnescapedValue ToDigitStringRepresentation(IEnumerable input) diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/PalindromeProducts.cs index 9fc159edd1..c8c97033db 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/PalindromeProducts.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Input; using Generators.Output; using Newtonsoft.Json.Linq; @@ -9,23 +8,23 @@ namespace Generators.Exercises { public class PalindromeProducts : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - if (canonicalDataCase.Expected.ContainsKey("error")) + if (data.Expected.ContainsKey("error")) { - canonicalDataCase.ExceptionThrown = typeof(ArgumentException); + data.ExceptionThrown = typeof(ArgumentException); } else { - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = (canonicalDataCase.Expected["value"], FormatCoordinates(canonicalDataCase.Expected["factors"])); + data.UseVariableForTested = true; + data.UseVariableForExpected = true; + data.Expected = (data.Expected["value"], FormatCoordinates(data.Expected["factors"])); } } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.Data.CanonicalDataCase.ExceptionThrown != null) + if (testMethodBody.Data.ExceptionThrown != null) { return base.RenderTestMethodBodyAssert(testMethodBody); } diff --git a/generators/Exercises/PascalsTriangle.cs b/generators/Exercises/PascalsTriangle.cs index ccdee62da4..cc74b572a4 100644 --- a/generators/Exercises/PascalsTriangle.cs +++ b/generators/Exercises/PascalsTriangle.cs @@ -1,19 +1,19 @@ using System; -using Generators.Input; +using Generators.Output; using Newtonsoft.Json.Linq; namespace Generators.Exercises { public class PascalsTriangle : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Property = "calculate"; - if (canonicalDataCase.Expected is JArray jArray) - canonicalDataCase.Expected = jArray.ToObject(); + data.UseVariableForExpected = true; + data.Property = "calculate"; + if (data.Expected is JArray jArray) + data.Expected = jArray.ToObject(); else - canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); + data.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/PerfectNumbers.cs b/generators/Exercises/PerfectNumbers.cs index fa7ff0da45..cfc8d93579 100644 --- a/generators/Exercises/PerfectNumbers.cs +++ b/generators/Exercises/PerfectNumbers.cs @@ -1,5 +1,4 @@ using System; -using Generators.Input; using Generators.Output; using Humanizer; @@ -7,12 +6,12 @@ namespace Generators.Exercises { public class PerfectNumbers : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - if (canonicalDataCase.Expected is string classificationType) - canonicalDataCase.Expected = new UnescapedValue($"Classification.{classificationType.Transform(To.SentenceCase)}"); + if (data.Expected is string classificationType) + data.Expected = new UnescapedValue($"Classification.{classificationType.Transform(To.SentenceCase)}"); else - canonicalDataCase.ExceptionThrown = typeof(ArgumentOutOfRangeException); + data.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/PhoneNumber.cs b/generators/Exercises/PhoneNumber.cs index 9e42bff160..9d6624c844 100644 --- a/generators/Exercises/PhoneNumber.cs +++ b/generators/Exercises/PhoneNumber.cs @@ -1,14 +1,14 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class PhoneNumber : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is null ? typeof(ArgumentException) : null; + data.UseVariablesForInput = true; + data.ExceptionThrown = data.Expected is null ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/Poker.cs b/generators/Exercises/Poker.cs index b4231563dd..731b06c42e 100644 --- a/generators/Exercises/Poker.cs +++ b/generators/Exercises/Poker.cs @@ -1,14 +1,14 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Poker : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariableForTested = true; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; + data.UseVariableForTested = true; } } } diff --git a/generators/Exercises/Pov.cs b/generators/Exercises/Pov.cs index cf95eec5e3..53331013fa 100644 --- a/generators/Exercises/Pov.cs +++ b/generators/Exercises/Pov.cs @@ -1,24 +1,23 @@ using System; using System.Linq; using System.Text; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class Pov : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is null ? typeof(ArgumentException) : null; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; + data.ExceptionThrown = data.Expected is null ? typeof(ArgumentException) : null; - canonicalDataCase.Input["tree"] = RenderTree(canonicalDataCase.Input["tree"]); + data.Input["tree"] = RenderTree(data.Input["tree"]); - if (canonicalDataCase.Property == "fromPov") + if (data.Property == "fromPov") { - canonicalDataCase.Expected = RenderTree(canonicalDataCase.Expected); + data.Expected = RenderTree(data.Expected); } } diff --git a/generators/Exercises/Proverb.cs b/generators/Exercises/Proverb.cs index aa0baf8675..add5b77767 100644 --- a/generators/Exercises/Proverb.cs +++ b/generators/Exercises/Proverb.cs @@ -1,16 +1,17 @@ using System; using System.Collections.Generic; using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Proverb : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Input["strings"] = ConvertHelper.ToArray(canonicalDataCase.Input["strings"]); - canonicalDataCase.Expected = ConvertHelper.ToArray(canonicalDataCase.Expected); + data.UseVariableForExpected = true; + data.Input["strings"] = ConvertHelper.ToArray(data.Input["strings"]); + data.Expected = ConvertHelper.ToArray(data.Expected); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/QueenAttack.cs b/generators/Exercises/QueenAttack.cs index 642e036f5a..a2d82bbd82 100644 --- a/generators/Exercises/QueenAttack.cs +++ b/generators/Exercises/QueenAttack.cs @@ -1,25 +1,24 @@ using System; using System.Collections.Generic; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class QueenAttack : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - if (canonicalDataCase.Property == "create") - SetCreatePropertyData(canonicalDataCase); + if (data.Property == "create") + SetCreatePropertyData(data); } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.Data.CanonicalDataCase.Property == "canAttack") + if (testMethodBody.Data.Property == "canAttack") return new[] { RenderCanAttackAssert(testMethodBody) }; - return testMethodBody.Data.UseVariableForTested - ? Array.Empty() + return testMethodBody.Data.UseVariableForTested + ? Array.Empty() : base.RenderTestMethodBodyAssert(testMethodBody); } @@ -30,8 +29,8 @@ private static string RenderCanAttackAssert(TestMethodBody testMethodBody) var blackQueen = QueenAttack.Create({{blackQueenX}},{{blackQueenY}}); Assert.{% if Expected %}True{% else %}False{% endif %}(QueenAttack.CanAttack(whiteQueen, blackQueen));"; - var whiteQueenPositions = GetCoordinatesFromPosition(testMethodBody.Data.CanonicalDataCase.Input["white_queen"]); - var blackQueenPositions = GetCoordinatesFromPosition(testMethodBody.Data.CanonicalDataCase.Input["black_queen"]); + var whiteQueenPositions = GetCoordinatesFromPosition(testMethodBody.Data.Input["white_queen"]); + var blackQueenPositions = GetCoordinatesFromPosition(testMethodBody.Data.Input["black_queen"]); var templateParameters = new { @@ -39,7 +38,7 @@ private static string RenderCanAttackAssert(TestMethodBody testMethodBody) whiteQueenY = whiteQueenPositions.Item2, blackQueenX = blackQueenPositions.Item1, blackQueenY = blackQueenPositions.Item2, - testMethodBody.Data.CanonicalDataCase.Expected + testMethodBody.Data.Expected }; return TemplateRenderer.RenderInline(template, templateParameters); @@ -55,7 +54,7 @@ private static Tuple GetCoordinatesFromPosition(dynamic expected) return Tuple.Create(positionX, positionY); } - private static void SetCreatePropertyData(CanonicalDataCase canonicalDataCase) + private static void SetCreatePropertyData(TestMethodBodyData canonicalDataCase) { var validExpected = canonicalDataCase.Expected >= 0; diff --git a/generators/Exercises/RailFenceCipher.cs b/generators/Exercises/RailFenceCipher.cs index 601d41e14f..3f3a885d42 100644 --- a/generators/Exercises/RailFenceCipher.cs +++ b/generators/Exercises/RailFenceCipher.cs @@ -1,14 +1,14 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class RailFenceCipher : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.SetConstructorInputParameters("rails"); + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; + data.SetConstructorInputParameters("rails"); } } } \ No newline at end of file diff --git a/generators/Exercises/RationalNumbers.cs b/generators/Exercises/RationalNumbers.cs index e321b0ad50..1d9f950c99 100644 --- a/generators/Exercises/RationalNumbers.cs +++ b/generators/Exercises/RationalNumbers.cs @@ -19,9 +19,9 @@ public class RationalNumbers : GeneratorExercise { protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var input = testMethodBody.Data.CanonicalDataCase.Properties["input"] as Dictionary; - var operation = testMethodBody.Data.CanonicalDataCase.Properties["property"].ToString(); - var expected = testMethodBody.Data.CanonicalDataCase.Properties["expected"]; + var input = testMethodBody.Data.Properties["input"] as Dictionary; + var operation = testMethodBody.Data.Properties["property"].ToString(); + var expected = testMethodBody.Data.Properties["expected"]; var operationName = char.ToUpper(operation[0]) + operation.Substring(1); var assertCodeLine = ""; const string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; @@ -70,9 +70,9 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody return new[] { TemplateRenderer.RenderInline(assertCodeLine, testMethodBody.AssertTemplateParameters) }; } - private static int Precision(object rawValue) - => rawValue.ToString().Split(new[] { '.' }).Length <= 1 - ? 0 + private static int Precision(object rawValue) + => rawValue.ToString().Split(new[] { '.' }).Length <= 1 + ? 0 : rawValue.ToString().Split(new[] { '.' })[1].Length; } } \ No newline at end of file diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index 50609dffbb..13bf412722 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -15,10 +15,10 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod var arrange = new StringBuilder(); arrange.AppendLine("var sut = new Reactor();"); - var cells = RenderCells(testMethodBody.Data.CanonicalDataCase.Input["cells"]); + var cells = RenderCells(testMethodBody.Data.Input["cells"]); arrange.AppendLine(cells); - var operations = RenderOperations(testMethodBody.Data.CanonicalDataCase.Input["operations"]); + var operations = RenderOperations(testMethodBody.Data.Input["operations"]); arrange.AppendLine(operations); return new[] { arrange.ToString() }; @@ -57,9 +57,9 @@ private static string RenderComputeFunction(dynamic computeFunction) { var match = Regex.Match((string)computeFunction, "if (.+) then (.+) else (.+)"); - return match.Success - ? $"{match.Groups[1]} ? {match.Groups[2]} : {match.Groups[3]}" - : (string) computeFunction; + return match.Success + ? $"{match.Groups[1]} ? {match.Groups[2]} : {match.Groups[3]}" + : (string)computeFunction; } private static string RenderOperations(dynamic operations) diff --git a/generators/Exercises/Rectangles.cs b/generators/Exercises/Rectangles.cs index a73c2e24c0..295cd33a84 100644 --- a/generators/Exercises/Rectangles.cs +++ b/generators/Exercises/Rectangles.cs @@ -1,16 +1,16 @@ using System; using System.Collections.Generic; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Rectangles : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) - { - canonicalDataCase.Property = "count"; - canonicalDataCase.Input["strings"] = canonicalDataCase.Input["strings"] as string[] ?? Array.Empty(); - canonicalDataCase.UseVariablesForInput = true; + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + { + data.Property = "count"; + data.Input["strings"] = data.Input["strings"] as string[] ?? Array.Empty(); + data.UseVariablesForInput = true; } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/RnaTranscription.cs b/generators/Exercises/RnaTranscription.cs index 0e80e94fe3..4038ce54f5 100644 --- a/generators/Exercises/RnaTranscription.cs +++ b/generators/Exercises/RnaTranscription.cs @@ -1,13 +1,13 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class RnaTranscription : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is null ? typeof(ArgumentException) : null; + data.ExceptionThrown = data.Expected is null ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index 2114cfb8da..2c4ae1e5f7 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -1,33 +1,32 @@ using System; using System.Collections.Generic; using System.Text; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class RobotSimulator : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { const string direction = "direction"; const string position = "position"; const string coordinate = "coordinate"; - var positionVal = new UnescapedValue(GetCoordinateInstance(canonicalDataCase.Input[position])); - var directionVal = new UnescapedValue(GetDirectionEnum(canonicalDataCase.Input[direction])); + var positionVal = new UnescapedValue(GetCoordinateInstance(data.Input[position])); + var directionVal = new UnescapedValue(GetDirectionEnum(data.Input[direction])); - canonicalDataCase.Input[direction] = directionVal; - canonicalDataCase.Input[coordinate] = positionVal; + data.Input[direction] = directionVal; + data.Input[coordinate] = positionVal; - canonicalDataCase.SetConstructorInputParameters(direction, coordinate); + data.SetConstructorInputParameters(direction, coordinate); - canonicalDataCase.UseFullDescriptionPath = true; + data.UseFullDescriptionPath = true; } protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) { - switch (testMethodBody.Data.CanonicalDataCase.Property) + switch (testMethodBody.Data.Property) { case "create": return Array.Empty(); case "instructions": return RenderInstructionsMethodBodyAct(testMethodBody); @@ -41,7 +40,7 @@ private static IEnumerable RenderDefaultMethodBodyAct(TestMethodBody tes var templateParameters = new { - MethodInvocation = testMethodBody.Data.CanonicalDataCase.Property.ToTestedMethodName() + MethodInvocation = testMethodBody.Data.Property.ToTestedMethodName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; @@ -54,7 +53,7 @@ private static IEnumerable RenderInstructionsMethodBodyAct(TestMethodBod var templateParameters = new { MethodInvocation = "Simulate", - Instructions = testMethodBody.Data.CanonicalDataCase.Input["instructions"] + Instructions = testMethodBody.Data.Input["instructions"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; @@ -62,7 +61,7 @@ private static IEnumerable RenderInstructionsMethodBodyAct(TestMethodBod protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var expected = testMethodBody.Data.CanonicalDataCase.Expected as Dictionary; + var expected = testMethodBody.Data.Expected as Dictionary; expected.TryGetValue("position", out var position); expected.TryGetValue("direction", out var direction); diff --git a/generators/Exercises/RomanNumerals.cs b/generators/Exercises/RomanNumerals.cs index e835c2c6f3..92b34925f1 100644 --- a/generators/Exercises/RomanNumerals.cs +++ b/generators/Exercises/RomanNumerals.cs @@ -1,13 +1,13 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class RomanNumerals : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.TestedMethodType = TestedMethodType.Extension; - canonicalDataCase.Property = "ToRoman"; + data.TestedMethodType = TestedMethodType.Extension; + data.Property = "ToRoman"; } } } \ No newline at end of file diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index 446adcae6d..0c89ac7e69 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -1,20 +1,19 @@ using System.Collections.Generic; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class RunLengthEncoding : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Description = $"{canonicalDataCase.Property} {canonicalDataCase.Description}"; + data.Description = $"{data.Property} {data.Description}"; } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - return testMethodBody.Data.CanonicalDataCase.Property == "consistency" - ? RenderConsistencyToAssert(testMethodBody) + return testMethodBody.Data.Property == "consistency" + ? RenderConsistencyToAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } @@ -24,8 +23,8 @@ private static IEnumerable RenderConsistencyToAssert(TestMethodBody test var templateParameters = new { - ExpectedOutput = testMethodBody.Data.CanonicalDataCase.Expected, - ExerciseName = testMethodBody.Data.CanonicalDataCase.Exercise.ToTestedClassName() + ExpectedOutput = testMethodBody.Data.Expected, + ExerciseName = testMethodBody.Data.Exercise.ToTestedClassName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index d809e05301..d1b4312065 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -1,27 +1,27 @@ using System; using System.Collections.Generic; -using Generators.Input; +using Generators.Output; using Newtonsoft.Json.Linq; namespace Generators.Exercises { public class SaddlePoints : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.TestedMethodType = TestedMethodType.Instance; - canonicalDataCase.Property = "Calculate"; - canonicalDataCase.SetConstructorInputParameters("matrix"); - canonicalDataCase.UseVariablesForConstructorParameters = true; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.UseVariableForExpected = true; + data.TestedMethodType = TestedMethodType.Instance; + data.Property = "Calculate"; + data.SetConstructorInputParameters("matrix"); + data.UseVariablesForConstructorParameters = true; + data.UseVariablesForInput = true; + data.UseVariableForTested = true; + data.UseVariableForExpected = true; - canonicalDataCase.Input["matrix"] = ToMultiDimensionalArray(canonicalDataCase.Input["matrix"]); + data.Input["matrix"] = ToMultiDimensionalArray(data.Input["matrix"]); - if (canonicalDataCase.Expected is Array array) + if (data.Expected is Array array) { - canonicalDataCase.Expected = ToTupleCollection(array); + data.Expected = ToTupleCollection(array); } } diff --git a/generators/Exercises/Say.cs b/generators/Exercises/Say.cs index c98372f741..8135a3e051 100644 --- a/generators/Exercises/Say.cs +++ b/generators/Exercises/Say.cs @@ -1,14 +1,14 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Say : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = "InEnglish"; - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is int ? typeof(ArgumentOutOfRangeException) : null; + data.Property = "InEnglish"; + data.ExceptionThrown = data.Expected is int ? typeof(ArgumentOutOfRangeException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/ScaleGenerator.cs b/generators/Exercises/ScaleGenerator.cs index c03ed17b1e..063ba04d4a 100644 --- a/generators/Exercises/ScaleGenerator.cs +++ b/generators/Exercises/ScaleGenerator.cs @@ -1,12 +1,12 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class ScaleGenerator : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; + data.UseVariableForExpected = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Sieve.cs b/generators/Exercises/Sieve.cs index 9836625a8d..e2e34073b9 100644 --- a/generators/Exercises/Sieve.cs +++ b/generators/Exercises/Sieve.cs @@ -1,14 +1,14 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Sieve : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.ExceptionThrown = canonicalDataCase.Input["limit"] < 2 ? typeof(ArgumentOutOfRangeException) : null; + data.UseVariableForExpected = true; + data.ExceptionThrown = data.Input["limit"] < 2 ? typeof(ArgumentOutOfRangeException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index 430db51cb2..de1ec6e96e 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -1,58 +1,57 @@ using System; using System.Collections.Generic; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class SimpleCipher : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseFullDescriptionPath = true; + data.UseFullDescriptionPath = true; - if (canonicalDataCase.Property == "new") + if (data.Property == "new") { return; } - canonicalDataCase.TestedMethodType = TestedMethodType.Instance; + data.TestedMethodType = TestedMethodType.Instance; - if (canonicalDataCase.Input.ContainsKey("key")) + if (data.Input.ContainsKey("key")) { - canonicalDataCase.SetConstructorInputParameters("key"); + data.SetConstructorInputParameters("key"); } - if (canonicalDataCase.Input.TryGetValue("ciphertext", out var cipherText)) + if (data.Input.TryGetValue("ciphertext", out var cipherText)) { switch (cipherText) { case "cipher.key": - canonicalDataCase.Input["ciphertext"] = new UnescapedValue("sut.Key.Substring(0, 10)"); + data.Input["ciphertext"] = new UnescapedValue("sut.Key.Substring(0, 10)"); break; case "cipher.encode": - var plaintext = ValueFormatter.Format(canonicalDataCase.Input["plaintext"]); - canonicalDataCase.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); - canonicalDataCase.SetInputParameters("ciphertext"); + var plaintext = ValueFormatter.Format(data.Input["plaintext"]); + data.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); + data.SetInputParameters("ciphertext"); break; } } - if (canonicalDataCase.Expected is string s && s == "cipher.key") + if (data.Expected is string s && s == "cipher.key") { - canonicalDataCase.Expected = new UnescapedValue("sut.Key.Substring(0, 10)"); + data.Expected = new UnescapedValue("sut.Key.Substring(0, 10)"); } } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - switch (testMethodBody.Data.CanonicalDataCase.Property) + switch (testMethodBody.Data.Property) { case "new": - var key = ValueFormatter.Format(testMethodBody.Data.CanonicalDataCase.Input["key"]); + var key = ValueFormatter.Format(testMethodBody.Data.Input["key"]); return new[] { $"Assert.Throws(() => new SimpleCipher({key}));" }; case "key": - var pattern = ValueFormatter.Format(testMethodBody.Data.CanonicalDataCase.Expected["match"]); + var pattern = ValueFormatter.Format(testMethodBody.Data.Expected["match"]); return new[] { $"Assert.Matches({pattern}, sut.Key);" }; default: return base.RenderTestMethodBodyAssert(testMethodBody); diff --git a/generators/Exercises/SpaceAge.cs b/generators/Exercises/SpaceAge.cs index 60bb8f8fa7..b76e08b7c2 100644 --- a/generators/Exercises/SpaceAge.cs +++ b/generators/Exercises/SpaceAge.cs @@ -1,14 +1,14 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class SpaceAge : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = $"On_{canonicalDataCase.Input["planet"]}"; - canonicalDataCase.SetInputParameters(); - canonicalDataCase.SetConstructorInputParameters("seconds"); + data.Property = $"On_{data.Input["planet"]}"; + data.SetInputParameters(); + data.SetConstructorInputParameters("seconds"); } } } \ No newline at end of file diff --git a/generators/Exercises/SpiralMatrix.cs b/generators/Exercises/SpiralMatrix.cs index a003ab14b6..cf12817b27 100644 --- a/generators/Exercises/SpiralMatrix.cs +++ b/generators/Exercises/SpiralMatrix.cs @@ -1,16 +1,16 @@ using System.Linq; -using Generators.Input; +using Generators.Output; using Newtonsoft.Json.Linq; namespace Generators.Exercises { public class SpiralMatrix : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = "GetMatrix"; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); + data.Property = "GetMatrix"; + data.UseVariableForExpected = true; + data.Expected = ConvertExpected(data.Expected); } private static dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/Sublist.cs b/generators/Exercises/Sublist.cs index db9ba1f4c3..ecc12fd731 100644 --- a/generators/Exercises/Sublist.cs +++ b/generators/Exercises/Sublist.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using System.Linq; -using Generators.Input; using Generators.Output; using Humanizer; @@ -8,13 +7,13 @@ namespace Generators.Exercises { public class Sublist : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Input["listOne"] = InputValues(canonicalDataCase.Input["listOne"] as int[]); - canonicalDataCase.Input["listTwo"] = InputValues(canonicalDataCase.Input["listTwo"] as int[]); + data.Input["listOne"] = InputValues(data.Input["listOne"] as int[]); + data.Input["listTwo"] = InputValues(data.Input["listTwo"] as int[]); - canonicalDataCase.Property = "classify"; - canonicalDataCase.Expected = new UnescapedValue($"SublistType.{(canonicalDataCase.Expected as string).Dehumanize()}"); + data.Property = "classify"; + data.Expected = new UnescapedValue($"SublistType.{(data.Expected as string).Dehumanize()}"); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(IList).Namespace }; diff --git a/generators/Exercises/SumOfMultiples.cs b/generators/Exercises/SumOfMultiples.cs index bb8499df23..00df355129 100644 --- a/generators/Exercises/SumOfMultiples.cs +++ b/generators/Exercises/SumOfMultiples.cs @@ -1,14 +1,15 @@ using System; using System.Collections.Generic; using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class SumOfMultiples : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Input["factors"] = ConvertHelper.ToArray(canonicalDataCase.Input["factors"]); + data.Input["factors"] = ConvertHelper.ToArray(data.Input["factors"]); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index abac948bf3..d4c6689990 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -9,14 +9,14 @@ namespace Generators.Exercises { public class Tournament : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = "RunTally"; - canonicalDataCase.TestedMethodType = TestedMethodType.Static; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Input["rows"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["rows"], ""); - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); + data.Property = "RunTally"; + data.TestedMethodType = TestedMethodType.Static; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; + data.Input["rows"] = ConvertHelper.ToMultiLineString(data.Input["rows"], ""); + data.Expected = ConvertHelper.ToMultiLineString(data.Expected); } protected override IEnumerable AdditionalNamespaces => new[] diff --git a/generators/Exercises/Transpose.cs b/generators/Exercises/Transpose.cs index 75a64ad444..acc163418b 100644 --- a/generators/Exercises/Transpose.cs +++ b/generators/Exercises/Transpose.cs @@ -1,17 +1,18 @@ using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Transpose : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Property = "String"; - canonicalDataCase.Input["lines"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["lines"], ""); - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected, ""); + data.Property = "String"; + data.Input["lines"] = ConvertHelper.ToMultiLineString(data.Input["lines"], ""); + data.Expected = ConvertHelper.ToMultiLineString(data.Expected, ""); - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForExpected = true; + data.UseVariablesForInput = true; + data.UseVariableForExpected = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Triangle.cs b/generators/Exercises/Triangle.cs index 2418b478a8..ccffefb8a4 100644 --- a/generators/Exercises/Triangle.cs +++ b/generators/Exercises/Triangle.cs @@ -1,25 +1,25 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Triangle : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - if (canonicalDataCase.Property == "equilateral") - canonicalDataCase.Property = "IsEquilateral"; - else if (canonicalDataCase.Property == "isosceles") - canonicalDataCase.Property = "IsIsosceles"; - else if (canonicalDataCase.Property == "scalene") - canonicalDataCase.Property = "IsScalene"; + if (data.Property == "equilateral") + data.Property = "IsEquilateral"; + else if (data.Property == "isosceles") + data.Property = "IsIsosceles"; + else if (data.Property == "scalene") + data.Property = "IsScalene"; - canonicalDataCase.Input["x"] = canonicalDataCase.Input["sides"][0]; - canonicalDataCase.Input["y"] = canonicalDataCase.Input["sides"][1]; - canonicalDataCase.Input["z"] = canonicalDataCase.Input["sides"][2]; - canonicalDataCase.Input.Remove("sides"); - canonicalDataCase.SetInputParameters("x", "y", "z"); + data.Input["x"] = data.Input["sides"][0]; + data.Input["y"] = data.Input["sides"][1]; + data.Input["z"] = data.Input["sides"][2]; + data.Input.Remove("sides"); + data.SetInputParameters("x", "y", "z"); - canonicalDataCase.UseFullDescriptionPath = true; + data.UseFullDescriptionPath = true; } } } \ No newline at end of file diff --git a/generators/Exercises/TwelveDays.cs b/generators/Exercises/TwelveDays.cs index ccb95be9da..7a8c10fb96 100644 --- a/generators/Exercises/TwelveDays.cs +++ b/generators/Exercises/TwelveDays.cs @@ -1,17 +1,18 @@ using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class TwelveDays : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.Expected = ConvertHelper.ToMultiLineString(canonicalDataCase.Expected); + data.UseVariableForExpected = true; + data.Expected = ConvertHelper.ToMultiLineString(data.Expected); - if (canonicalDataCase.Input["startVerse"] == canonicalDataCase.Input["endVerse"]) + if (data.Input["startVerse"] == data.Input["endVerse"]) { - canonicalDataCase.SetInputParameters("startVerse"); + data.SetInputParameters("startVerse"); } } } diff --git a/generators/Exercises/TwoBucket.cs b/generators/Exercises/TwoBucket.cs index aafc0361b2..e596a6d11a 100644 --- a/generators/Exercises/TwoBucket.cs +++ b/generators/Exercises/TwoBucket.cs @@ -1,18 +1,17 @@ using System.Collections.Generic; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class TwoBucket : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.TestedMethodType = TestedMethodType.Instance; - canonicalDataCase.SetConstructorInputParameters("bucketOne", "bucketTwo", "startBucket"); + data.TestedMethodType = TestedMethodType.Instance; + data.SetConstructorInputParameters("bucketOne", "bucketTwo", "startBucket"); - var startBucket = canonicalDataCase.Input["startBucket"]; - canonicalDataCase.Input["startBucket"] = new UnescapedValue(startBucket == "two" ? "Bucket.Two" : "Bucket.One"); + var startBucket = data.Input["startBucket"]; + data.Input["startBucket"] = new UnescapedValue(startBucket == "two" ? "Bucket.Two" : "Bucket.One"); } protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) @@ -36,9 +35,9 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody var templateParameters = new { - MovesExpected = testMethodBody.Data.CanonicalDataCase.Expected["moves"], - OtherBucketExpected = testMethodBody.Data.CanonicalDataCase.Expected["otherBucket"], - GoalBucketExpected = testMethodBody.Data.CanonicalDataCase.Expected["goalBucket"] + MovesExpected = testMethodBody.Data.Expected["moves"], + OtherBucketExpected = testMethodBody.Data.Expected["otherBucket"], + GoalBucketExpected = testMethodBody.Data.Expected["goalBucket"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/TwoFer.cs b/generators/Exercises/TwoFer.cs index b2c4824b97..9b5ff1d453 100644 --- a/generators/Exercises/TwoFer.cs +++ b/generators/Exercises/TwoFer.cs @@ -1,12 +1,12 @@ -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class TwoFer : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) - { - canonicalDataCase.Property = "Name"; + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + { + data.Property = "Name"; } } } \ No newline at end of file diff --git a/generators/Exercises/VariableLengthQuantity.cs b/generators/Exercises/VariableLengthQuantity.cs index 169a9414f1..6018b80632 100644 --- a/generators/Exercises/VariableLengthQuantity.cs +++ b/generators/Exercises/VariableLengthQuantity.cs @@ -2,23 +2,22 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -using Generators.Input; using Generators.Output; namespace Generators.Exercises { public class VariableLengthQuantity : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.Input["integers"] = FormatUInt32Array(canonicalDataCase.Input["integers"]); + data.UseVariableForExpected = true; + data.UseVariablesForInput = true; + data.Input["integers"] = FormatUInt32Array(data.Input["integers"]); - if (canonicalDataCase.Expected == null) - canonicalDataCase.ExceptionThrown = typeof(InvalidOperationException); + if (data.Expected == null) + data.ExceptionThrown = typeof(InvalidOperationException); else - canonicalDataCase.Expected = FormatUInt32Array(canonicalDataCase.Expected); + data.Expected = FormatUInt32Array(data.Expected); } protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; diff --git a/generators/Exercises/WordCount.cs b/generators/Exercises/WordCount.cs index a45fc634ba..0d3da9d250 100644 --- a/generators/Exercises/WordCount.cs +++ b/generators/Exercises/WordCount.cs @@ -1,16 +1,16 @@ using System.Collections.Generic; using System.Linq; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class WordCount : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.Expected = ConvertExpected(canonicalDataCase.Expected); + data.UseVariableForExpected = true; + data.UseVariableForTested = true; + data.Expected = ConvertExpected(data.Expected); } private static dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index 1b6246d758..364913c4be 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -8,18 +8,18 @@ namespace Generators.Exercises { public class WordSearch : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.UseVariablesForInput = true; - canonicalDataCase.UseVariableForTested = true; - canonicalDataCase.UseVariableForExpected = true; - canonicalDataCase.UseVariablesForConstructorParameters = true; + data.UseVariablesForInput = true; + data.UseVariableForTested = true; + data.UseVariableForExpected = true; + data.UseVariablesForConstructorParameters = true; - canonicalDataCase.SetConstructorInputParameters("grid"); + data.SetConstructorInputParameters("grid"); - canonicalDataCase.Input["grid"] = ConvertHelper.ToMultiLineString(canonicalDataCase.Input["grid"]); + data.Input["grid"] = ConvertHelper.ToMultiLineString(data.Input["grid"]); - var expectedDictionary = canonicalDataCase.Expected as IDictionary; + var expectedDictionary = data.Expected as IDictionary; var expected = new List { @@ -30,12 +30,12 @@ protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataC expected.AddRange(expectedDictionary.Select((kv, i) => $" [\"{kv.Key}\"] = {FormatPosition(kv.Value)}{(i < expectedDictionary.Count - 1 ? "," : "")}")); expected.Add("}"); - canonicalDataCase.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); + data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var expectedDictionary = testMethodBody.Data.CanonicalDataCase.Properties["expected"] as IDictionary; + var expectedDictionary = testMethodBody.Data.Properties["expected"] as IDictionary; foreach (var kv in expectedDictionary) yield return RenderTestMethodBodyAssertForSearchWord(kv.Key, kv.Value); @@ -43,15 +43,15 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody private static string RenderTestMethodBodyAssertForSearchWord(string word, dynamic expected) { - return expected == null - ? $"Assert.Null(expected[\"{word}\"]);" + return expected == null + ? $"Assert.Null(expected[\"{word}\"]);" : $"Assert.Equal(expected[\"{word}\"], actual[\"{word}\"]);"; } private static string FormatPosition(dynamic position) { - return position == null - ? "null" : + return position == null + ? "null" : ValueFormatter.Format((FormatCoordinate(position["start"]), FormatCoordinate(position["end"]))); } diff --git a/generators/Exercises/Wordy.cs b/generators/Exercises/Wordy.cs index f1adfbffc4..7efdd80273 100644 --- a/generators/Exercises/Wordy.cs +++ b/generators/Exercises/Wordy.cs @@ -1,13 +1,13 @@ using System; -using Generators.Input; +using Generators.Output; namespace Generators.Exercises { public class Wordy : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.ExceptionThrown = canonicalDataCase.Expected is bool ? typeof(ArgumentException) : null; + data.ExceptionThrown = data.Expected is bool ? typeof(ArgumentException) : null; } } } \ No newline at end of file diff --git a/generators/Exercises/Yacht.cs b/generators/Exercises/Yacht.cs index 4b8c7e1017..449252c4c5 100644 --- a/generators/Exercises/Yacht.cs +++ b/generators/Exercises/Yacht.cs @@ -1,17 +1,16 @@ -using Generators.Input; -using Generators.Output; +using Generators.Output; using Humanizer; namespace Generators.Exercises { public class Yacht : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) { - canonicalDataCase.Exercise = "yacht-game"; - var category = canonicalDataCase.Input["category"].ToString(); + data.Exercise = "yacht-game"; + var category = data.Input["category"].ToString(); var formattedCategory = StringDehumanizeExtensions.Dehumanize(category); - canonicalDataCase.Input["category"] = new UnescapedValue($"YachtCategory.{formattedCategory}"); + data.Input["category"] = new UnescapedValue($"YachtCategory.{formattedCategory}"); } } } diff --git a/generators/Exercises/ZebraPuzzle.cs b/generators/Exercises/ZebraPuzzle.cs index 0e7dfeed2f..ba4f620e0b 100644 --- a/generators/Exercises/ZebraPuzzle.cs +++ b/generators/Exercises/ZebraPuzzle.cs @@ -1,15 +1,14 @@ -using Generators.Input; -using Generators.Output; +using Generators.Output; using Humanizer; namespace Generators.Exercises { public class ZebraPuzzle : GeneratorExercise { - protected override void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) - { - var nationality = canonicalDataCase.Expected as string; - canonicalDataCase.Expected = new UnescapedValue($"Nationality.{nationality.Humanize()}"); + protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + { + var nationality = data.Expected as string; + data.Expected = new UnescapedValue($"Nationality.{nationality.Humanize()}"); } } } \ No newline at end of file diff --git a/generators/Exercises/Zipper.cs b/generators/Exercises/Zipper.cs index 68b9766fd4..27dfe53a71 100644 --- a/generators/Exercises/Zipper.cs +++ b/generators/Exercises/Zipper.cs @@ -10,17 +10,17 @@ public class Zipper : GeneratorExercise { protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) { - var tree = RenderTree(testMethodBody.Data.CanonicalDataCase.Input["initialTree"]); + var tree = RenderTree(testMethodBody.Data.Input["initialTree"]); yield return $"var tree = {tree};"; yield return "var sut = Zipper.FromTree(tree);"; - var operations = RenderOperations(testMethodBody.Data.CanonicalDataCase.Input["operations"]); + var operations = RenderOperations(testMethodBody.Data.Input["operations"]); yield return $"var actual = sut{operations};"; } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - var expected = RenderExpected(testMethodBody.Data.CanonicalDataCase.Expected); + var expected = RenderExpected(testMethodBody.Data.Expected); if (expected == null) { yield return "Assert.Null(actual);"; diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index 19f3ac54ac..51186970e7 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -8,7 +8,6 @@ namespace Generators { public abstract class GeneratorExercise : Exercise { - private static readonly ExerciseWriter ExerciseWriter = new ExerciseWriter(); private CanonicalData _canonicalData; public override string Name => GetType().ToExerciseName(); @@ -17,18 +16,11 @@ public void Regenerate(CanonicalData canonicalData) { _canonicalData = canonicalData; - foreach (var canonicalDataCase in _canonicalData.Cases) - UpdateCanonicalDataCase(canonicalDataCase); - ExerciseWriter.WriteToFile(this); } public string Render() => CreateTestClass().Render(); - protected virtual void UpdateCanonicalDataCase(CanonicalDataCase canonicalDataCase) - { - } - protected virtual IEnumerable AdditionalNamespaces => Enumerable.Empty(); protected virtual IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) @@ -42,64 +34,81 @@ protected virtual IEnumerable RenderTestMethodBodyAssert(TestMethodBody protected virtual IEnumerable RenderAdditionalMethods() => Array.Empty(); - private IEnumerable GetUsingNamespaces() + private IEnumerable GetUsingNamespaces(IEnumerable testMethodBodyData) { var usingNamespaces = new HashSet { "Xunit" }; - foreach (var canonicalDataCase in _canonicalData.Cases.Where(canonicalDataCase => canonicalDataCase.ExceptionThrown != null)) - usingNamespaces.Add(canonicalDataCase.ExceptionThrown.Namespace); + foreach (var data in testMethodBodyData.Where(x => x.ExceptionThrown != null)) + usingNamespaces.Add(data.ExceptionThrown.Namespace); usingNamespaces.UnionWith(AdditionalNamespaces); return usingNamespaces; } - private IEnumerable RenderTestMethods() => _canonicalData.Cases.Select(RenderTestMethod).Concat(RenderAdditionalMethods()).ToArray(); + private IEnumerable RenderTestMethods(IEnumerable testMethodBodyData) + => testMethodBodyData + .Select(RenderTestMethod) + .Concat(RenderAdditionalMethods()) + .ToArray(); - protected virtual TestClass CreateTestClass() => new TestClass + protected virtual TestClass CreateTestClass() { - ClassName = Name.ToTestClassName(), - Methods = RenderTestMethods(), - CanonicalDataVersion = _canonicalData.Version, - UsingNamespaces = GetUsingNamespaces() - }; + var testMethodBodyData = _canonicalData.Cases + .Select(canonicalDataCase => CreateTestMethodBodyData(_canonicalData, canonicalDataCase)) + .ToArray(); + + foreach (var data in testMethodBodyData) + UpdateTestMethodBodyData(data); + + return new TestClass + { + ClassName = Name.ToTestClassName(), + Methods = RenderTestMethods(testMethodBodyData), + CanonicalDataVersion = _canonicalData.Version, + UsingNamespaces = GetUsingNamespaces(testMethodBodyData) + }; + } - private string RenderTestMethod(CanonicalDataCase canonicalDataCase, int index) => CreateTestMethod(canonicalDataCase, index).Render(); + private string RenderTestMethod(TestMethodBodyData data, int index) => CreateTestMethod(data, index).Render(); - protected virtual TestMethod CreateTestMethod(CanonicalDataCase canonicalDataCase, int index) => new TestMethod + protected virtual TestMethod CreateTestMethod(TestMethodBodyData data, int index) => new TestMethod { Skip = index > 0, - Name = ToTestMethodName(canonicalDataCase), - Body = RenderTestMethodBody(canonicalDataCase) + Name = ToTestMethodName(data), + Body = RenderTestMethodBody(data) }; - private static string ToTestMethodName(CanonicalDataCase canonicalDataCase) - => canonicalDataCase.UseFullDescriptionPath - ? string.Join(" - ", canonicalDataCase.DescriptionPath).ToTestMethodName() - : canonicalDataCase.Description.ToTestMethodName(); + private static string ToTestMethodName(TestMethodBodyData data) + => data.UseFullDescriptionPath + ? string.Join(" - ", data.DescriptionPath).ToTestMethodName() + : data.Description.ToTestMethodName(); - private string RenderTestMethodBody(CanonicalDataCase canonicalDataCase) + private string RenderTestMethodBody(TestMethodBodyData data) { - var testMethodBodyData = CreateTestMethodBodyData(canonicalDataCase); - var testMethodBody = CreateTestMethodBody(testMethodBodyData); + var testMethodBody = CreateTestMethodBody(data); testMethodBody.Arrange = RenderTestMethodBodyArrange(testMethodBody); testMethodBody.Act = RenderTestMethodBodyAct(testMethodBody); testMethodBody.Assert = RenderTestMethodBodyAssert(testMethodBody); return testMethodBody.Render(); } - - protected virtual TestMethodBodyData CreateTestMethodBodyData(CanonicalDataCase canonicalDataCase) - => new TestMethodBodyData(canonicalDataCase); + + protected virtual TestMethodBodyData CreateTestMethodBodyData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) + => new TestMethodBodyData(canonicalData, canonicalDataCase); + + protected virtual void UpdateTestMethodBodyData(TestMethodBodyData data) + { + } protected virtual TestMethodBody CreateTestMethodBody(TestMethodBodyData data) { - if (data.CanonicalDataCase.ExceptionThrown != null) + if (data.ExceptionThrown != null) { return new TestMethodBodyWithExceptionCheck(data); } - switch (data.CanonicalDataCase.Expected) + switch (data.Expected) { case bool _: return new TestMethodBodyWithBooleanCheck(data); diff --git a/generators/Input/CanonicalData.cs b/generators/Input/CanonicalData.cs index 19268a61e2..5821c6e961 100644 --- a/generators/Input/CanonicalData.cs +++ b/generators/Input/CanonicalData.cs @@ -1,12 +1,14 @@ -namespace Generators.Input +using System.Collections.Generic; + +namespace Generators.Input { public sealed class CanonicalData { - public CanonicalData(string exercise, string version, CanonicalDataCase[] cases) + public CanonicalData(string exercise, string version, IReadOnlyCollection cases) => (Exercise, Version, Cases) = (exercise, version, cases); public string Exercise { get; } public string Version { get; } - public CanonicalDataCase[] Cases { get; } + public IReadOnlyCollection Cases { get; } } } \ No newline at end of file diff --git a/generators/Input/CanonicalDataCase.cs b/generators/Input/CanonicalDataCase.cs index 81834ebca6..2bc04f036d 100644 --- a/generators/Input/CanonicalDataCase.cs +++ b/generators/Input/CanonicalDataCase.cs @@ -1,47 +1,20 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; namespace Generators.Input { public sealed class CanonicalDataCase { - public IDictionary Properties { get; set; } - public IDictionary Input { get; set; } - public dynamic Expected { get; set; } - - public string Exercise { get; set; } - public string Property { get; set; } - public string Description { get; set; } - public string[] DescriptionPath { get; set; } - - public bool UseVariablesForInput { get; set; } - public bool UseVariableForExpected { get; set; } - public bool UseVariablesForConstructorParameters { get; set; } - public bool UseVariableForTested { get; set; } - public bool UseFullDescriptionPath { get; set; } - - public TestedMethodType TestedMethodType { get; set; } - public Type ExceptionThrown { get; set; } - - public HashSet InputParameters { get; } = new HashSet(); - public HashSet ConstructorInputParameters { get; } = new HashSet(); - - public void SetInputParameters(params string[] properties) - { - InputParameters.Clear(); - InputParameters.UnionWith(properties); - - ConstructorInputParameters.ExceptWith(properties); - } - - public void SetConstructorInputParameters(params string[] properties) - { - ConstructorInputParameters.Clear(); - ConstructorInputParameters.UnionWith(properties); - - InputParameters.ExceptWith(properties); - - TestedMethodType = TestedMethodType.Instance; - } + public CanonicalDataCase(string property, IReadOnlyDictionary properties, + IReadOnlyDictionary input, dynamic expected, + string description, IReadOnlyCollection descriptionPath) + => (Property, Properties, Input, Expected, Description, DescriptionPath) = + (property, properties, input, expected, description, descriptionPath); + + public IReadOnlyDictionary Properties { get; } + public IReadOnlyDictionary Input { get; } + public dynamic Expected { get; } + public string Property { get; } + public string Description { get; } + public IReadOnlyCollection DescriptionPath { get; } } } \ No newline at end of file diff --git a/generators/Input/CanonicalDataCaseParser.cs b/generators/Input/CanonicalDataCaseParser.cs index f9cc25b36b..6823349de6 100644 --- a/generators/Input/CanonicalDataCaseParser.cs +++ b/generators/Input/CanonicalDataCaseParser.cs @@ -9,27 +9,20 @@ public static class CanonicalDataCaseParser { private const string TokensPath = "$..*[?(@.property)]"; - public static CanonicalDataCase[] Parse(JArray canonicalDataCasesJArray) + public static IReadOnlyCollection Parse(JArray canonicalDataCasesJArray) => canonicalDataCasesJArray .SelectTokens(TokensPath) .Select(Parse) .ToArray(); private static CanonicalDataCase Parse(JToken canonicalDataCaseJToken) - { - var canonicalDataCase = new CanonicalDataCase - { - Property = canonicalDataCaseJToken.Value("property"), - Properties = ToDictionary(canonicalDataCaseJToken), - Input = ToDictionary(canonicalDataCaseJToken["input"]), - Expected = ConvertJToken(canonicalDataCaseJToken["expected"]), - Description = canonicalDataCaseJToken.Value("description"), - DescriptionPath = GetDescriptionPath(canonicalDataCaseJToken) - }; - canonicalDataCase.SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); - - return canonicalDataCase; - } + => new CanonicalDataCase( + property: canonicalDataCaseJToken.Value("property"), + properties: ToReadOnlyDictionary(canonicalDataCaseJToken), + input: ToReadOnlyDictionary(canonicalDataCaseJToken["input"]), + expected: ConvertJToken(canonicalDataCaseJToken["expected"]), + description: canonicalDataCaseJToken.Value("description"), + descriptionPath: GetDescriptionPath(canonicalDataCaseJToken)); private static string[] GetDescriptionPath(JToken canonicalDataCaseToken) { @@ -53,7 +46,7 @@ private static string[] GetDescriptionPath(JToken canonicalDataCaseToken) return descriptionPath.Where(x => !string.IsNullOrEmpty(x)).ToArray(); } - private static IDictionary ToDictionary(JToken jToken) => ConvertJToken(jToken); + private static IReadOnlyDictionary ToReadOnlyDictionary(JToken jToken) => ConvertJToken(jToken); private static dynamic ConvertJToken(JToken jToken) { @@ -64,7 +57,7 @@ private static dynamic ConvertJToken(JToken jToken) case JTokenType.Array: return ConvertJArray((JArray)jToken); case JTokenType.Property: - return jToken.ToObject>(); + return jToken.ToObject>(); case JTokenType.Integer: return ConvertIntegerJToken(jToken); case JTokenType.Float: diff --git a/generators/Input/CanonicalDataParser.cs b/generators/Input/CanonicalDataParser.cs index 206af4ac1f..257bc24b3b 100644 --- a/generators/Input/CanonicalDataParser.cs +++ b/generators/Input/CanonicalDataParser.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json.Linq; +using System.Collections.Generic; +using Newtonsoft.Json.Linq; namespace Generators.Input { @@ -13,20 +14,18 @@ public CanonicalData Parse(string exercise) var canonicalDataJsonContents = _canonicalDataFile.Contents(exercise); var canonicalDataJson = JObject.Parse(canonicalDataJsonContents); - var name = ParseName(canonicalDataJson); + var exerciseName = ParseExerciseName(canonicalDataJson); var version = ParseVersion(canonicalDataJson); var canonicalDataCases = ParseCanonicalDataCases(canonicalDataJson); - foreach (var canonicalDataCase in canonicalDataCases) - canonicalDataCase.Exercise = name; - - return new CanonicalData(name, version, canonicalDataCases); + return new CanonicalData(exerciseName, version, canonicalDataCases); } - private static string ParseName(JToken canonicalDataJObject) => canonicalDataJObject.Value("exercise"); + private static string ParseExerciseName(JToken canonicalDataJObject) => canonicalDataJObject.Value("exercise"); private static string ParseVersion(JToken canonicalDataJObject) => canonicalDataJObject.Value("version"); - private static CanonicalDataCase[] ParseCanonicalDataCases(JObject canonicalDataJObject) => CanonicalDataCaseParser.Parse((JArray)canonicalDataJObject["cases"]); + private static IReadOnlyCollection ParseCanonicalDataCases(JObject canonicalDataJObject) + => CanonicalDataCaseParser.Parse((JArray)canonicalDataJObject["cases"]); } } \ No newline at end of file diff --git a/generators/Input/ConvertHelper.cs b/generators/Input/ConvertHelper.cs index 88e04d1f80..e055b353f5 100644 --- a/generators/Input/ConvertHelper.cs +++ b/generators/Input/ConvertHelper.cs @@ -19,7 +19,6 @@ public static T[] ToArray(this object obj) return arr; return new T[0]; - } } } \ No newline at end of file diff --git a/generators/Input/ConfigFile.cs b/generators/Input/TrackConfigFile.cs similarity index 95% rename from generators/Input/ConfigFile.cs rename to generators/Input/TrackConfigFile.cs index ce3d77158f..e1dbccad92 100644 --- a/generators/Input/ConfigFile.cs +++ b/generators/Input/TrackConfigFile.cs @@ -6,7 +6,7 @@ namespace Generators.Input { - public static class ConfigFile + public static class TrackConfigFile { private const string ConfigFilePath = "../config.json"; diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index 6103e6404d..610f4114c4 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using Generators.Input; namespace Generators.Output { @@ -34,7 +33,7 @@ protected void InitializeTemplateParameters() { ArrangeTemplateParameters = new { Data.Variables }; ActTemplateParameters = new { }; - AssertTemplateParameters = new { Data.ExpectedParameter, Data.TestedValue }; + AssertTemplateParameters = new { ExpectedParameter = Data.ExpectedParameter, TestedValue = Data.TestedValue }; } } } \ No newline at end of file diff --git a/generators/Output/TestMethodBodyData.cs b/generators/Output/TestMethodBodyData.cs index c20d310bed..8c495ad0b5 100644 --- a/generators/Output/TestMethodBodyData.cs +++ b/generators/Output/TestMethodBodyData.cs @@ -11,39 +11,74 @@ public sealed class TestMethodBodyData private const string TestedVariableName = "actual"; private const string ExpectedVariableName = "expected"; - public CanonicalDataCase CanonicalDataCase { get; } - - public TestMethodBodyData(CanonicalDataCase canonicalDataCase) + public TestMethodBodyData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) { - CanonicalDataCase = canonicalDataCase; - - UseVariablesForInput = CanonicalDataCase.UseVariablesForInput; - UseVariablesForConstructorParameters = CanonicalDataCase.UseVariablesForConstructorParameters; - UseVariableForExpected = CanonicalDataCase.UseVariableForExpected; - UseVariableForTested = CanonicalDataCase.UseVariableForTested; + Properties = new Dictionary(canonicalDataCase.Properties); + Input = new Dictionary(canonicalDataCase.Input); + Expected = canonicalDataCase.Expected; + + Exercise = canonicalData.Exercise; + Property = canonicalDataCase.Property; + Description = canonicalDataCase.Description; + DescriptionPath = new List(canonicalDataCase.DescriptionPath); + + SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); } + + public IDictionary Properties { get; set; } + public IDictionary Input { get; set; } + public dynamic Expected { get; set; } + + public string Exercise { get; set; } + public string Property { get; set; } + public string Description { get; set; } + public IList DescriptionPath { get; set; } public bool UseVariablesForInput { get; set; } - public bool UseVariablesForConstructorParameters { get; set; } public bool UseVariableForExpected { get; set; } + public bool UseVariablesForConstructorParameters { get; set; } public bool UseVariableForTested { get; set; } + public bool UseFullDescriptionPath { get; set; } - public string TestedValue => UseVariableForTested ? TestedVariableName : TestedMethodInvocation; - public string InputParameters => UseVariablesForInput ? string.Join(", ", CanonicalDataCase.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); - public string ExpectedParameter => UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(CanonicalDataCase.Expected); - public string ConstructorParameters => UseVariablesForConstructorParameters ? string.Join(", ", CanonicalDataCase.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); + public TestedMethodType TestedMethodType { get; set; } + public Type ExceptionThrown { get; set; } + + public HashSet InputParameters { get; } = new HashSet(); + public HashSet ConstructorInputParameters { get; } = new HashSet(); + + public void SetInputParameters(params string[] properties) + { + InputParameters.Clear(); + InputParameters.UnionWith(properties); + + ConstructorInputParameters.ExceptWith(properties); + } + + public void SetConstructorInputParameters(params string[] properties) + { + ConstructorInputParameters.Clear(); + ConstructorInputParameters.UnionWith(properties); + + InputParameters.ExceptWith(properties); - private string TestedClassName => CanonicalDataCase.Exercise.ToTestedClassName(); - private string TestedMethodName => CanonicalDataCase.Property.ToTestedMethodName(); + TestedMethodType = TestedMethodType.Instance; + } + + public string TestedValue => UseVariableForTested ? TestedVariableName : TestedMethodInvocation; + public string _inputParameters => UseVariablesForInput ? string.Join(", ", InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(_input); + public string ExpectedParameter => UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Expected); + public string _constructorParameters => UseVariablesForConstructorParameters ? string.Join(", ", ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(_constructorInput); - private IDictionary Input => CanonicalDataCase.InputParameters.ToDictionary(key => key, key => CanonicalDataCase.Input[key]); - private IDictionary ConstructorInput => CanonicalDataCase.ConstructorInputParameters.ToDictionary(key => key, key => CanonicalDataCase.Input[key]); - private object Expected => CanonicalDataCase.Expected; + private string TestedClassName => Exercise.ToTestedClassName(); + private string TestedMethodName => Property.ToTestedMethodName(); - private IEnumerable InputVariablesDeclaration => ValueFormatter.FormatVariables(Input); + private IDictionary _input => InputParameters.ToDictionary(key => key, key => Input[key]); + private IDictionary _constructorInput => ConstructorInputParameters.ToDictionary(key => key, key => Input[key]); + + private IEnumerable InputVariablesDeclaration => ValueFormatter.FormatVariables(_input); private IEnumerable ExpectedVariableDeclaration => ValueFormatter.FormatVariable(Expected, ExpectedVariableName); - private IEnumerable ConstructorVariablesDeclaration => ValueFormatter.FormatVariables(ConstructorInput); - private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {TestedClassName}({ConstructorParameters});" }; + private IEnumerable ConstructorVariablesDeclaration => ValueFormatter.FormatVariables(_constructorInput); + private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {TestedClassName}({_constructorParameters});" }; private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; public IEnumerable Variables @@ -58,7 +93,7 @@ public IEnumerable Variables if (UseVariablesForConstructorParameters) lines.AddRange(ConstructorVariablesDeclaration); - if (CanonicalDataCase.TestedMethodType == TestedMethodType.Instance) + if (TestedMethodType == TestedMethodType.Instance) lines.AddRange(SutVariableDeclaration); if (UseVariableForTested) @@ -75,14 +110,14 @@ public string TestedMethodInvocation { get { - switch (CanonicalDataCase.TestedMethodType) + switch (TestedMethodType) { case TestedMethodType.Static: - return $"{TestedClassName}.{TestedMethodName}({InputParameters})"; + return $"{TestedClassName}.{TestedMethodName}({_inputParameters})"; case TestedMethodType.Instance: - return $"{SutVariableName}.{TestedMethodName}({InputParameters})"; + return $"{SutVariableName}.{TestedMethodName}({_inputParameters})"; case TestedMethodType.Extension: - return $"{InputParameters}.{TestedMethodName}()"; + return $"{_inputParameters}.{TestedMethodName}()"; default: throw new ArgumentOutOfRangeException(); } diff --git a/generators/Output/TestMethodBodyWithBooleanCheck.cs b/generators/Output/TestMethodBodyWithBooleanCheck.cs index 334163bcfa..550ba2b782 100644 --- a/generators/Output/TestMethodBodyWithBooleanCheck.cs +++ b/generators/Output/TestMethodBodyWithBooleanCheck.cs @@ -1,5 +1,4 @@ using System; -using Generators.Input; namespace Generators.Output { @@ -8,9 +7,9 @@ public class TestMethodBodyWithBooleanCheck : TestMethodBody public TestMethodBodyWithBooleanCheck(TestMethodBodyData data) : base(data) { AssertTemplateName = "AssertBoolean"; - AssertTemplateParameters = new { BooleanAssertMethod, Data.TestedValue }; + AssertTemplateParameters = new { BooleanAssertMethod, TestedValue = Data.TestedValue }; } - private string BooleanAssertMethod => Convert.ToBoolean(Data.CanonicalDataCase.Expected).ToString(); + private string BooleanAssertMethod => Convert.ToBoolean(Data.Expected).ToString(); } } \ No newline at end of file diff --git a/generators/Output/TestMethodBodyWithEqualityCheck.cs b/generators/Output/TestMethodBodyWithEqualityCheck.cs index b06e44996b..c6bbb157b1 100644 --- a/generators/Output/TestMethodBodyWithEqualityCheck.cs +++ b/generators/Output/TestMethodBodyWithEqualityCheck.cs @@ -1,5 +1,4 @@ using System.Collections; -using Generators.Input; namespace Generators.Output { @@ -11,12 +10,12 @@ public TestMethodBodyWithEqualityCheck(TestMethodBodyData data) : base(data) InitializeTemplateParameters(); AssertTemplateName = ExpectedIsEmptyEnumerable ? "AssertEqual_Empty" : "AssertEqual"; - AssertTemplateParameters = new { Data.ExpectedParameter, Data.TestedValue }; + AssertTemplateParameters = new { ExpectedParameter = Data.ExpectedParameter, TestedValue = Data.TestedValue }; } private bool ExpectedIsEmptyEnumerable => - !(Data.CanonicalDataCase.Expected is string) && - Data.CanonicalDataCase.Expected is IEnumerable enumerable + !(Data.Expected is string) && + Data.Expected is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; } } \ No newline at end of file diff --git a/generators/Output/TestMethodBodyWithExceptionCheck.cs b/generators/Output/TestMethodBodyWithExceptionCheck.cs index 53e7c95746..d23663fb19 100644 --- a/generators/Output/TestMethodBodyWithExceptionCheck.cs +++ b/generators/Output/TestMethodBodyWithExceptionCheck.cs @@ -12,6 +12,6 @@ public TestMethodBodyWithExceptionCheck(TestMethodBodyData data) : base(data) AssertTemplateParameters = new { ExceptionType, Data.TestedValue }; } - private string ExceptionType => Data.CanonicalDataCase.ExceptionThrown.Name; + private string ExceptionType => Data.ExceptionThrown.Name; } } \ No newline at end of file From 55e4ff7a2612a5f5cf4b66e3fa12e3582824fad8 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 21 Jun 2018 07:49:48 +0200 Subject: [PATCH 17/97] generators: Extract rendering logic from test data to test method body --- generators/Exercises/AllYourBase.cs | 2 +- generators/Exercises/Allergies.cs | 2 +- generators/Exercises/Alphametics.cs | 4 +- generators/Exercises/Anagram.cs | 2 +- generators/Exercises/BeerSong.cs | 2 +- generators/Exercises/BinarySearch.cs | 2 +- generators/Exercises/BookStore.cs | 2 +- generators/Exercises/Bowling.cs | 2 +- generators/Exercises/BracketPush.cs | 2 +- generators/Exercises/Change.cs | 2 +- generators/Exercises/CircularBuffer.cs | 2 +- generators/Exercises/Clock.cs | 2 +- generators/Exercises/CollatzConjecture.cs | 2 +- generators/Exercises/ComplexNumbers.cs | 4 +- generators/Exercises/Connect.cs | 2 +- generators/Exercises/CryptoSquare.cs | 2 +- generators/Exercises/CustomSet.cs | 2 +- generators/Exercises/DifferenceOfSquares.cs | 2 +- generators/Exercises/Dominoes.cs | 2 +- generators/Exercises/Etl.cs | 2 +- generators/Exercises/FlattenArray.cs | 2 +- generators/Exercises/FoodChain.cs | 2 +- generators/Exercises/Forth.cs | 2 +- generators/Exercises/Gigasecond.cs | 2 +- generators/Exercises/GoCounting.cs | 2 +- generators/Exercises/Grains.cs | 2 +- generators/Exercises/Grep.cs | 2 +- generators/Exercises/Hamming.cs | 2 +- generators/Exercises/House.cs | 2 +- generators/Exercises/KindergartenGarden.cs | 2 +- generators/Exercises/LargestSeriesProduct.cs | 2 +- generators/Exercises/Leap.cs | 2 +- generators/Exercises/ListOps.cs | 2 +- generators/Exercises/Luhn.cs | 2 +- generators/Exercises/Markdown.cs | 4 +- generators/Exercises/Matrix.cs | 2 +- generators/Exercises/Meetup.cs | 2 +- generators/Exercises/Minesweeper.cs | 2 +- generators/Exercises/NthPrime.cs | 2 +- generators/Exercises/NucleotideCount.cs | 2 +- generators/Exercises/OcrNumbers.cs | 2 +- generators/Exercises/PalindromeProducts.cs | 2 +- generators/Exercises/PascalsTriangle.cs | 2 +- generators/Exercises/PerfectNumbers.cs | 2 +- generators/Exercises/PhoneNumber.cs | 2 +- generators/Exercises/Poker.cs | 2 +- generators/Exercises/Pov.cs | 2 +- generators/Exercises/Proverb.cs | 2 +- generators/Exercises/QueenAttack.cs | 4 +- generators/Exercises/RailFenceCipher.cs | 2 +- generators/Exercises/Rectangles.cs | 2 +- generators/Exercises/RnaTranscription.cs | 2 +- generators/Exercises/RobotSimulator.cs | 2 +- generators/Exercises/RomanNumerals.cs | 2 +- generators/Exercises/RunLengthEncoding.cs | 2 +- generators/Exercises/SaddlePoints.cs | 2 +- generators/Exercises/Say.cs | 2 +- generators/Exercises/ScaleGenerator.cs | 2 +- generators/Exercises/Sieve.cs | 2 +- generators/Exercises/SimpleCipher.cs | 2 +- generators/Exercises/SpaceAge.cs | 2 +- generators/Exercises/SpiralMatrix.cs | 2 +- generators/Exercises/Sublist.cs | 2 +- generators/Exercises/SumOfMultiples.cs | 2 +- generators/Exercises/Tournament.cs | 2 +- generators/Exercises/Transpose.cs | 2 +- generators/Exercises/Triangle.cs | 2 +- generators/Exercises/TwelveDays.cs | 2 +- generators/Exercises/TwoBucket.cs | 4 +- generators/Exercises/TwoFer.cs | 2 +- .../Exercises/VariableLengthQuantity.cs | 2 +- generators/Exercises/WordCount.cs | 2 +- generators/Exercises/WordSearch.cs | 2 +- generators/Exercises/Wordy.cs | 2 +- generators/Exercises/Yacht.cs | 2 +- generators/Exercises/ZebraPuzzle.cs | 2 +- generators/GeneratorExercise.cs | 42 +++--- generators/Output/TestData.cs | 66 +++++++++ generators/Output/TestMethodBody.cs | 71 +++++++++- generators/Output/TestMethodBodyData.cs | 127 ------------------ .../Output/TestMethodBodyWithBooleanCheck.cs | 4 +- .../Output/TestMethodBodyWithEqualityCheck.cs | 4 +- .../TestMethodBodyWithExceptionCheck.cs | 4 +- .../Output/TestMethodBodyWithNullCheck.cs | 4 +- 84 files changed, 243 insertions(+), 241 deletions(-) create mode 100644 generators/Output/TestData.cs delete mode 100644 generators/Output/TestMethodBodyData.cs diff --git a/generators/Exercises/AllYourBase.cs b/generators/Exercises/AllYourBase.cs index 793275c666..042d846031 100644 --- a/generators/Exercises/AllYourBase.cs +++ b/generators/Exercises/AllYourBase.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class AllYourBase : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Input["digits"] = ConvertHelper.ToArray(data.Input["digits"]); data.ExceptionThrown = data.Expected is Dictionary ? typeof(ArgumentException) : null; diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Allergies.cs index 7b202ede6a..3c0bd42a87 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Allergies.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Allergies : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { if (data.Property == "allergicTo") data.Property = "IsAllergicTo"; diff --git a/generators/Exercises/Alphametics.cs b/generators/Exercises/Alphametics.cs index e4a7985803..1c769c85d0 100644 --- a/generators/Exercises/Alphametics.cs +++ b/generators/Exercises/Alphametics.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class Alphametics : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.UseVariableForTested = true; @@ -18,7 +18,7 @@ protected override void UpdateTestMethodBodyData(TestMethodBodyData data) data.Expected = ConvertExpected(data); } - private static dynamic ConvertExpected(TestMethodBodyData canonicalDataCase) + private static dynamic ConvertExpected(TestData canonicalDataCase) { Dictionary expected = canonicalDataCase.Expected; return expected.ToDictionary(kv => kv.Key[0], kv => int.Parse(kv.Value.ToString())); diff --git a/generators/Exercises/Anagram.cs b/generators/Exercises/Anagram.cs index c49f327c92..a711195c59 100644 --- a/generators/Exercises/Anagram.cs +++ b/generators/Exercises/Anagram.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class Anagram : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/BeerSong.cs b/generators/Exercises/BeerSong.cs index d132dd2ed2..b3b5568eaf 100644 --- a/generators/Exercises/BeerSong.cs +++ b/generators/Exercises/BeerSong.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class BeerSong : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.Expected = ConvertHelper.ToMultiLineString(data.Expected); diff --git a/generators/Exercises/BinarySearch.cs b/generators/Exercises/BinarySearch.cs index 862cb1c462..dfb1174c2c 100644 --- a/generators/Exercises/BinarySearch.cs +++ b/generators/Exercises/BinarySearch.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class BinarySearch : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Input["array"] = ConvertHelper.ToArray(data.Input["array"]); data.UseVariablesForConstructorParameters = true; diff --git a/generators/Exercises/BookStore.cs b/generators/Exercises/BookStore.cs index 87d2d50a45..f2ea093db2 100644 --- a/generators/Exercises/BookStore.cs +++ b/generators/Exercises/BookStore.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class BookStore : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Expected = data.Expected / 100.0f; data.Input["basket"] = ConvertHelper.ToArray(data.Input["basket"]); diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index 198f1f945e..83a946e214 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -9,7 +9,7 @@ public class Bowling : GeneratorExercise { private const string PreviousRolls = "previousRolls"; - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { if (!(data.Expected is int)) { diff --git a/generators/Exercises/BracketPush.cs b/generators/Exercises/BracketPush.cs index c8f088d813..a27ca6cd63 100644 --- a/generators/Exercises/BracketPush.cs +++ b/generators/Exercises/BracketPush.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class BracketPush : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Input["value"] = data.Input["value"].Replace("\\", "\\\\"); data.UseVariablesForInput = true; diff --git a/generators/Exercises/Change.cs b/generators/Exercises/Change.cs index 79aa919a39..26ca481738 100644 --- a/generators/Exercises/Change.cs +++ b/generators/Exercises/Change.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Change : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/CircularBuffer.cs index 379806f54b..fdea7feff7 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/CircularBuffer.cs @@ -14,7 +14,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody yield return RenderOperation(operation); } - private static string RenderSut(TestMethodBodyData canonicalDataCase) + private static string RenderSut(TestData canonicalDataCase) { var capacity = canonicalDataCase.Input["capacity"]; return $"var buffer = new CircularBuffer(capacity: {capacity});"; diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Clock.cs index e57109d0b7..fc6121f9e2 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Clock.cs @@ -15,7 +15,7 @@ public class Clock : GeneratorExercise private const string PropertyEquals = "equals"; private const string PropertyToString = "to_string"; - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { if (data.Property != PropertyEqual) { diff --git a/generators/Exercises/CollatzConjecture.cs b/generators/Exercises/CollatzConjecture.cs index 6e56dabf80..78b28fbb16 100644 --- a/generators/Exercises/CollatzConjecture.cs +++ b/generators/Exercises/CollatzConjecture.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class CollatzConjecture : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.ExceptionThrown = data.Input["number"] <= 0 ? typeof(ArgumentException) : null; } diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 4593116325..8de104542c 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -8,7 +8,7 @@ namespace Generators.Exercises { public class ComplexNumbers : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Exercise = "complex-number"; data.UseVariableForExpected = IsComplexNumber(data.Expected); @@ -27,7 +27,7 @@ protected override void UpdateTestMethodBodyData(TestMethodBodyData data) data.Input[key] = ConvertToType(data.Input[key]); } - private static string[] GetInputParameters(TestMethodBodyData canonicalDataCase, string constructorParamName) + private static string[] GetInputParameters(TestData canonicalDataCase, string constructorParamName) => canonicalDataCase.Input.Keys.Where(x => x != constructorParamName).ToArray(); protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/Connect.cs b/generators/Exercises/Connect.cs index fc8a21b5bd..d87ef714c0 100644 --- a/generators/Exercises/Connect.cs +++ b/generators/Exercises/Connect.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Connect : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForConstructorParameters = true; data.SetConstructorInputParameters("board"); diff --git a/generators/Exercises/CryptoSquare.cs b/generators/Exercises/CryptoSquare.cs index 07d545faf7..632d79f52e 100644 --- a/generators/Exercises/CryptoSquare.cs +++ b/generators/Exercises/CryptoSquare.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class CryptoSquare : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/CustomSet.cs b/generators/Exercises/CustomSet.cs index 32cf5b5d0f..ad92318008 100644 --- a/generators/Exercises/CustomSet.cs +++ b/generators/Exercises/CustomSet.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class CustomSet : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; diff --git a/generators/Exercises/DifferenceOfSquares.cs b/generators/Exercises/DifferenceOfSquares.cs index b8513b8639..2b9e266990 100644 --- a/generators/Exercises/DifferenceOfSquares.cs +++ b/generators/Exercises/DifferenceOfSquares.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class DifferenceOfSquares : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { switch (data.Property) { diff --git a/generators/Exercises/Dominoes.cs b/generators/Exercises/Dominoes.cs index bd8e563d9e..56485a1935 100644 --- a/generators/Exercises/Dominoes.cs +++ b/generators/Exercises/Dominoes.cs @@ -8,7 +8,7 @@ namespace Generators.Exercises { public class Dominoes : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.Input["dominoes"] = ConvertInput(data.Input["dominoes"]); diff --git a/generators/Exercises/Etl.cs b/generators/Exercises/Etl.cs index 0024343974..3a0dc9cbf1 100644 --- a/generators/Exercises/Etl.cs +++ b/generators/Exercises/Etl.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class Etl : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/FlattenArray.cs b/generators/Exercises/FlattenArray.cs index f6f1c32d2c..8bbd515585 100644 --- a/generators/Exercises/FlattenArray.cs +++ b/generators/Exercises/FlattenArray.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class FlattenArray : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/FoodChain.cs b/generators/Exercises/FoodChain.cs index 9e1fe7ba43..b2216c7535 100644 --- a/generators/Exercises/FoodChain.cs +++ b/generators/Exercises/FoodChain.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class FoodChain : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Expected = ConvertHelper.ToMultiLineString(data.Expected); data.UseVariableForExpected = true; diff --git a/generators/Exercises/Forth.cs b/generators/Exercises/Forth.cs index 51128fb794..8eea6bc3f1 100644 --- a/generators/Exercises/Forth.cs +++ b/generators/Exercises/Forth.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Forth : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseFullDescriptionPath = true; diff --git a/generators/Exercises/Gigasecond.cs b/generators/Exercises/Gigasecond.cs index ed50429185..54fe3288d9 100644 --- a/generators/Exercises/Gigasecond.cs +++ b/generators/Exercises/Gigasecond.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class Gigasecond : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { var input = DateTime.Parse(data.Input["birthdate"].ToString()); data.Input["birthdate"] = new UnescapedValue(FormatDateTime(input)); diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index 114b23c9ed..c2176997ad 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -10,7 +10,7 @@ namespace Generators.Exercises { public class GoCounting : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/Grains.cs b/generators/Exercises/Grains.cs index 356910127b..ee0455f14a 100644 --- a/generators/Exercises/Grains.cs +++ b/generators/Exercises/Grains.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Grains : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { if (ShouldThrowException(data.Expected)) data.ExceptionThrown = typeof(ArgumentOutOfRangeException); diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index 3ff0377dfc..82bcd1b549 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -8,7 +8,7 @@ namespace Generators.Exercises { public class Grep : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "Match"; data.Input["flags"] = string.Join(" ", data.Input["flags"]); diff --git a/generators/Exercises/Hamming.cs b/generators/Exercises/Hamming.cs index f9b5680966..0c459bebed 100644 --- a/generators/Exercises/Hamming.cs +++ b/generators/Exercises/Hamming.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Hamming : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.ExceptionThrown = data.Expected is int ? null : typeof(ArgumentException); } diff --git a/generators/Exercises/House.cs b/generators/Exercises/House.cs index 1fbc71d22d..a3ffff2b57 100644 --- a/generators/Exercises/House.cs +++ b/generators/Exercises/House.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class House : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.Expected = ConvertHelper.ToMultiLineString(data.Expected); diff --git a/generators/Exercises/KindergartenGarden.cs b/generators/Exercises/KindergartenGarden.cs index 88a6981aa6..df7b806a87 100644 --- a/generators/Exercises/KindergartenGarden.cs +++ b/generators/Exercises/KindergartenGarden.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class KindergartenGarden : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.TestedMethodType = TestedMethodType.Instance; data.UseFullDescriptionPath = true; diff --git a/generators/Exercises/LargestSeriesProduct.cs b/generators/Exercises/LargestSeriesProduct.cs index 13b081cc3a..43caaec4ec 100644 --- a/generators/Exercises/LargestSeriesProduct.cs +++ b/generators/Exercises/LargestSeriesProduct.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class LargestSeriesProduct : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "GetLargestProduct"; diff --git a/generators/Exercises/Leap.cs b/generators/Exercises/Leap.cs index d00488f47b..df377d6ec2 100644 --- a/generators/Exercises/Leap.cs +++ b/generators/Exercises/Leap.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class Leap : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "IsLeapYear"; } diff --git a/generators/Exercises/ListOps.cs b/generators/Exercises/ListOps.cs index 9b06940fd5..45d5386e08 100644 --- a/generators/Exercises/ListOps.cs +++ b/generators/Exercises/ListOps.cs @@ -9,7 +9,7 @@ namespace Generators.Exercises { public class ListOps : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseFullDescriptionPath = true; data.UseVariablesForInput = true; diff --git a/generators/Exercises/Luhn.cs b/generators/Exercises/Luhn.cs index 4b14e7db63..8738b635f0 100644 --- a/generators/Exercises/Luhn.cs +++ b/generators/Exercises/Luhn.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class Luhn : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "IsValid"; } diff --git a/generators/Exercises/Markdown.cs b/generators/Exercises/Markdown.cs index e079dbdfdb..b8a580aecd 100644 --- a/generators/Exercises/Markdown.cs +++ b/generators/Exercises/Markdown.cs @@ -4,13 +4,13 @@ namespace Generators.Exercises { public class Markdown : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; } - protected override TestMethod CreateTestMethod(TestMethodBodyData canonicalDataCase, int index) + protected override TestMethod CreateTestMethod(TestData canonicalDataCase, int index) { var testMethod = base.CreateTestMethod(canonicalDataCase, index); testMethod.Skip = false; diff --git a/generators/Exercises/Matrix.cs b/generators/Exercises/Matrix.cs index 82a3e4cdb8..6eed35a30f 100644 --- a/generators/Exercises/Matrix.cs +++ b/generators/Exercises/Matrix.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class Matrix : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Properties["string"] = data.Properties["input"]["string"]; data.SetConstructorInputParameters("string"); diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 3cbd8de7f3..79be3efc9c 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -14,7 +14,7 @@ public class Meetup : GeneratorExercise private const string PropertyDay = "Day"; - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = PropertyDay; data.UseVariableForExpected = true; diff --git a/generators/Exercises/Minesweeper.cs b/generators/Exercises/Minesweeper.cs index 5c4f71e6e2..5b84f03495 100644 --- a/generators/Exercises/Minesweeper.cs +++ b/generators/Exercises/Minesweeper.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class Minesweeper : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/NthPrime.cs b/generators/Exercises/NthPrime.cs index b14cb44ec0..f4553c39cf 100644 --- a/generators/Exercises/NthPrime.cs +++ b/generators/Exercises/NthPrime.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class NthPrime : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.ExceptionThrown = data.Expected is Dictionary ? typeof(ArgumentOutOfRangeException) : null; } diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index 3c5f3f47d6..045447bc32 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class NucleotideCount : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { if (((Dictionary)data.Expected).ContainsKey("error")) return; diff --git a/generators/Exercises/OcrNumbers.cs b/generators/Exercises/OcrNumbers.cs index e6dbcd8c0a..db7109930a 100644 --- a/generators/Exercises/OcrNumbers.cs +++ b/generators/Exercises/OcrNumbers.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class OcrNumbers : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.ExceptionThrown = data.Expected is int && data.Expected <= 0 ? typeof(ArgumentException) : null; data.Input["rows"] = ToDigitStringRepresentation(data.Input["rows"]); diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/PalindromeProducts.cs index c8c97033db..6557589a10 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/PalindromeProducts.cs @@ -8,7 +8,7 @@ namespace Generators.Exercises { public class PalindromeProducts : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { if (data.Expected.ContainsKey("error")) { diff --git a/generators/Exercises/PascalsTriangle.cs b/generators/Exercises/PascalsTriangle.cs index cc74b572a4..3ba37b9c02 100644 --- a/generators/Exercises/PascalsTriangle.cs +++ b/generators/Exercises/PascalsTriangle.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class PascalsTriangle : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.Property = "calculate"; diff --git a/generators/Exercises/PerfectNumbers.cs b/generators/Exercises/PerfectNumbers.cs index cfc8d93579..c1e438c4a5 100644 --- a/generators/Exercises/PerfectNumbers.cs +++ b/generators/Exercises/PerfectNumbers.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class PerfectNumbers : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { if (data.Expected is string classificationType) data.Expected = new UnescapedValue($"Classification.{classificationType.Transform(To.SentenceCase)}"); diff --git a/generators/Exercises/PhoneNumber.cs b/generators/Exercises/PhoneNumber.cs index 9d6624c844..de49184cb5 100644 --- a/generators/Exercises/PhoneNumber.cs +++ b/generators/Exercises/PhoneNumber.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class PhoneNumber : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.ExceptionThrown = data.Expected is null ? typeof(ArgumentException) : null; diff --git a/generators/Exercises/Poker.cs b/generators/Exercises/Poker.cs index 731b06c42e..941bba5208 100644 --- a/generators/Exercises/Poker.cs +++ b/generators/Exercises/Poker.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class Poker : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/Pov.cs b/generators/Exercises/Pov.cs index 53331013fa..abb0cef7fe 100644 --- a/generators/Exercises/Pov.cs +++ b/generators/Exercises/Pov.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class Pov : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/Proverb.cs b/generators/Exercises/Proverb.cs index add5b77767..f4d5ce1c6b 100644 --- a/generators/Exercises/Proverb.cs +++ b/generators/Exercises/Proverb.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class Proverb : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.Input["strings"] = ConvertHelper.ToArray(data.Input["strings"]); diff --git a/generators/Exercises/QueenAttack.cs b/generators/Exercises/QueenAttack.cs index a2d82bbd82..0c3196798e 100644 --- a/generators/Exercises/QueenAttack.cs +++ b/generators/Exercises/QueenAttack.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class QueenAttack : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { if (data.Property == "create") SetCreatePropertyData(data); @@ -54,7 +54,7 @@ private static Tuple GetCoordinatesFromPosition(dynamic expected) return Tuple.Create(positionX, positionY); } - private static void SetCreatePropertyData(TestMethodBodyData canonicalDataCase) + private static void SetCreatePropertyData(TestData canonicalDataCase) { var validExpected = canonicalDataCase.Expected >= 0; diff --git a/generators/Exercises/RailFenceCipher.cs b/generators/Exercises/RailFenceCipher.cs index 3f3a885d42..47a60dd447 100644 --- a/generators/Exercises/RailFenceCipher.cs +++ b/generators/Exercises/RailFenceCipher.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class RailFenceCipher : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/Rectangles.cs b/generators/Exercises/Rectangles.cs index 295cd33a84..64dcd7d9f3 100644 --- a/generators/Exercises/Rectangles.cs +++ b/generators/Exercises/Rectangles.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class Rectangles : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "count"; data.Input["strings"] = data.Input["strings"] as string[] ?? Array.Empty(); diff --git a/generators/Exercises/RnaTranscription.cs b/generators/Exercises/RnaTranscription.cs index 4038ce54f5..c96664bd1d 100644 --- a/generators/Exercises/RnaTranscription.cs +++ b/generators/Exercises/RnaTranscription.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class RnaTranscription : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.ExceptionThrown = data.Expected is null ? typeof(ArgumentException) : null; } diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index 2c4ae1e5f7..1c1bb1566a 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class RobotSimulator : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { const string direction = "direction"; const string position = "position"; diff --git a/generators/Exercises/RomanNumerals.cs b/generators/Exercises/RomanNumerals.cs index 92b34925f1..c9053877d3 100644 --- a/generators/Exercises/RomanNumerals.cs +++ b/generators/Exercises/RomanNumerals.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class RomanNumerals : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.TestedMethodType = TestedMethodType.Extension; data.Property = "ToRoman"; diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index 0c89ac7e69..c91adb42d5 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class RunLengthEncoding : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Description = $"{data.Property} {data.Description}"; } diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index d1b4312065..f738a83059 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class SaddlePoints : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.TestedMethodType = TestedMethodType.Instance; data.Property = "Calculate"; diff --git a/generators/Exercises/Say.cs b/generators/Exercises/Say.cs index 8135a3e051..e12d5165a4 100644 --- a/generators/Exercises/Say.cs +++ b/generators/Exercises/Say.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Say : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "InEnglish"; data.ExceptionThrown = data.Expected is int ? typeof(ArgumentOutOfRangeException) : null; diff --git a/generators/Exercises/ScaleGenerator.cs b/generators/Exercises/ScaleGenerator.cs index 063ba04d4a..39bcce2fdd 100644 --- a/generators/Exercises/ScaleGenerator.cs +++ b/generators/Exercises/ScaleGenerator.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class ScaleGenerator : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; } diff --git a/generators/Exercises/Sieve.cs b/generators/Exercises/Sieve.cs index e2e34073b9..e8b3dd20ba 100644 --- a/generators/Exercises/Sieve.cs +++ b/generators/Exercises/Sieve.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Sieve : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.ExceptionThrown = data.Input["limit"] < 2 ? typeof(ArgumentOutOfRangeException) : null; diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index de1ec6e96e..dfa1aec284 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class SimpleCipher : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseFullDescriptionPath = true; diff --git a/generators/Exercises/SpaceAge.cs b/generators/Exercises/SpaceAge.cs index b76e08b7c2..f83fe6cc67 100644 --- a/generators/Exercises/SpaceAge.cs +++ b/generators/Exercises/SpaceAge.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class SpaceAge : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = $"On_{data.Input["planet"]}"; data.SetInputParameters(); diff --git a/generators/Exercises/SpiralMatrix.cs b/generators/Exercises/SpiralMatrix.cs index cf12817b27..cdb284bd40 100644 --- a/generators/Exercises/SpiralMatrix.cs +++ b/generators/Exercises/SpiralMatrix.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class SpiralMatrix : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "GetMatrix"; data.UseVariableForExpected = true; diff --git a/generators/Exercises/Sublist.cs b/generators/Exercises/Sublist.cs index ecc12fd731..debee0bc1b 100644 --- a/generators/Exercises/Sublist.cs +++ b/generators/Exercises/Sublist.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class Sublist : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Input["listOne"] = InputValues(data.Input["listOne"] as int[]); data.Input["listTwo"] = InputValues(data.Input["listTwo"] as int[]); diff --git a/generators/Exercises/SumOfMultiples.cs b/generators/Exercises/SumOfMultiples.cs index 00df355129..80323a4dce 100644 --- a/generators/Exercises/SumOfMultiples.cs +++ b/generators/Exercises/SumOfMultiples.cs @@ -7,7 +7,7 @@ namespace Generators.Exercises { public class SumOfMultiples : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Input["factors"] = ConvertHelper.ToArray(data.Input["factors"]); } diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index d4c6689990..b2ae030c8b 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -9,7 +9,7 @@ namespace Generators.Exercises { public class Tournament : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "RunTally"; data.TestedMethodType = TestedMethodType.Static; diff --git a/generators/Exercises/Transpose.cs b/generators/Exercises/Transpose.cs index acc163418b..cdcfea92ba 100644 --- a/generators/Exercises/Transpose.cs +++ b/generators/Exercises/Transpose.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Transpose : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "String"; data.Input["lines"] = ConvertHelper.ToMultiLineString(data.Input["lines"], ""); diff --git a/generators/Exercises/Triangle.cs b/generators/Exercises/Triangle.cs index ccffefb8a4..2d68bfb34b 100644 --- a/generators/Exercises/Triangle.cs +++ b/generators/Exercises/Triangle.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class Triangle : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { if (data.Property == "equilateral") data.Property = "IsEquilateral"; diff --git a/generators/Exercises/TwelveDays.cs b/generators/Exercises/TwelveDays.cs index 7a8c10fb96..7dc0e5ea04 100644 --- a/generators/Exercises/TwelveDays.cs +++ b/generators/Exercises/TwelveDays.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class TwelveDays : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.Expected = ConvertHelper.ToMultiLineString(data.Expected); diff --git a/generators/Exercises/TwoBucket.cs b/generators/Exercises/TwoBucket.cs index e596a6d11a..0f69ef2f2a 100644 --- a/generators/Exercises/TwoBucket.cs +++ b/generators/Exercises/TwoBucket.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class TwoBucket : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.TestedMethodType = TestedMethodType.Instance; data.SetConstructorInputParameters("bucketOne", "bucketTwo", "startBucket"); @@ -20,7 +20,7 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te var templateParameters = new { - MethodInvocation = testMethodBody.Data.TestedMethodInvocation + MethodInvocation = testMethodBody.TestedMethodInvocation }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/TwoFer.cs b/generators/Exercises/TwoFer.cs index 9b5ff1d453..97a120ffcf 100644 --- a/generators/Exercises/TwoFer.cs +++ b/generators/Exercises/TwoFer.cs @@ -4,7 +4,7 @@ namespace Generators.Exercises { public class TwoFer : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Property = "Name"; } diff --git a/generators/Exercises/VariableLengthQuantity.cs b/generators/Exercises/VariableLengthQuantity.cs index 6018b80632..0e0be99906 100644 --- a/generators/Exercises/VariableLengthQuantity.cs +++ b/generators/Exercises/VariableLengthQuantity.cs @@ -8,7 +8,7 @@ namespace Generators.Exercises { public class VariableLengthQuantity : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.UseVariablesForInput = true; diff --git a/generators/Exercises/WordCount.cs b/generators/Exercises/WordCount.cs index 0d3da9d250..d34412063b 100644 --- a/generators/Exercises/WordCount.cs +++ b/generators/Exercises/WordCount.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises { public class WordCount : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.UseVariableForTested = true; diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index 364913c4be..07fb14225f 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -8,7 +8,7 @@ namespace Generators.Exercises { public class WordSearch : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForTested = true; diff --git a/generators/Exercises/Wordy.cs b/generators/Exercises/Wordy.cs index 7efdd80273..778e7223f3 100644 --- a/generators/Exercises/Wordy.cs +++ b/generators/Exercises/Wordy.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Wordy : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.ExceptionThrown = data.Expected is bool ? typeof(ArgumentException) : null; } diff --git a/generators/Exercises/Yacht.cs b/generators/Exercises/Yacht.cs index 449252c4c5..67b01792c1 100644 --- a/generators/Exercises/Yacht.cs +++ b/generators/Exercises/Yacht.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class Yacht : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { data.Exercise = "yacht-game"; var category = data.Input["category"].ToString(); diff --git a/generators/Exercises/ZebraPuzzle.cs b/generators/Exercises/ZebraPuzzle.cs index ba4f620e0b..9a916984f3 100644 --- a/generators/Exercises/ZebraPuzzle.cs +++ b/generators/Exercises/ZebraPuzzle.cs @@ -5,7 +5,7 @@ namespace Generators.Exercises { public class ZebraPuzzle : GeneratorExercise { - protected override void UpdateTestMethodBodyData(TestMethodBodyData data) + protected override void UpdateTestData(TestData data) { var nationality = data.Expected as string; data.Expected = new UnescapedValue($"Nationality.{nationality.Humanize()}"); diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index 51186970e7..4e363a69e0 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -34,11 +34,11 @@ protected virtual IEnumerable RenderTestMethodBodyAssert(TestMethodBody protected virtual IEnumerable RenderAdditionalMethods() => Array.Empty(); - private IEnumerable GetUsingNamespaces(IEnumerable testMethodBodyData) + private IEnumerable GetUsingNamespaces(IEnumerable testData) { var usingNamespaces = new HashSet { "Xunit" }; - foreach (var data in testMethodBodyData.Where(x => x.ExceptionThrown != null)) + foreach (var data in testData.Where(x => x.ExceptionThrown != null)) usingNamespaces.Add(data.ExceptionThrown.Namespace); usingNamespaces.UnionWith(AdditionalNamespaces); @@ -46,45 +46,45 @@ private IEnumerable GetUsingNamespaces(IEnumerable t return usingNamespaces; } - private IEnumerable RenderTestMethods(IEnumerable testMethodBodyData) - => testMethodBodyData - .Select(RenderTestMethod) - .Concat(RenderAdditionalMethods()) - .ToArray(); + private IEnumerable RenderTestMethods(IEnumerable testData) + => testData + .Select(RenderTestMethod) + .Concat(RenderAdditionalMethods()) + .ToArray(); protected virtual TestClass CreateTestClass() { - var testMethodBodyData = _canonicalData.Cases - .Select(canonicalDataCase => CreateTestMethodBodyData(_canonicalData, canonicalDataCase)) + var testData = _canonicalData.Cases + .Select(canonicalDataCase => CreateTestData(_canonicalData, canonicalDataCase)) .ToArray(); - foreach (var data in testMethodBodyData) - UpdateTestMethodBodyData(data); + foreach (var data in testData) + UpdateTestData(data); return new TestClass { ClassName = Name.ToTestClassName(), - Methods = RenderTestMethods(testMethodBodyData), + Methods = RenderTestMethods(testData), CanonicalDataVersion = _canonicalData.Version, - UsingNamespaces = GetUsingNamespaces(testMethodBodyData) + UsingNamespaces = GetUsingNamespaces(testData) }; } - private string RenderTestMethod(TestMethodBodyData data, int index) => CreateTestMethod(data, index).Render(); + private string RenderTestMethod(TestData data, int index) => CreateTestMethod(data, index).Render(); - protected virtual TestMethod CreateTestMethod(TestMethodBodyData data, int index) => new TestMethod + protected virtual TestMethod CreateTestMethod(TestData data, int index) => new TestMethod { Skip = index > 0, Name = ToTestMethodName(data), Body = RenderTestMethodBody(data) }; - private static string ToTestMethodName(TestMethodBodyData data) + private static string ToTestMethodName(TestData data) => data.UseFullDescriptionPath ? string.Join(" - ", data.DescriptionPath).ToTestMethodName() : data.Description.ToTestMethodName(); - private string RenderTestMethodBody(TestMethodBodyData data) + private string RenderTestMethodBody(TestData data) { var testMethodBody = CreateTestMethodBody(data); testMethodBody.Arrange = RenderTestMethodBodyArrange(testMethodBody); @@ -94,14 +94,14 @@ private string RenderTestMethodBody(TestMethodBodyData data) return testMethodBody.Render(); } - protected virtual TestMethodBodyData CreateTestMethodBodyData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) - => new TestMethodBodyData(canonicalData, canonicalDataCase); + protected virtual TestData CreateTestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) + => new TestData(canonicalData, canonicalDataCase); - protected virtual void UpdateTestMethodBodyData(TestMethodBodyData data) + protected virtual void UpdateTestData(TestData data) { } - protected virtual TestMethodBody CreateTestMethodBody(TestMethodBodyData data) + protected virtual TestMethodBody CreateTestMethodBody(TestData data) { if (data.ExceptionThrown != null) { diff --git a/generators/Output/TestData.cs b/generators/Output/TestData.cs new file mode 100644 index 0000000000..713ae75d97 --- /dev/null +++ b/generators/Output/TestData.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Generators.Input; + +namespace Generators.Output +{ + public sealed class TestData + { + public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) + { + Properties = new Dictionary(canonicalDataCase.Properties); + Input = new Dictionary(canonicalDataCase.Input); + Expected = canonicalDataCase.Expected; + + Exercise = canonicalData.Exercise; + Property = canonicalDataCase.Property; + Description = canonicalDataCase.Description; + DescriptionPath = new List(canonicalDataCase.DescriptionPath); + + SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); + } + + public IDictionary Properties { get; set; } + public IDictionary Input { get; set; } + public dynamic Expected { get; set; } + + public string Exercise { get; set; } + public string Property { get; set; } + public string Description { get; set; } + public IList DescriptionPath { get; set; } + + public bool UseVariablesForInput { get; set; } + public bool UseVariableForExpected { get; set; } + public bool UseVariablesForConstructorParameters { get; set; } + public bool UseVariableForTested { get; set; } + public bool UseFullDescriptionPath { get; set; } + + public TestedMethodType TestedMethodType { get; set; } + public Type ExceptionThrown { get; set; } + + public HashSet InputParameters { get; } = new HashSet(); + public HashSet ConstructorInputParameters { get; } = new HashSet(); + + public void SetInputParameters(params string[] properties) + { + InputParameters.Clear(); + InputParameters.UnionWith(properties); + + ConstructorInputParameters.ExceptWith(properties); + } + + public void SetConstructorInputParameters(params string[] properties) + { + ConstructorInputParameters.Clear(); + ConstructorInputParameters.UnionWith(properties); + + InputParameters.ExceptWith(properties); + + TestedMethodType = TestedMethodType.Instance; + } + + public string TestedClassName => Exercise.ToTestedClassName(); + public string TestedMethodName => Property.ToTestedMethodName(); + } +} \ No newline at end of file diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index 610f4114c4..97a1238ea5 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -1,10 +1,16 @@ +using System; using System.Collections.Generic; +using System.Linq; namespace Generators.Output { public abstract class TestMethodBody { - protected TestMethodBody(TestMethodBodyData data) + private const string SutVariableName = "sut"; + private const string TestedVariableName = "actual"; + private const string ExpectedVariableName = "expected"; + + protected TestMethodBody(TestData data) { Data = data; InitializeTemplateParameters(); @@ -12,7 +18,7 @@ protected TestMethodBody(TestMethodBodyData data) public string TemplateName { get; set; } = "TestMethodBody"; - public TestMethodBodyData Data { get; } + public TestData Data { get; } public string ArrangeTemplateName { get; set; } = "Arrange"; public object ArrangeTemplateParameters { get; set; } @@ -31,9 +37,66 @@ protected TestMethodBody(TestMethodBodyData data) protected void InitializeTemplateParameters() { - ArrangeTemplateParameters = new { Data.Variables }; + ArrangeTemplateParameters = new { Variables }; ActTemplateParameters = new { }; - AssertTemplateParameters = new { ExpectedParameter = Data.ExpectedParameter, TestedValue = Data.TestedValue }; + AssertTemplateParameters = new {ExpectedParameter, TestedValue }; + } + + protected string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; + protected string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); + protected string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Data.Expected); + protected string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); + + private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); + private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); + + private IEnumerable InputVariablesDeclaration => ValueFormatter.FormatVariables(Input); + private IEnumerable ExpectedVariableDeclaration => ValueFormatter.FormatVariable(Data.Expected, ExpectedVariableName); + private IEnumerable ConstructorVariablesDeclaration => ValueFormatter.FormatVariables(ConstructorInput); + private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {Data.TestedClassName}({ConstructorParameters});" }; + private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; + + public IEnumerable Variables + { + get + { + var lines = new List(); + + if (Data.UseVariablesForInput) + lines.AddRange(InputVariablesDeclaration); + + if (Data.UseVariablesForConstructorParameters) + lines.AddRange(ConstructorVariablesDeclaration); + + if (Data.TestedMethodType == TestedMethodType.Instance) + lines.AddRange(SutVariableDeclaration); + + if (Data.UseVariableForTested) + lines.AddRange(ActualVariableDeclaration); + + if (Data.UseVariableForExpected) + lines.AddRange(ExpectedVariableDeclaration); + + return lines; + } + } + + public string TestedMethodInvocation + { + get + { + switch (Data.TestedMethodType) + { + case TestedMethodType.Static: + return $"{Data.TestedClassName}.{Data.TestedMethodName}({InputParameters})"; + case TestedMethodType.Instance: + return $"{SutVariableName}.{Data.TestedMethodName}({InputParameters})"; + case TestedMethodType.Extension: + return $"{InputParameters}.{Data.TestedMethodName}()"; + default: + throw new ArgumentOutOfRangeException(); + } + } } } } \ No newline at end of file diff --git a/generators/Output/TestMethodBodyData.cs b/generators/Output/TestMethodBodyData.cs deleted file mode 100644 index 8c495ad0b5..0000000000 --- a/generators/Output/TestMethodBodyData.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Generators.Input; - -namespace Generators.Output -{ - public sealed class TestMethodBodyData - { - private const string SutVariableName = "sut"; - private const string TestedVariableName = "actual"; - private const string ExpectedVariableName = "expected"; - - public TestMethodBodyData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) - { - Properties = new Dictionary(canonicalDataCase.Properties); - Input = new Dictionary(canonicalDataCase.Input); - Expected = canonicalDataCase.Expected; - - Exercise = canonicalData.Exercise; - Property = canonicalDataCase.Property; - Description = canonicalDataCase.Description; - DescriptionPath = new List(canonicalDataCase.DescriptionPath); - - SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); - } - - public IDictionary Properties { get; set; } - public IDictionary Input { get; set; } - public dynamic Expected { get; set; } - - public string Exercise { get; set; } - public string Property { get; set; } - public string Description { get; set; } - public IList DescriptionPath { get; set; } - - public bool UseVariablesForInput { get; set; } - public bool UseVariableForExpected { get; set; } - public bool UseVariablesForConstructorParameters { get; set; } - public bool UseVariableForTested { get; set; } - public bool UseFullDescriptionPath { get; set; } - - public TestedMethodType TestedMethodType { get; set; } - public Type ExceptionThrown { get; set; } - - public HashSet InputParameters { get; } = new HashSet(); - public HashSet ConstructorInputParameters { get; } = new HashSet(); - - public void SetInputParameters(params string[] properties) - { - InputParameters.Clear(); - InputParameters.UnionWith(properties); - - ConstructorInputParameters.ExceptWith(properties); - } - - public void SetConstructorInputParameters(params string[] properties) - { - ConstructorInputParameters.Clear(); - ConstructorInputParameters.UnionWith(properties); - - InputParameters.ExceptWith(properties); - - TestedMethodType = TestedMethodType.Instance; - } - - public string TestedValue => UseVariableForTested ? TestedVariableName : TestedMethodInvocation; - public string _inputParameters => UseVariablesForInput ? string.Join(", ", InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(_input); - public string ExpectedParameter => UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Expected); - public string _constructorParameters => UseVariablesForConstructorParameters ? string.Join(", ", ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(_constructorInput); - - private string TestedClassName => Exercise.ToTestedClassName(); - private string TestedMethodName => Property.ToTestedMethodName(); - - private IDictionary _input => InputParameters.ToDictionary(key => key, key => Input[key]); - private IDictionary _constructorInput => ConstructorInputParameters.ToDictionary(key => key, key => Input[key]); - - private IEnumerable InputVariablesDeclaration => ValueFormatter.FormatVariables(_input); - private IEnumerable ExpectedVariableDeclaration => ValueFormatter.FormatVariable(Expected, ExpectedVariableName); - private IEnumerable ConstructorVariablesDeclaration => ValueFormatter.FormatVariables(_constructorInput); - private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {TestedClassName}({_constructorParameters});" }; - private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; - - public IEnumerable Variables - { - get - { - var lines = new List(); - - if (UseVariablesForInput) - lines.AddRange(InputVariablesDeclaration); - - if (UseVariablesForConstructorParameters) - lines.AddRange(ConstructorVariablesDeclaration); - - if (TestedMethodType == TestedMethodType.Instance) - lines.AddRange(SutVariableDeclaration); - - if (UseVariableForTested) - lines.AddRange(ActualVariableDeclaration); - - if (UseVariableForExpected) - lines.AddRange(ExpectedVariableDeclaration); - - return lines; - } - } - - public string TestedMethodInvocation - { - get - { - switch (TestedMethodType) - { - case TestedMethodType.Static: - return $"{TestedClassName}.{TestedMethodName}({_inputParameters})"; - case TestedMethodType.Instance: - return $"{SutVariableName}.{TestedMethodName}({_inputParameters})"; - case TestedMethodType.Extension: - return $"{_inputParameters}.{TestedMethodName}()"; - default: - throw new ArgumentOutOfRangeException(); - } - } - } - } -} \ No newline at end of file diff --git a/generators/Output/TestMethodBodyWithBooleanCheck.cs b/generators/Output/TestMethodBodyWithBooleanCheck.cs index 550ba2b782..c1f72a424a 100644 --- a/generators/Output/TestMethodBodyWithBooleanCheck.cs +++ b/generators/Output/TestMethodBodyWithBooleanCheck.cs @@ -4,10 +4,10 @@ namespace Generators.Output { public class TestMethodBodyWithBooleanCheck : TestMethodBody { - public TestMethodBodyWithBooleanCheck(TestMethodBodyData data) : base(data) + public TestMethodBodyWithBooleanCheck(TestData data) : base(data) { AssertTemplateName = "AssertBoolean"; - AssertTemplateParameters = new { BooleanAssertMethod, TestedValue = Data.TestedValue }; + AssertTemplateParameters = new { BooleanAssertMethod, TestedValue }; } private string BooleanAssertMethod => Convert.ToBoolean(Data.Expected).ToString(); diff --git a/generators/Output/TestMethodBodyWithEqualityCheck.cs b/generators/Output/TestMethodBodyWithEqualityCheck.cs index c6bbb157b1..57350dc6f1 100644 --- a/generators/Output/TestMethodBodyWithEqualityCheck.cs +++ b/generators/Output/TestMethodBodyWithEqualityCheck.cs @@ -4,13 +4,13 @@ namespace Generators.Output { public class TestMethodBodyWithEqualityCheck : TestMethodBody { - public TestMethodBodyWithEqualityCheck(TestMethodBodyData data) : base(data) + public TestMethodBodyWithEqualityCheck(TestData data) : base(data) { Data.UseVariableForExpected = Data.UseVariableForExpected && !ExpectedIsEmptyEnumerable; InitializeTemplateParameters(); AssertTemplateName = ExpectedIsEmptyEnumerable ? "AssertEqual_Empty" : "AssertEqual"; - AssertTemplateParameters = new { ExpectedParameter = Data.ExpectedParameter, TestedValue = Data.TestedValue }; + AssertTemplateParameters = new { ExpectedParameter, TestedValue }; } private bool ExpectedIsEmptyEnumerable => diff --git a/generators/Output/TestMethodBodyWithExceptionCheck.cs b/generators/Output/TestMethodBodyWithExceptionCheck.cs index d23663fb19..bfb5b3022b 100644 --- a/generators/Output/TestMethodBodyWithExceptionCheck.cs +++ b/generators/Output/TestMethodBodyWithExceptionCheck.cs @@ -2,14 +2,14 @@ { public class TestMethodBodyWithExceptionCheck : TestMethodBody { - public TestMethodBodyWithExceptionCheck(TestMethodBodyData data) : base(data) + public TestMethodBodyWithExceptionCheck(TestData data) : base(data) { Data.UseVariableForExpected = false; Data.UseVariableForTested = false; InitializeTemplateParameters(); AssertTemplateName = "AssertThrowsException"; - AssertTemplateParameters = new { ExceptionType, Data.TestedValue }; + AssertTemplateParameters = new { ExceptionType, TestedValue }; } private string ExceptionType => Data.ExceptionThrown.Name; diff --git a/generators/Output/TestMethodBodyWithNullCheck.cs b/generators/Output/TestMethodBodyWithNullCheck.cs index 1cc1a2cc95..d4e854ae4e 100644 --- a/generators/Output/TestMethodBodyWithNullCheck.cs +++ b/generators/Output/TestMethodBodyWithNullCheck.cs @@ -2,10 +2,10 @@ { public class TestMethodBodyWithNullCheck : TestMethodBody { - public TestMethodBodyWithNullCheck(TestMethodBodyData data) : base(data) + public TestMethodBodyWithNullCheck(TestData data) : base(data) { AssertTemplateName = "AssertNull"; - AssertTemplateParameters = new { Data.TestedValue }; + AssertTemplateParameters = new { TestedValue }; } } } \ No newline at end of file From bbc999b73e016fdc7d242b10a68bae25ae4be59c Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 22 Jun 2018 22:09:15 +0200 Subject: [PATCH 18/97] generators: Replace Exercise and Property with TestedClass and TestedMethod --- generators/Exercises/Allergies.cs | 4 ++-- generators/Exercises/Clock.cs | 10 ++++------ generators/Exercises/ComplexNumbers.cs | 2 +- generators/Exercises/Connect.cs | 2 +- generators/Exercises/CustomSet.cs | 2 +- generators/Exercises/DifferenceOfSquares.cs | 6 +++--- generators/Exercises/Grep.cs | 2 +- generators/Exercises/LargestSeriesProduct.cs | 2 +- generators/Exercises/Leap.cs | 2 +- generators/Exercises/Luhn.cs | 2 +- generators/Exercises/Meetup.cs | 2 +- generators/Exercises/PascalsTriangle.cs | 2 +- generators/Exercises/Rectangles.cs | 2 +- generators/Exercises/RomanNumerals.cs | 2 +- generators/Exercises/RunLengthEncoding.cs | 6 +++--- generators/Exercises/SaddlePoints.cs | 2 +- generators/Exercises/Say.cs | 2 +- generators/Exercises/SpaceAge.cs | 2 +- generators/Exercises/SpiralMatrix.cs | 2 +- generators/Exercises/Sublist.cs | 2 +- generators/Exercises/Tournament.cs | 2 +- generators/Exercises/Transpose.cs | 2 +- generators/Exercises/Triangle.cs | 6 +++--- generators/Exercises/TwoFer.cs | 2 +- generators/Exercises/Yacht.cs | 2 +- generators/Output/TestData.cs | 16 ++++++++++------ generators/Output/TestMethodBody.cs | 8 ++++---- 27 files changed, 49 insertions(+), 47 deletions(-) diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Allergies.cs index 3c0bd42a87..8b9cd6fc8b 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Allergies.cs @@ -8,7 +8,7 @@ public class Allergies : GeneratorExercise protected override void UpdateTestData(TestData data) { if (data.Property == "allergicTo") - data.Property = "IsAllergicTo"; + data.TestedMethod = "IsAllergicTo"; else if (data.Property == "list") data.UseVariableForExpected = true; @@ -17,7 +17,7 @@ protected override void UpdateTestData(TestData data) protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - return testMethodBody.Data.Property == "IsAllergicTo" + return testMethodBody.Data.Property == "allergicTo" ? RenderIsAllergicToAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Clock.cs index fc6121f9e2..72e6807d80 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Clock.cs @@ -12,8 +12,6 @@ public class Clock : GeneratorExercise private const string PropertyCreate = "create"; private const string PropertyEqual = "equal"; - private const string PropertyEquals = "equals"; - private const string PropertyToString = "to_string"; protected override void UpdateTestData(TestData data) { @@ -31,22 +29,22 @@ protected override void UpdateTestData(TestData data) if (data.Property == PropertyCreate) { - data.Property = PropertyToString; + data.TestedMethod = "ToString"; } else if (data.Property == PropertyEqual) { - data.Property = PropertyEquals; + data.TestedMethod = "Equals"; } } protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - if (testMethodBody.Data.Property == PropertyEquals) + if (testMethodBody.Data.Property == PropertyEqual) { return RenderEqualToAssert(testMethodBody); } - return testMethodBody.Data.Property != PropertyToString + return testMethodBody.Data.Property != PropertyCreate ? RenderConsistencyToAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 8de104542c..8f6dbb7fec 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -10,7 +10,7 @@ public class ComplexNumbers : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Exercise = "complex-number"; + data.TestedClass = "ComplexNumber"; data.UseVariableForExpected = IsComplexNumber(data.Expected); data.Expected = ConvertToType(data.Expected); diff --git a/generators/Exercises/Connect.cs b/generators/Exercises/Connect.cs index d87ef714c0..8c62c7d12d 100644 --- a/generators/Exercises/Connect.cs +++ b/generators/Exercises/Connect.cs @@ -9,7 +9,7 @@ protected override void UpdateTestData(TestData data) { data.UseVariablesForConstructorParameters = true; data.SetConstructorInputParameters("board"); - data.Property = "result"; + data.TestedMethod = "Result"; data.Input["board"] = ToMultiLineString(data.Input["board"]); switch (data.Expected) diff --git a/generators/Exercises/CustomSet.cs b/generators/Exercises/CustomSet.cs index ad92318008..45aed2db07 100644 --- a/generators/Exercises/CustomSet.cs +++ b/generators/Exercises/CustomSet.cs @@ -29,7 +29,7 @@ protected override void UpdateTestData(TestData data) if (data.Property == "equal") { - data.Property = "Equals"; + data.TestedMethod = "Equals"; } } diff --git a/generators/Exercises/DifferenceOfSquares.cs b/generators/Exercises/DifferenceOfSquares.cs index 2b9e266990..6e6eb9cc89 100644 --- a/generators/Exercises/DifferenceOfSquares.cs +++ b/generators/Exercises/DifferenceOfSquares.cs @@ -9,13 +9,13 @@ protected override void UpdateTestData(TestData data) switch (data.Property) { case "squareOfSum": - data.Property = "CalculateSquareOfSum"; + data.TestedMethod = "CalculateSquareOfSum"; break; case "sumOfSquares": - data.Property = "CalculateSumOfSquares"; + data.TestedMethod = "CalculateSumOfSquares"; break; case "differenceOfSquares": - data.Property = "CalculateDifferenceOfSquares"; + data.TestedMethod = "CalculateDifferenceOfSquares"; break; } } diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index 82bcd1b549..cd00e60e69 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -10,7 +10,7 @@ public class Grep : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "Match"; + data.TestedMethod = "Match"; data.Input["flags"] = string.Join(" ", data.Input["flags"]); data.Expected = ConvertExpected(data.Expected); data.UseVariablesForInput = true; diff --git a/generators/Exercises/LargestSeriesProduct.cs b/generators/Exercises/LargestSeriesProduct.cs index 43caaec4ec..c4edfcfe0c 100644 --- a/generators/Exercises/LargestSeriesProduct.cs +++ b/generators/Exercises/LargestSeriesProduct.cs @@ -7,7 +7,7 @@ public class LargestSeriesProduct : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "GetLargestProduct"; + data.TestedMethod = "GetLargestProduct"; var caseInputLessThanZero = (long)data.Expected == -1; data.ExceptionThrown = caseInputLessThanZero ? typeof(ArgumentException) : null; diff --git a/generators/Exercises/Leap.cs b/generators/Exercises/Leap.cs index df377d6ec2..3ce0e329a0 100644 --- a/generators/Exercises/Leap.cs +++ b/generators/Exercises/Leap.cs @@ -6,7 +6,7 @@ public class Leap : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "IsLeapYear"; + data.TestedMethod = "IsLeapYear"; } } } \ No newline at end of file diff --git a/generators/Exercises/Luhn.cs b/generators/Exercises/Luhn.cs index 8738b635f0..ff0fb1f419 100644 --- a/generators/Exercises/Luhn.cs +++ b/generators/Exercises/Luhn.cs @@ -6,7 +6,7 @@ public class Luhn : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "IsValid"; + data.TestedMethod = "IsValid"; } } } diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 79be3efc9c..410c08b732 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -16,7 +16,7 @@ public class Meetup : GeneratorExercise protected override void UpdateTestData(TestData data) { - data.Property = PropertyDay; + data.TestedMethod = PropertyDay; data.UseVariableForExpected = true; data.SetConstructorInputParameters(ParamMonth, ParamYear); data.SetInputParameters(ParamDayOfWeek, ParamWeek); diff --git a/generators/Exercises/PascalsTriangle.cs b/generators/Exercises/PascalsTriangle.cs index 3ba37b9c02..1cbd05d546 100644 --- a/generators/Exercises/PascalsTriangle.cs +++ b/generators/Exercises/PascalsTriangle.cs @@ -9,7 +9,7 @@ public class PascalsTriangle : GeneratorExercise protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; - data.Property = "calculate"; + data.TestedMethod = "Calculate"; if (data.Expected is JArray jArray) data.Expected = jArray.ToObject(); else diff --git a/generators/Exercises/Rectangles.cs b/generators/Exercises/Rectangles.cs index 64dcd7d9f3..db17ba8aa2 100644 --- a/generators/Exercises/Rectangles.cs +++ b/generators/Exercises/Rectangles.cs @@ -8,7 +8,7 @@ public class Rectangles : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "count"; + data.TestedMethod = "Count"; data.Input["strings"] = data.Input["strings"] as string[] ?? Array.Empty(); data.UseVariablesForInput = true; } diff --git a/generators/Exercises/RomanNumerals.cs b/generators/Exercises/RomanNumerals.cs index c9053877d3..1f31b91c2c 100644 --- a/generators/Exercises/RomanNumerals.cs +++ b/generators/Exercises/RomanNumerals.cs @@ -7,7 +7,7 @@ public class RomanNumerals : GeneratorExercise protected override void UpdateTestData(TestData data) { data.TestedMethodType = TestedMethodType.Extension; - data.Property = "ToRoman"; + data.TestedMethod = "ToRoman"; } } } \ No newline at end of file diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index c91adb42d5..719627545b 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -19,12 +19,12 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) { - const string template = @"Assert.Equal(""{{ExpectedOutput}}"", {{ExerciseName}}.Decode({{ExerciseName}}.Encode(""{{ExpectedOutput}}"")));"; + const string template = @"Assert.Equal(""{{Expected}}"", {{TestedClassName}}.Decode({{TestedClassName}}.Encode(""{{Expected}}"")));"; var templateParameters = new { - ExpectedOutput = testMethodBody.Data.Expected, - ExerciseName = testMethodBody.Data.Exercise.ToTestedClassName() + testMethodBody.Data.Expected, + TestedClassName = testMethodBody.Data.TestedClass }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index f738a83059..c01b4c2ca6 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -10,7 +10,7 @@ public class SaddlePoints : GeneratorExercise protected override void UpdateTestData(TestData data) { data.TestedMethodType = TestedMethodType.Instance; - data.Property = "Calculate"; + data.TestedMethod = "Calculate"; data.SetConstructorInputParameters("matrix"); data.UseVariablesForConstructorParameters = true; data.UseVariablesForInput = true; diff --git a/generators/Exercises/Say.cs b/generators/Exercises/Say.cs index e12d5165a4..90e8b350c1 100644 --- a/generators/Exercises/Say.cs +++ b/generators/Exercises/Say.cs @@ -7,7 +7,7 @@ public class Say : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "InEnglish"; + data.TestedMethod = "InEnglish"; data.ExceptionThrown = data.Expected is int ? typeof(ArgumentOutOfRangeException) : null; } } diff --git a/generators/Exercises/SpaceAge.cs b/generators/Exercises/SpaceAge.cs index f83fe6cc67..93996569a0 100644 --- a/generators/Exercises/SpaceAge.cs +++ b/generators/Exercises/SpaceAge.cs @@ -6,7 +6,7 @@ public class SpaceAge : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = $"On_{data.Input["planet"]}"; + data.TestedMethod = $"On{data.Input["planet"]}"; data.SetInputParameters(); data.SetConstructorInputParameters("seconds"); } diff --git a/generators/Exercises/SpiralMatrix.cs b/generators/Exercises/SpiralMatrix.cs index cdb284bd40..a8031e891d 100644 --- a/generators/Exercises/SpiralMatrix.cs +++ b/generators/Exercises/SpiralMatrix.cs @@ -8,7 +8,7 @@ public class SpiralMatrix : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "GetMatrix"; + data.TestedMethod = "GetMatrix"; data.UseVariableForExpected = true; data.Expected = ConvertExpected(data.Expected); } diff --git a/generators/Exercises/Sublist.cs b/generators/Exercises/Sublist.cs index debee0bc1b..015238772a 100644 --- a/generators/Exercises/Sublist.cs +++ b/generators/Exercises/Sublist.cs @@ -12,7 +12,7 @@ protected override void UpdateTestData(TestData data) data.Input["listOne"] = InputValues(data.Input["listOne"] as int[]); data.Input["listTwo"] = InputValues(data.Input["listTwo"] as int[]); - data.Property = "classify"; + data.TestedMethod = "Classify"; data.Expected = new UnescapedValue($"SublistType.{(data.Expected as string).Dehumanize()}"); } diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index b2ae030c8b..aea015b6ee 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -11,7 +11,7 @@ public class Tournament : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "RunTally"; + data.TestedMethod = "RunTally"; data.TestedMethodType = TestedMethodType.Static; data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/Transpose.cs b/generators/Exercises/Transpose.cs index cdcfea92ba..ddef564d29 100644 --- a/generators/Exercises/Transpose.cs +++ b/generators/Exercises/Transpose.cs @@ -7,7 +7,7 @@ public class Transpose : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "String"; + data.TestedMethod = "String"; data.Input["lines"] = ConvertHelper.ToMultiLineString(data.Input["lines"], ""); data.Expected = ConvertHelper.ToMultiLineString(data.Expected, ""); diff --git a/generators/Exercises/Triangle.cs b/generators/Exercises/Triangle.cs index 2d68bfb34b..65996608f9 100644 --- a/generators/Exercises/Triangle.cs +++ b/generators/Exercises/Triangle.cs @@ -7,11 +7,11 @@ public class Triangle : GeneratorExercise protected override void UpdateTestData(TestData data) { if (data.Property == "equilateral") - data.Property = "IsEquilateral"; + data.TestedMethod = "IsEquilateral"; else if (data.Property == "isosceles") - data.Property = "IsIsosceles"; + data.TestedMethod = "IsIsosceles"; else if (data.Property == "scalene") - data.Property = "IsScalene"; + data.TestedMethod = "IsScalene"; data.Input["x"] = data.Input["sides"][0]; data.Input["y"] = data.Input["sides"][1]; diff --git a/generators/Exercises/TwoFer.cs b/generators/Exercises/TwoFer.cs index 97a120ffcf..6c7d2a472e 100644 --- a/generators/Exercises/TwoFer.cs +++ b/generators/Exercises/TwoFer.cs @@ -6,7 +6,7 @@ public class TwoFer : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Property = "Name"; + data.TestedMethod = "Name"; } } } \ No newline at end of file diff --git a/generators/Exercises/Yacht.cs b/generators/Exercises/Yacht.cs index 67b01792c1..80bfc8f15a 100644 --- a/generators/Exercises/Yacht.cs +++ b/generators/Exercises/Yacht.cs @@ -7,7 +7,7 @@ public class Yacht : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Exercise = "yacht-game"; + data.TestedClass = "YachtGame"; var category = data.Input["category"].ToString(); var formattedCategory = StringDehumanizeExtensions.Dehumanize(category); data.Input["category"] = new UnescapedValue($"YachtCategory.{formattedCategory}"); diff --git a/generators/Output/TestData.cs b/generators/Output/TestData.cs index 713ae75d97..96d390b559 100644 --- a/generators/Output/TestData.cs +++ b/generators/Output/TestData.cs @@ -15,18 +15,23 @@ public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase Exercise = canonicalData.Exercise; Property = canonicalDataCase.Property; + Description = canonicalDataCase.Description; DescriptionPath = new List(canonicalDataCase.DescriptionPath); SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); + + TestedClass = canonicalData.Exercise.ToTestedClassName(); + TestedMethod = canonicalDataCase.Property.ToTestedMethodName(); } + public string Exercise { get; } + public string Property { get; } + public IDictionary Properties { get; set; } public IDictionary Input { get; set; } public dynamic Expected { get; set; } - - public string Exercise { get; set; } - public string Property { get; set; } + public string Description { get; set; } public IList DescriptionPath { get; set; } @@ -36,6 +41,8 @@ public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase public bool UseVariableForTested { get; set; } public bool UseFullDescriptionPath { get; set; } + public string TestedClass { get; set; } + public string TestedMethod { get; set; } public TestedMethodType TestedMethodType { get; set; } public Type ExceptionThrown { get; set; } @@ -59,8 +66,5 @@ public void SetConstructorInputParameters(params string[] properties) TestedMethodType = TestedMethodType.Instance; } - - public string TestedClassName => Exercise.ToTestedClassName(); - public string TestedMethodName => Property.ToTestedMethodName(); } } \ No newline at end of file diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index 97a1238ea5..6bcbed2f59 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -53,7 +53,7 @@ protected void InitializeTemplateParameters() private IEnumerable InputVariablesDeclaration => ValueFormatter.FormatVariables(Input); private IEnumerable ExpectedVariableDeclaration => ValueFormatter.FormatVariable(Data.Expected, ExpectedVariableName); private IEnumerable ConstructorVariablesDeclaration => ValueFormatter.FormatVariables(ConstructorInput); - private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {Data.TestedClassName}({ConstructorParameters});" }; + private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {Data.TestedClass}({ConstructorParameters});" }; private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; public IEnumerable Variables @@ -88,11 +88,11 @@ public string TestedMethodInvocation switch (Data.TestedMethodType) { case TestedMethodType.Static: - return $"{Data.TestedClassName}.{Data.TestedMethodName}({InputParameters})"; + return $"{Data.TestedClass}.{Data.TestedMethod}({InputParameters})"; case TestedMethodType.Instance: - return $"{SutVariableName}.{Data.TestedMethodName}({InputParameters})"; + return $"{SutVariableName}.{Data.TestedMethod}({InputParameters})"; case TestedMethodType.Extension: - return $"{InputParameters}.{Data.TestedMethodName}()"; + return $"{InputParameters}.{Data.TestedMethod}()"; default: throw new ArgumentOutOfRangeException(); } From 998873c3e3a45825bdd29aadd478d73aa34df377 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 23 Jun 2018 10:07:19 +0200 Subject: [PATCH 19/97] generators: Update package versions --- generators/Generators.csproj | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/generators/Generators.csproj b/generators/Generators.csproj index 30898a188f..94eadd94a9 100644 --- a/generators/Generators.csproj +++ b/generators/Generators.csproj @@ -4,12 +4,12 @@ netcoreapp2.0 - - - + + + - - + + From ea4586b5a00e077f3b39638ccc04bd84821e1dba Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 23 Jun 2018 10:36:24 +0200 Subject: [PATCH 20/97] generators: Don't use sealed --- generators/DeprecatedExercise.cs | 2 +- generators/ExerciseCollection.cs | 15 +++++++-------- generators/Exercises/Bowling.cs | 4 ++-- generators/Exercises/ComplexNumbers.cs | 8 ++++---- generators/Exercises/Connect.cs | 2 +- generators/Exercises/Wordy.cs | 2 +- generators/Exercises/Yacht.cs | 2 +- generators/Input/CanonicalData.cs | 2 +- generators/Input/CanonicalDataCase.cs | 2 +- generators/Input/CanonicalDataFile.cs | 11 ++++------- generators/Input/CanonicalDataParser.cs | 2 +- generators/Input/TrackConfigFile.cs | 5 ++--- generators/MissingDataExercise.cs | 2 +- generators/Options.cs | 2 +- generators/Output/TestClass.cs | 4 ++-- generators/Output/TestData.cs | 14 +++++++------- .../Output/TestMethodBodyWithEqualityCheck.cs | 4 ++-- .../Output/TestMethodBodyWithExceptionCheck.cs | 2 +- generators/Program.cs | 9 ++++----- generators/UnimplementedExercise.cs | 2 +- 20 files changed, 45 insertions(+), 51 deletions(-) diff --git a/generators/DeprecatedExercise.cs b/generators/DeprecatedExercise.cs index 680dfde465..eb4e1d7219 100644 --- a/generators/DeprecatedExercise.cs +++ b/generators/DeprecatedExercise.cs @@ -1,6 +1,6 @@ namespace Generators { - public sealed class DeprecatedExercise : Exercise + public class DeprecatedExercise : Exercise { public DeprecatedExercise(string name) => Name = name; diff --git a/generators/ExerciseCollection.cs b/generators/ExerciseCollection.cs index bdad8640f5..fd56bd3e62 100644 --- a/generators/ExerciseCollection.cs +++ b/generators/ExerciseCollection.cs @@ -14,14 +14,15 @@ public class ExerciseCollection : IEnumerable private readonly Dictionary _exerciseTypesByName; public ExerciseCollection(CanonicalDataFile canonicalDataFile) - { - _canonicalDataFile = canonicalDataFile; + => (_canonicalDataFile, _exerciseTypesByName) = (canonicalDataFile, GetExerciseTypesByName()); - _exerciseTypesByName = Assembly.GetEntryAssembly() + private static Dictionary GetExerciseTypesByName() + => Assembly.GetEntryAssembly() .GetTypes() .Where(IsConcreteGenerator) .ToDictionary(type => type.ToExerciseName(), StringComparer.OrdinalIgnoreCase); - } + + private static bool IsConcreteGenerator(Type type) => typeof(Exercise).IsAssignableFrom(type); public IEnumerator GetEnumerator() => GetExercises().GetEnumerator(); @@ -31,7 +32,7 @@ private IEnumerable GetExercises() { foreach (var exercise in TrackConfigFile.GetExercises()) { - var exerciseName = exercise.Name; + var exerciseName = exercise.Slug.ToExerciseName(); if (exercise.Deprecated) yield return new DeprecatedExercise(exerciseName); else if (HasNoCanonicalData(exerciseName)) @@ -47,9 +48,7 @@ private IEnumerable GetExercises() private bool IsNotImplemented(string exerciseName) => !_exerciseTypesByName.ContainsKey(exerciseName.ToExerciseName()); - private Exercise CreateExercise(string exerciseName) + private Exercise CreateExercise(string exerciseName) => (Exercise)Activator.CreateInstance(_exerciseTypesByName[exerciseName.ToExerciseName()]); - - private static bool IsConcreteGenerator(Type type) => typeof(Exercise).IsAssignableFrom(type); } } \ No newline at end of file diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index 83a946e214..a93df3ed08 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -69,7 +69,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) { var template = -@"DoRoll(previousRolls, sut); + @"DoRoll(previousRolls, sut); "; if (testMethodBody.Data.ExceptionThrown != null) @@ -80,7 +80,7 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te if (testMethodBody.Data.Input.ContainsKey("roll")) { template += -@"sut.Roll({{RolVal}}); + @"sut.Roll({{RolVal}}); var actual = sut.Score(); "; var templateParameters = new diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 8f6dbb7fec..83384ffd60 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -32,8 +32,8 @@ private static string[] GetInputParameters(TestData canonicalDataCase, string co protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { - return testMethodBody.Data.UseVariableForExpected - ? RenderComplexNumberAssert(testMethodBody) + return testMethodBody.Data.UseVariableForExpected + ? RenderComplexNumberAssert(testMethodBody) : base.RenderTestMethodBodyAssert(testMethodBody); } @@ -48,8 +48,8 @@ private static IEnumerable RenderComplexNumberAssert(TestMethodBody test private static object ConvertToType(dynamic rawValue) { - return IsComplexNumber(rawValue) - ? new UnescapedValue($"new ComplexNumber({ValueFormatter.Format(ConvertMathDouble(rawValue[0]))}, {ValueFormatter.Format(ConvertMathDouble(rawValue[1]))})") + return IsComplexNumber(rawValue) + ? new UnescapedValue($"new ComplexNumber({ValueFormatter.Format(ConvertMathDouble(rawValue[0]))}, {ValueFormatter.Format(ConvertMathDouble(rawValue[1]))})") : rawValue; } diff --git a/generators/Exercises/Connect.cs b/generators/Exercises/Connect.cs index 8c62c7d12d..a84a8fbce1 100644 --- a/generators/Exercises/Connect.cs +++ b/generators/Exercises/Connect.cs @@ -29,7 +29,7 @@ protected override void UpdateTestData(TestData data) private static UnescapedValue ToMultiLineString(IEnumerable input) { const string template = -@"new [] + @"new [] { {% if input.size == 0 %}string.Empty{% else %}{% for item in {{input}} %}{% if forloop.length == 1 %}""{{item}}""{% break %}{% endif %}""{{item}}""{% if forloop.last == false %},{% else %}{{string.Empty}}{% endif %} {% endfor %}{% endif %} diff --git a/generators/Exercises/Wordy.cs b/generators/Exercises/Wordy.cs index 778e7223f3..e631bcf758 100644 --- a/generators/Exercises/Wordy.cs +++ b/generators/Exercises/Wordy.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises public class Wordy : GeneratorExercise { protected override void UpdateTestData(TestData data) - { + { data.ExceptionThrown = data.Expected is bool ? typeof(ArgumentException) : null; } } diff --git a/generators/Exercises/Yacht.cs b/generators/Exercises/Yacht.cs index 80bfc8f15a..6b7fb2df01 100644 --- a/generators/Exercises/Yacht.cs +++ b/generators/Exercises/Yacht.cs @@ -6,7 +6,7 @@ namespace Generators.Exercises public class Yacht : GeneratorExercise { protected override void UpdateTestData(TestData data) - { + { data.TestedClass = "YachtGame"; var category = data.Input["category"].ToString(); var formattedCategory = StringDehumanizeExtensions.Dehumanize(category); diff --git a/generators/Input/CanonicalData.cs b/generators/Input/CanonicalData.cs index 5821c6e961..e83573b6c3 100644 --- a/generators/Input/CanonicalData.cs +++ b/generators/Input/CanonicalData.cs @@ -2,7 +2,7 @@ namespace Generators.Input { - public sealed class CanonicalData + public class CanonicalData { public CanonicalData(string exercise, string version, IReadOnlyCollection cases) => (Exercise, Version, Cases) = (exercise, version, cases); diff --git a/generators/Input/CanonicalDataCase.cs b/generators/Input/CanonicalDataCase.cs index 2bc04f036d..4a606180b1 100644 --- a/generators/Input/CanonicalDataCase.cs +++ b/generators/Input/CanonicalDataCase.cs @@ -2,7 +2,7 @@ namespace Generators.Input { - public sealed class CanonicalDataCase + public class CanonicalDataCase { public CanonicalDataCase(string property, IReadOnlyDictionary properties, IReadOnlyDictionary input, dynamic expected, diff --git a/generators/Input/CanonicalDataFile.cs b/generators/Input/CanonicalDataFile.cs index 8c91b89cec..e9b3e5d22c 100644 --- a/generators/Input/CanonicalDataFile.cs +++ b/generators/Input/CanonicalDataFile.cs @@ -14,16 +14,13 @@ public class CanonicalDataFile private readonly Options _options; - public CanonicalDataFile(Options options) - { - _options = options; - } + public CanonicalDataFile(Options options) => _options = options; public bool Exists(string exercise) => File.Exists(GetExerciseCanonicalDataPath(exercise)); public string Contents(string exercise) => File.ReadAllText(GetExerciseCanonicalDataPath(exercise)); - private string GetExerciseCanonicalDataPath(string exercise) + private string GetExerciseCanonicalDataPath(string exercise) => Path.Combine(_options.CanonicalDataDirectory, "exercises", exercise, "canonical-data.json"); public void DownloadData() @@ -55,10 +52,10 @@ private void UpdateToLatestVersion() using (var repository = new Repository(_options.CanonicalDataDirectory)) { Commands.Fetch(repository, ProblemSpecificationsRemote, Enumerable.Empty(), new FetchOptions(), null); - + var remoteBranch = repository.Branches[ProblemSpecificationsRemoteBranch]; repository.Reset(ResetMode.Hard, remoteBranch.Tip); - } + } Log.Information("Updated repository to latest version."); } diff --git a/generators/Input/CanonicalDataParser.cs b/generators/Input/CanonicalDataParser.cs index 257bc24b3b..d54f2b0e5d 100644 --- a/generators/Input/CanonicalDataParser.cs +++ b/generators/Input/CanonicalDataParser.cs @@ -25,7 +25,7 @@ public CanonicalData Parse(string exercise) private static string ParseVersion(JToken canonicalDataJObject) => canonicalDataJObject.Value("version"); - private static IReadOnlyCollection ParseCanonicalDataCases(JObject canonicalDataJObject) + private static IReadOnlyCollection ParseCanonicalDataCases(JObject canonicalDataJObject) => CanonicalDataCaseParser.Parse((JArray)canonicalDataJObject["cases"]); } } \ No newline at end of file diff --git a/generators/Input/TrackConfigFile.cs b/generators/Input/TrackConfigFile.cs index e1dbccad92..bd49fe0fa2 100644 --- a/generators/Input/TrackConfigFile.cs +++ b/generators/Input/TrackConfigFile.cs @@ -14,17 +14,16 @@ public static IEnumerable GetExercises() { var jsonContents = File.ReadAllText(ConfigFilePath); var config = JsonConvert.DeserializeObject(jsonContents); - return config.Exercises.OrderBy(x => x.Name).ToArray(); + return config.Exercises.OrderBy(x => x.Slug).ToArray(); } - private class Config + private sealed class Config { public ConfigExercise[] Exercises { get; set; } } public class ConfigExercise { - public string Name => Slug.ToExerciseName(); public string Slug { get; set; } public bool Deprecated { get; set; } } diff --git a/generators/MissingDataExercise.cs b/generators/MissingDataExercise.cs index 8e8e8675d4..f92f3f47db 100644 --- a/generators/MissingDataExercise.cs +++ b/generators/MissingDataExercise.cs @@ -1,6 +1,6 @@ namespace Generators { - public sealed class MissingDataExercise : Exercise + public class MissingDataExercise : Exercise { public MissingDataExercise(string name) => Name = name; diff --git a/generators/Options.cs b/generators/Options.cs index 5817b3ab0f..ccba12b5f8 100644 --- a/generators/Options.cs +++ b/generators/Options.cs @@ -9,7 +9,7 @@ public class Options private static string DefaultCanonicalDataDirectory => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "exercism", "problem-specifications"); - [Option('e', "exercise", Required = false, + [Option('e', "exercise", Required = false, HelpText = "Exercise to generate (defaults to all exercises).")] public string Exercise { get; set; } diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index d6597234fb..1015812cc2 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -9,7 +9,7 @@ public class TestClass public IEnumerable Methods { get; set; } public IEnumerable UsingNamespaces { get; set; } public string TemplateName { get; set; } = "TestClass"; - + public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { ClassName, CanonicalDataVersion, Methods, UsingNamespaces }); - } + } } \ No newline at end of file diff --git a/generators/Output/TestData.cs b/generators/Output/TestData.cs index 96d390b559..f6483f70d1 100644 --- a/generators/Output/TestData.cs +++ b/generators/Output/TestData.cs @@ -5,7 +5,7 @@ namespace Generators.Output { - public sealed class TestData + public class TestData { public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) { @@ -15,23 +15,23 @@ public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase Exercise = canonicalData.Exercise; Property = canonicalDataCase.Property; - + Description = canonicalDataCase.Description; DescriptionPath = new List(canonicalDataCase.DescriptionPath); - + SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); - + TestedClass = canonicalData.Exercise.ToTestedClassName(); TestedMethod = canonicalDataCase.Property.ToTestedMethodName(); } - + public string Exercise { get; } public string Property { get; } - + public IDictionary Properties { get; set; } public IDictionary Input { get; set; } public dynamic Expected { get; set; } - + public string Description { get; set; } public IList DescriptionPath { get; set; } diff --git a/generators/Output/TestMethodBodyWithEqualityCheck.cs b/generators/Output/TestMethodBodyWithEqualityCheck.cs index 57350dc6f1..cc67e003b6 100644 --- a/generators/Output/TestMethodBodyWithEqualityCheck.cs +++ b/generators/Output/TestMethodBodyWithEqualityCheck.cs @@ -8,14 +8,14 @@ public TestMethodBodyWithEqualityCheck(TestData data) : base(data) { Data.UseVariableForExpected = Data.UseVariableForExpected && !ExpectedIsEmptyEnumerable; InitializeTemplateParameters(); - + AssertTemplateName = ExpectedIsEmptyEnumerable ? "AssertEqual_Empty" : "AssertEqual"; AssertTemplateParameters = new { ExpectedParameter, TestedValue }; } private bool ExpectedIsEmptyEnumerable => !(Data.Expected is string) && - Data.Expected is IEnumerable enumerable + Data.Expected is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; } } \ No newline at end of file diff --git a/generators/Output/TestMethodBodyWithExceptionCheck.cs b/generators/Output/TestMethodBodyWithExceptionCheck.cs index bfb5b3022b..d947ab7ee1 100644 --- a/generators/Output/TestMethodBodyWithExceptionCheck.cs +++ b/generators/Output/TestMethodBodyWithExceptionCheck.cs @@ -7,7 +7,7 @@ public TestMethodBodyWithExceptionCheck(TestData data) : base(data) Data.UseVariableForExpected = false; Data.UseVariableForTested = false; InitializeTemplateParameters(); - + AssertTemplateName = "AssertThrowsException"; AssertTemplateParameters = new { ExceptionType, TestedValue }; } diff --git a/generators/Program.cs b/generators/Program.cs index 479cf734a3..3c5d2880ea 100644 --- a/generators/Program.cs +++ b/generators/Program.cs @@ -1,5 +1,4 @@ using System; -using System.Diagnostics; using CommandLine; using Generators.Input; using Generators.Output; @@ -19,9 +18,9 @@ public static int Main(string[] args) .WithParsed(RegenerateTestClasses); return 0; } - catch (Exception exception) when (!Debugger.IsAttached) + catch (Exception exception) { - Log.Error(exception, "Exception occured: {Message}", exception.Message); + Log.Error(exception, "Exception occured: {Exception}", exception.Message); return 1; } } @@ -52,7 +51,7 @@ private static void RegenerateTestClasses(Options options) private static void RegenerateTestClass(Exercise exercise, Options options, CanonicalDataParser canonicalDataParser) { - if (ShouldBeSkipped(exercise, options)) + if (SkipGenerateTestClass(exercise, options)) return; switch (exercise) @@ -75,7 +74,7 @@ private static void RegenerateTestClass(Exercise exercise, Options options, Cano } } - private static bool ShouldBeSkipped(Exercise exercise, Options options) + private static bool SkipGenerateTestClass(Exercise exercise, Options options) => DoesNotMatchFilteredExercise(exercise, options) || DoesNotMatchFilteredStatus(exercise, options); private static bool DoesNotMatchFilteredExercise(Exercise exercise, Options options) diff --git a/generators/UnimplementedExercise.cs b/generators/UnimplementedExercise.cs index 1809140b79..f2f28666d4 100644 --- a/generators/UnimplementedExercise.cs +++ b/generators/UnimplementedExercise.cs @@ -1,6 +1,6 @@ namespace Generators { - public sealed class UnimplementedExercise : Exercise + public class UnimplementedExercise : Exercise { public UnimplementedExercise(string name) => Name = name; From 245e122f3a31b73ed2fbd1d05f6dd23ad46788af Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 23 Jun 2018 16:50:59 +0200 Subject: [PATCH 21/97] generators: Use UpdateTestClass/UpdateTestMethod/UpdateTestMethodBody to customize output --- generators/Exercises/Allergies.cs | 9 ++- generators/Exercises/BinarySearchTree.cs | 7 +- generators/Exercises/Bowling.cs | 15 +++- generators/Exercises/CircularBuffer.cs | 7 +- generators/Exercises/Clock.cs | 9 ++- generators/Exercises/ComplexNumbers.cs | 9 ++- generators/Exercises/GoCounting.cs | 9 ++- generators/Exercises/Grep.cs | 7 +- generators/Exercises/Meetup.cs | 7 +- generators/Exercises/NucleotideCount.cs | 7 +- generators/Exercises/PalindromeProducts.cs | 9 ++- generators/Exercises/QueenAttack.cs | 9 ++- generators/Exercises/RationalNumbers.cs | 9 ++- generators/Exercises/React.cs | 15 ++-- generators/Exercises/RobotSimulator.cs | 10 ++- generators/Exercises/RunLengthEncoding.cs | 9 ++- generators/Exercises/SimpleCipher.cs | 9 ++- generators/Exercises/Tournament.cs | 8 +- generators/Exercises/TwoBucket.cs | 10 ++- generators/Exercises/WordSearch.cs | 8 +- generators/Exercises/Zipper.cs | 10 ++- generators/GeneratorExercise.cs | 91 ++++++++++++++-------- generators/Output/TestClass.cs | 6 +- generators/Output/TestMethod.cs | 4 +- generators/Output/TestMethodBody.cs | 26 +++++-- 25 files changed, 231 insertions(+), 88 deletions(-) diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Allergies.cs index 8b9cd6fc8b..ad965885c4 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Allergies.cs @@ -14,12 +14,17 @@ protected override void UpdateTestData(TestData data) data.SetConstructorInputParameters("score"); } + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { return testMethodBody.Data.Property == "allergicTo" ? RenderIsAllergicToAssert(testMethodBody) - : base.RenderTestMethodBodyAssert(testMethodBody); + : testMethodBody.Assert; } private static IEnumerable RenderIsAllergicToAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index e91c5a2402..427f835dd5 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -32,8 +32,13 @@ public class BinarySearchTree : GeneratorExercise private StringBuilder _testFactCodeLines; private void AddCodeLine(string line) => _testFactCodeLines.Append(line + "\r\n"); + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { _testFactCodeLines = new StringBuilder(); var canonicalDataCase = testMethodBody.Data; diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index a93df3ed08..65a531a0c1 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -22,8 +22,15 @@ protected override void UpdateTestData(TestData data) data.SetInputParameters(); } + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Arrange = RenderTestMethodBodyArrange(body); + body.Act = RenderTestMethodBodyAct(body); + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) { var builder = new StringBuilder(); builder.AppendLine("var sut = new BowlingGame();"); @@ -45,7 +52,7 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod return new[] { builder.ToString() }; } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.Data.ExceptionThrown != null && testMethodBody.Data.Input.ContainsKey("roll")) { @@ -59,14 +66,14 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody if (testMethodBody.Data.ExceptionThrown == null || testMethodBody.Data.Property != "score") - return base.RenderTestMethodBodyAssert(testMethodBody); + return testMethodBody.Assert; const string throwTemplate = "Assert.Throws(() => sut.Score());"; return new[] { throwTemplate }; } - protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) { var template = @"DoRoll(previousRolls, sut); diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/CircularBuffer.cs index fdea7feff7..7abcc1223e 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/CircularBuffer.cs @@ -6,7 +6,12 @@ namespace Generators.Exercises { public class CircularBuffer : GeneratorExercise { - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } + + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { yield return RenderSut(testMethodBody.Data); diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Clock.cs index 72e6807d80..95dee1fb41 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Clock.cs @@ -36,8 +36,13 @@ protected override void UpdateTestData(TestData data) data.TestedMethod = "Equals"; } } + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.Data.Property == PropertyEqual) { @@ -46,7 +51,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody return testMethodBody.Data.Property != PropertyCreate ? RenderConsistencyToAssert(testMethodBody) - : base.RenderTestMethodBodyAssert(testMethodBody); + : testMethodBody.Assert; } private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 83384ffd60..e587e76ac1 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -30,11 +30,16 @@ protected override void UpdateTestData(TestData data) private static string[] GetInputParameters(TestData canonicalDataCase, string constructorParamName) => canonicalDataCase.Input.Keys.Where(x => x != constructorParamName).ToArray(); - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } + + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { return testMethodBody.Data.UseVariableForExpected ? RenderComplexNumberAssert(testMethodBody) - : base.RenderTestMethodBodyAssert(testMethodBody); + : testMethodBody.Assert; } private static IEnumerable RenderComplexNumberAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index c2176997ad..655d86b995 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -51,12 +51,17 @@ protected override void UpdateTestData(TestData data) data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } } + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.Data.ExceptionThrown != null) { - return base.RenderTestMethodBodyAssert(testMethodBody); + return testMethodBody.Assert; } if (testMethodBody.Data.Property == "territories") diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index cd00e60e69..773db23dcb 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -29,12 +29,9 @@ private static dynamic ConvertExpected(dynamic expected) return ""; } - protected override TestClass CreateTestClass() + protected override void UpdateTestClass(TestClass @class) { - var testClass = base.CreateTestClass(); - testClass.TemplateName = "TestClassDisposable"; - - return testClass; + @class.TemplateName = "TestClassDisposable"; } protected override IEnumerable AdditionalNamespaces => new[] diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 410c08b732..4dc43ccef6 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -28,8 +28,13 @@ protected override void UpdateTestData(TestData data) data.Input[ParamDayOfWeek] = new UnescapedValue($"DayOfWeek.{((string)data.Input[ParamDayOfWeek]).Transform(To.SentenceCase)}"); } + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString(\"yyyy-MM-dd\"));"; diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index 045447bc32..9073f888b2 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -21,7 +21,12 @@ private static dynamic ConvertExpected(dynamic expected) protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } + + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { return testMethodBody.Data.UseVariableForExpected ? RenderEqualBodyAssert(testMethodBody) diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/PalindromeProducts.cs index 6557589a10..f57ce7acd0 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/PalindromeProducts.cs @@ -21,12 +21,17 @@ protected override void UpdateTestData(TestData data) data.Expected = (data.Expected["value"], FormatCoordinates(data.Expected["factors"])); } } + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.Data.ExceptionThrown != null) { - return base.RenderTestMethodBodyAssert(testMethodBody); + return testMethodBody.Assert; } return new[] diff --git a/generators/Exercises/QueenAttack.cs b/generators/Exercises/QueenAttack.cs index 0c3196798e..33ab8db864 100644 --- a/generators/Exercises/QueenAttack.cs +++ b/generators/Exercises/QueenAttack.cs @@ -11,15 +11,20 @@ protected override void UpdateTestData(TestData data) if (data.Property == "create") SetCreatePropertyData(data); } + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { if (testMethodBody.Data.Property == "canAttack") return new[] { RenderCanAttackAssert(testMethodBody) }; return testMethodBody.Data.UseVariableForTested ? Array.Empty() - : base.RenderTestMethodBodyAssert(testMethodBody); + : testMethodBody.Assert; } private static string RenderCanAttackAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/RationalNumbers.cs b/generators/Exercises/RationalNumbers.cs index 1d9f950c99..2f3f812780 100644 --- a/generators/Exercises/RationalNumbers.cs +++ b/generators/Exercises/RationalNumbers.cs @@ -16,8 +16,13 @@ public RationalNumber(IReadOnlyList n) } public class RationalNumbers : GeneratorExercise - { - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + { + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } + + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { var input = testMethodBody.Data.Properties["input"] as Dictionary; var operation = testMethodBody.Data.Properties["property"].ToString(); diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index 13bf412722..609b7b79e2 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -9,8 +9,14 @@ namespace Generators.Exercises { public class React : GeneratorExercise - { - protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + { + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Arrange = RenderTestMethodBodyArrange(body); + body.Assert = RenderTestMethodBodyAssert(); + } + + private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) { var arrange = new StringBuilder(); arrange.AppendLine("var sut = new Reactor();"); @@ -119,9 +125,8 @@ private static string RenderOperation(dynamic operation) } } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) => new[] { - "" - }; + private static IEnumerable RenderTestMethodBodyAssert() + => new[] { "" }; protected override IEnumerable AdditionalNamespaces => new[] { diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index 1c1bb1566a..2d8bb7adad 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -24,7 +24,13 @@ protected override void UpdateTestData(TestData data) data.UseFullDescriptionPath = true; } - protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Act = RenderTestMethodBodyAct(body); + body.Assert = RenderTestMethodBodyAssert(body); + } + + private static IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) { switch (testMethodBody.Data.Property) { @@ -59,7 +65,7 @@ private static IEnumerable RenderInstructionsMethodBodyAct(TestMethodBod return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { var expected = testMethodBody.Data.Expected as Dictionary; expected.TryGetValue("position", out var position); diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index 719627545b..beb83556ef 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -9,12 +9,17 @@ protected override void UpdateTestData(TestData data) { data.Description = $"{data.Property} {data.Description}"; } + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { return testMethodBody.Data.Property == "consistency" ? RenderConsistencyToAssert(testMethodBody) - : base.RenderTestMethodBodyAssert(testMethodBody); + : testMethodBody.Assert; } private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index dfa1aec284..c198816a7a 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -42,8 +42,13 @@ protected override void UpdateTestData(TestData data) data.Expected = new UnescapedValue("sut.Key.Substring(0, 10)"); } } + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { switch (testMethodBody.Data.Property) { @@ -54,7 +59,7 @@ protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody var pattern = ValueFormatter.Format(testMethodBody.Data.Expected["match"]); return new[] { $"Assert.Matches({pattern}, sut.Key);" }; default: - return base.RenderTestMethodBodyAssert(testMethodBody); + return testMethodBody.Assert; } } diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index aea015b6ee..ad40928f02 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -25,8 +25,14 @@ protected override void UpdateTestData(TestData data) typeof(Stream).Namespace, typeof(UTF8Encoding).Namespace }; + + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(); + } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert() { const string template = @"Assert.Equal(expected, RunTally(rows));"; return new[] { TemplateRenderer.RenderInline(template, new { }) }; diff --git a/generators/Exercises/TwoBucket.cs b/generators/Exercises/TwoBucket.cs index 0f69ef2f2a..3f4cf8a2ed 100644 --- a/generators/Exercises/TwoBucket.cs +++ b/generators/Exercises/TwoBucket.cs @@ -14,7 +14,13 @@ protected override void UpdateTestData(TestData data) data.Input["startBucket"] = new UnescapedValue(startBucket == "two" ? "Bucket.Two" : "Bucket.One"); } - protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Act = RenderTestMethodBodyAct(body); + body.Assert = RenderTestMethodBodyAssert(body); + } + + private static IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) { const string template = @"var result = {{MethodInvocation}};"; @@ -26,7 +32,7 @@ protected override IEnumerable RenderTestMethodBodyAct(TestMethodBody te return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { const string template = @"Assert.Equal({{MovesExpected}}, result.Moves); diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index 07fb14225f..baf83dd637 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -33,7 +33,13 @@ protected override void UpdateTestData(TestData data) data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Assert = RenderTestMethodBodyAssert(body); + } + + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { var expectedDictionary = testMethodBody.Data.Properties["expected"] as IDictionary; diff --git a/generators/Exercises/Zipper.cs b/generators/Exercises/Zipper.cs index 27dfe53a71..c95a2b5c15 100644 --- a/generators/Exercises/Zipper.cs +++ b/generators/Exercises/Zipper.cs @@ -8,7 +8,13 @@ namespace Generators.Exercises { public class Zipper : GeneratorExercise { - protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + protected override void UpdateTestMethodBody(TestMethodBody body) + { + body.Arrange = RenderTestMethodBodyArrange(body); + body.Assert = RenderTestMethodBodyAssert(body); + } + + private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) { var tree = RenderTree(testMethodBody.Data.Input["initialTree"]); yield return $"var tree = {tree};"; @@ -18,7 +24,7 @@ protected override IEnumerable RenderTestMethodBodyArrange(TestMethodBod yield return $"var actual = sut{operations};"; } - protected override IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) { var expected = RenderExpected(testMethodBody.Data.Expected); if (expected == null) diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index 4e363a69e0..c00dd112b5 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -19,22 +19,13 @@ public void Regenerate(CanonicalData canonicalData) ExerciseWriter.WriteToFile(this); } - public string Render() => CreateTestClass().Render(); + public string Render() => CreateUpdatedTestClass().Render(); protected virtual IEnumerable AdditionalNamespaces => Enumerable.Empty(); - protected virtual IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) - => new[] { TemplateRenderer.RenderPartial(testMethodBody.ArrangeTemplateName, testMethodBody.ArrangeTemplateParameters) }; - - protected virtual IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) - => new[] { TemplateRenderer.RenderPartial(testMethodBody.ActTemplateName, testMethodBody.ActTemplateParameters) }; - - protected virtual IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) - => new[] { TemplateRenderer.RenderPartial(testMethodBody.AssertTemplateName, testMethodBody.AssertTemplateParameters) }; - protected virtual IEnumerable RenderAdditionalMethods() => Array.Empty(); - private IEnumerable GetUsingNamespaces(IEnumerable testData) + private IEnumerable GetNamespaces(IEnumerable testData) { var usingNamespaces = new HashSet { "Xunit" }; @@ -52,56 +43,66 @@ private IEnumerable RenderTestMethods(IEnumerable testData) .Concat(RenderAdditionalMethods()) .ToArray(); - protected virtual TestClass CreateTestClass() + private TestClass CreateUpdatedTestClass() { - var testData = _canonicalData.Cases - .Select(canonicalDataCase => CreateTestData(_canonicalData, canonicalDataCase)) - .ToArray(); + var testClass = CreateTestClass(); + UpdateTestClass(testClass); + + return testClass; + } + + private TestClass CreateTestClass() + { + var testData = CreateUpdatedTestData(); - foreach (var data in testData) - UpdateTestData(data); - return new TestClass { ClassName = Name.ToTestClassName(), Methods = RenderTestMethods(testData), CanonicalDataVersion = _canonicalData.Version, - UsingNamespaces = GetUsingNamespaces(testData) + Namespaces = GetNamespaces(testData) }; } + + protected virtual void UpdateTestClass(TestClass @class) + { + } - private string RenderTestMethod(TestData data, int index) => CreateTestMethod(data, index).Render(); + private string RenderTestMethod(TestData data, int index) => CreateUpdatedTestMethod(data, index).Render(); + + protected virtual TestMethod CreateUpdatedTestMethod(TestData data, int index) + { + var testMethod = CreateTestMethod(data, index); + UpdateTestMethod(testMethod); + return testMethod; + } + protected virtual TestMethod CreateTestMethod(TestData data, int index) => new TestMethod { Skip = index > 0, Name = ToTestMethodName(data), - Body = RenderTestMethodBody(data) + Body = CreateUpdatedTestMethodBody(data) }; + protected virtual void UpdateTestMethod(TestMethod method) + { + } + private static string ToTestMethodName(TestData data) => data.UseFullDescriptionPath ? string.Join(" - ", data.DescriptionPath).ToTestMethodName() : data.Description.ToTestMethodName(); - private string RenderTestMethodBody(TestData data) + private TestMethodBody CreateUpdatedTestMethodBody(TestData data) { var testMethodBody = CreateTestMethodBody(data); - testMethodBody.Arrange = RenderTestMethodBodyArrange(testMethodBody); - testMethodBody.Act = RenderTestMethodBodyAct(testMethodBody); - testMethodBody.Assert = RenderTestMethodBodyAssert(testMethodBody); + UpdateTestMethodBody(testMethodBody); - return testMethodBody.Render(); + return testMethodBody; } - protected virtual TestData CreateTestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) - => new TestData(canonicalData, canonicalDataCase); - - protected virtual void UpdateTestData(TestData data) - { - } - - protected virtual TestMethodBody CreateTestMethodBody(TestData data) + private static TestMethodBody CreateTestMethodBody(TestData data) { if (data.ExceptionThrown != null) { @@ -118,5 +119,27 @@ protected virtual TestMethodBody CreateTestMethodBody(TestData data) return new TestMethodBodyWithEqualityCheck(data); } } + + protected virtual void UpdateTestMethodBody(TestMethodBody body) + { + } + + private TestData[] CreateUpdatedTestData() + { + var testData = CreateTestData(); + + foreach (var data in testData) + UpdateTestData(data); + + return testData; + } + + private TestData[] CreateTestData() => _canonicalData.Cases.Select(CreateTestData).ToArray(); + + private TestData CreateTestData(CanonicalDataCase canonicalDataCase) => new TestData(_canonicalData, canonicalDataCase); + + protected virtual void UpdateTestData(TestData data) + { + } } } diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index 1015812cc2..8c68ca198b 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -3,13 +3,13 @@ namespace Generators.Output { public class TestClass - { + { public string ClassName { get; set; } public string CanonicalDataVersion { get; set; } public IEnumerable Methods { get; set; } - public IEnumerable UsingNamespaces { get; set; } + public IEnumerable Namespaces { get; set; } public string TemplateName { get; set; } = "TestClass"; - public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { ClassName, CanonicalDataVersion, Methods, UsingNamespaces }); + public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { ClassName, CanonicalDataVersion, Methods, UsingNamespaces = Namespaces }); } } \ No newline at end of file diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index 47152fc032..3679441ea8 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -4,9 +4,9 @@ public class TestMethod { public bool Skip { get; set; } public string Name { get; set; } - public string Body { get; set; } + public TestMethodBody Body { get; set; } public string TemplateName { get; set; } = "TestMethod"; - public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { Name, Body, Skip }); + public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { Name, Body = Body.Render(), Skip }); } } \ No newline at end of file diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index 6bcbed2f59..e3dc293deb 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -9,7 +9,7 @@ public abstract class TestMethodBody private const string SutVariableName = "sut"; private const string TestedVariableName = "actual"; private const string ExpectedVariableName = "expected"; - + protected TestMethodBody(TestData data) { Data = data; @@ -33,23 +33,30 @@ protected TestMethodBody(TestData data) public IEnumerable Arrange { get; set; } public IEnumerable Assert { get; set; } - public virtual string Render() => TemplateRenderer.RenderPartial(TemplateName, new { Arrange, Act, Assert }); + public virtual string Render() + { + Arrange = Arrange ?? RenderTestMethodBodyArrange(); + Act = Act ?? RenderTestMethodBodyAct(); + Assert = Assert ?? RenderTestMethodBodyAssert(); + + return TemplateRenderer.RenderPartial(TemplateName, new { Arrange, Act, Assert }); + } protected void InitializeTemplateParameters() { ArrangeTemplateParameters = new { Variables }; ActTemplateParameters = new { }; - AssertTemplateParameters = new {ExpectedParameter, TestedValue }; + AssertTemplateParameters = new { ExpectedParameter, TestedValue }; } protected string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; protected string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); protected string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Data.Expected); protected string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); - + private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); - + private IEnumerable InputVariablesDeclaration => ValueFormatter.FormatVariables(Input); private IEnumerable ExpectedVariableDeclaration => ValueFormatter.FormatVariable(Data.Expected, ExpectedVariableName); private IEnumerable ConstructorVariablesDeclaration => ValueFormatter.FormatVariables(ConstructorInput); @@ -98,5 +105,14 @@ public string TestedMethodInvocation } } } + + private IEnumerable RenderTestMethodBodyArrange() + => new[] { TemplateRenderer.RenderPartial(ArrangeTemplateName, ArrangeTemplateParameters) }; + + private IEnumerable RenderTestMethodBodyAct() + => new[] { TemplateRenderer.RenderPartial(ActTemplateName, ActTemplateParameters) }; + + private IEnumerable RenderTestMethodBodyAssert() + => new[] { TemplateRenderer.RenderPartial(AssertTemplateName, AssertTemplateParameters) }; } } \ No newline at end of file From 9a8113526d18296954b7f247a69201e398082bb3 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 23 Jun 2018 17:01:30 +0200 Subject: [PATCH 22/97] exercises: Sort namespaces --- exercises/all-your-base/AllYourBaseTest.cs | 2 +- exercises/alphametics/AlphameticsTest.cs | 2 +- exercises/binary-search-tree/BinarySearchTreeTest.cs | 2 +- exercises/binary-search/BinarySearchTest.cs | 2 +- exercises/book-store/BookStoreTest.cs | 2 +- exercises/bowling/BowlingTest.cs | 2 +- exercises/change/ChangeTest.cs | 2 +- exercises/circular-buffer/CircularBufferTest.cs | 2 +- exercises/collatz-conjecture/CollatzConjectureTest.cs | 2 +- exercises/complex-numbers/ComplexNumbersTest.cs | 2 +- exercises/dominoes/DominoesTest.cs | 2 +- exercises/etl/EtlTest.cs | 2 +- exercises/forth/ForthTest.cs | 2 +- exercises/gigasecond/GigasecondTest.cs | 2 +- exercises/go-counting/GoCountingTest.cs | 2 +- exercises/grains/GrainsTest.cs | 2 +- exercises/grep/GrepTest.cs | 2 +- exercises/hamming/HammingTest.cs | 2 +- .../largest-series-product/LargestSeriesProductTest.cs | 2 +- exercises/list-ops/ListOpsTest.cs | 2 +- exercises/meetup/MeetupTest.cs | 2 +- exercises/minesweeper/MinesweeperTest.cs | 2 +- exercises/nth-prime/NthPrimeTest.cs | 2 +- exercises/nucleotide-count/NucleotideCountTest.cs | 2 +- exercises/ocr-numbers/OcrNumbersTest.cs | 2 +- exercises/palindrome-products/PalindromeProductsTest.cs | 2 +- exercises/pascals-triangle/PascalsTriangleTest.cs | 2 +- exercises/perfect-numbers/PerfectNumbersTest.cs | 2 +- exercises/phone-number/PhoneNumberTest.cs | 2 +- exercises/pov/PovTest.cs | 2 +- exercises/proverb/ProverbTest.cs | 2 +- exercises/queen-attack/QueenAttackTest.cs | 2 +- exercises/react/ReactTest.cs | 4 ++-- exercises/rectangles/RectanglesTest.cs | 2 +- exercises/saddle-points/SaddlePointsTest.cs | 2 +- exercises/say/SayTest.cs | 2 +- exercises/sieve/SieveTest.cs | 2 +- exercises/simple-cipher/SimpleCipherTest.cs | 8 ++++---- exercises/sublist/SublistTest.cs | 2 +- exercises/sum-of-multiples/SumOfMultiplesTest.cs | 2 +- exercises/tournament/TournamentTest.cs | 2 +- .../VariableLengthQuantityTest.cs | 2 +- exercises/word-count/WordCountTest.cs | 2 +- exercises/word-search/WordSearchTest.cs | 2 +- exercises/wordy/WordyTest.cs | 2 +- generators/GeneratorExercise.cs | 2 +- 46 files changed, 50 insertions(+), 50 deletions(-) diff --git a/exercises/all-your-base/AllYourBaseTest.cs b/exercises/all-your-base/AllYourBaseTest.cs index c7ed9acdde..9ce28a7e49 100644 --- a/exercises/all-your-base/AllYourBaseTest.cs +++ b/exercises/all-your-base/AllYourBaseTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 2.3.0 of the canonical data. -using Xunit; using System; +using Xunit; public class AllYourBaseTest { diff --git a/exercises/alphametics/AlphameticsTest.cs b/exercises/alphametics/AlphameticsTest.cs index 3ce16c20ce..ce325e38b8 100644 --- a/exercises/alphametics/AlphameticsTest.cs +++ b/exercises/alphametics/AlphameticsTest.cs @@ -1,8 +1,8 @@ // This file was auto-generated based on version 1.2.0 of the canonical data. -using Xunit; using System; using System.Collections.Generic; +using Xunit; public class AlphameticsTest { diff --git a/exercises/binary-search-tree/BinarySearchTreeTest.cs b/exercises/binary-search-tree/BinarySearchTreeTest.cs index 970c4b81c7..9246e9b30c 100644 --- a/exercises/binary-search-tree/BinarySearchTreeTest.cs +++ b/exercises/binary-search-tree/BinarySearchTreeTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.0.0 of the canonical data. -using Xunit; using System.Linq; +using Xunit; public class BinarySearchTreeTest { diff --git a/exercises/binary-search/BinarySearchTest.cs b/exercises/binary-search/BinarySearchTest.cs index 33dae2e239..cf4c027b81 100644 --- a/exercises/binary-search/BinarySearchTest.cs +++ b/exercises/binary-search/BinarySearchTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class BinarySearchTest { diff --git a/exercises/book-store/BookStoreTest.cs b/exercises/book-store/BookStoreTest.cs index 78b8e8a871..204505245f 100644 --- a/exercises/book-store/BookStoreTest.cs +++ b/exercises/book-store/BookStoreTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.3.0 of the canonical data. -using Xunit; using System; +using Xunit; public class BookStoreTest { diff --git a/exercises/bowling/BowlingTest.cs b/exercises/bowling/BowlingTest.cs index 8851cda911..230ddbfdcf 100644 --- a/exercises/bowling/BowlingTest.cs +++ b/exercises/bowling/BowlingTest.cs @@ -1,8 +1,8 @@ // This file was auto-generated based on version 1.2.0 of the canonical data. -using Xunit; using System; using System.Collections.Generic; +using Xunit; public class BowlingTest { diff --git a/exercises/change/ChangeTest.cs b/exercises/change/ChangeTest.cs index 1c7f79169e..9663ad5867 100644 --- a/exercises/change/ChangeTest.cs +++ b/exercises/change/ChangeTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.2.0 of the canonical data. -using Xunit; using System; +using Xunit; public class ChangeTest { diff --git a/exercises/circular-buffer/CircularBufferTest.cs b/exercises/circular-buffer/CircularBufferTest.cs index e0ae774635..f5be48eedd 100644 --- a/exercises/circular-buffer/CircularBufferTest.cs +++ b/exercises/circular-buffer/CircularBufferTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class CircularBufferTest { diff --git a/exercises/collatz-conjecture/CollatzConjectureTest.cs b/exercises/collatz-conjecture/CollatzConjectureTest.cs index 32b512d359..e5748ef4f8 100644 --- a/exercises/collatz-conjecture/CollatzConjectureTest.cs +++ b/exercises/collatz-conjecture/CollatzConjectureTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.2.0 of the canonical data. -using Xunit; using System; +using Xunit; public class CollatzConjectureTest { diff --git a/exercises/complex-numbers/ComplexNumbersTest.cs b/exercises/complex-numbers/ComplexNumbersTest.cs index 8835b7d521..7b5b3e2270 100644 --- a/exercises/complex-numbers/ComplexNumbersTest.cs +++ b/exercises/complex-numbers/ComplexNumbersTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.3.0 of the canonical data. -using Xunit; using System; +using Xunit; public class ComplexNumbersTest { diff --git a/exercises/dominoes/DominoesTest.cs b/exercises/dominoes/DominoesTest.cs index 97fa3bc7dd..03d2270700 100644 --- a/exercises/dominoes/DominoesTest.cs +++ b/exercises/dominoes/DominoesTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 2.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class DominoesTest { diff --git a/exercises/etl/EtlTest.cs b/exercises/etl/EtlTest.cs index 5207bd5c74..2ecc5f7212 100644 --- a/exercises/etl/EtlTest.cs +++ b/exercises/etl/EtlTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.0.0 of the canonical data. -using Xunit; using System.Collections.Generic; +using Xunit; public class EtlTest { diff --git a/exercises/forth/ForthTest.cs b/exercises/forth/ForthTest.cs index bba6dda3b2..1ee9c54287 100644 --- a/exercises/forth/ForthTest.cs +++ b/exercises/forth/ForthTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.6.0 of the canonical data. -using Xunit; using System; +using Xunit; public class ForthTest { diff --git a/exercises/gigasecond/GigasecondTest.cs b/exercises/gigasecond/GigasecondTest.cs index 2c56fe3f73..ba2e004924 100644 --- a/exercises/gigasecond/GigasecondTest.cs +++ b/exercises/gigasecond/GigasecondTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class GigasecondTest { diff --git a/exercises/go-counting/GoCountingTest.cs b/exercises/go-counting/GoCountingTest.cs index 30c7faebec..49e2ada09b 100644 --- a/exercises/go-counting/GoCountingTest.cs +++ b/exercises/go-counting/GoCountingTest.cs @@ -1,8 +1,8 @@ // This file was auto-generated based on version 1.0.0 of the canonical data. -using Xunit; using System; using System.Collections.Generic; +using Xunit; public class GoCountingTest { diff --git a/exercises/grains/GrainsTest.cs b/exercises/grains/GrainsTest.cs index 895efb6775..e6782ef1e6 100644 --- a/exercises/grains/GrainsTest.cs +++ b/exercises/grains/GrainsTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class GrainsTest { diff --git a/exercises/grep/GrepTest.cs b/exercises/grep/GrepTest.cs index 8c61ab9976..7cb9de6d9f 100644 --- a/exercises/grep/GrepTest.cs +++ b/exercises/grep/GrepTest.cs @@ -1,8 +1,8 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; using System.IO; +using Xunit; public class GrepTest : IDisposable { diff --git a/exercises/hamming/HammingTest.cs b/exercises/hamming/HammingTest.cs index 67d3b71159..d38c185207 100644 --- a/exercises/hamming/HammingTest.cs +++ b/exercises/hamming/HammingTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 2.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class HammingTest { diff --git a/exercises/largest-series-product/LargestSeriesProductTest.cs b/exercises/largest-series-product/LargestSeriesProductTest.cs index c41f8613c4..e17ff30af9 100644 --- a/exercises/largest-series-product/LargestSeriesProductTest.cs +++ b/exercises/largest-series-product/LargestSeriesProductTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class LargestSeriesProductTest { diff --git a/exercises/list-ops/ListOpsTest.cs b/exercises/list-ops/ListOpsTest.cs index ea57b19b74..38cbc1cf28 100644 --- a/exercises/list-ops/ListOpsTest.cs +++ b/exercises/list-ops/ListOpsTest.cs @@ -1,8 +1,8 @@ // This file was auto-generated based on version 2.3.0 of the canonical data. -using Xunit; using System; using System.Collections.Generic; +using Xunit; public class ListOpsTest { diff --git a/exercises/meetup/MeetupTest.cs b/exercises/meetup/MeetupTest.cs index a4fe493710..c6ac3b7b24 100644 --- a/exercises/meetup/MeetupTest.cs +++ b/exercises/meetup/MeetupTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class MeetupTest { diff --git a/exercises/minesweeper/MinesweeperTest.cs b/exercises/minesweeper/MinesweeperTest.cs index d08846350f..e2e8dbbc61 100644 --- a/exercises/minesweeper/MinesweeperTest.cs +++ b/exercises/minesweeper/MinesweeperTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class MinesweeperTest { diff --git a/exercises/nth-prime/NthPrimeTest.cs b/exercises/nth-prime/NthPrimeTest.cs index 8c9aec4c89..4a2ca7fb4d 100644 --- a/exercises/nth-prime/NthPrimeTest.cs +++ b/exercises/nth-prime/NthPrimeTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 2.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class NthPrimeTest { diff --git a/exercises/nucleotide-count/NucleotideCountTest.cs b/exercises/nucleotide-count/NucleotideCountTest.cs index 9b4174757c..22646544d3 100644 --- a/exercises/nucleotide-count/NucleotideCountTest.cs +++ b/exercises/nucleotide-count/NucleotideCountTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.3.0 of the canonical data. -using Xunit; using System.Collections.Generic; +using Xunit; public class NucleotideCountTest { diff --git a/exercises/ocr-numbers/OcrNumbersTest.cs b/exercises/ocr-numbers/OcrNumbersTest.cs index b189cdc75d..9043f2d538 100644 --- a/exercises/ocr-numbers/OcrNumbersTest.cs +++ b/exercises/ocr-numbers/OcrNumbersTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class OcrNumbersTest { diff --git a/exercises/palindrome-products/PalindromeProductsTest.cs b/exercises/palindrome-products/PalindromeProductsTest.cs index 89e57b6510..de2548c600 100644 --- a/exercises/palindrome-products/PalindromeProductsTest.cs +++ b/exercises/palindrome-products/PalindromeProductsTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class PalindromeProductsTest { diff --git a/exercises/pascals-triangle/PascalsTriangleTest.cs b/exercises/pascals-triangle/PascalsTriangleTest.cs index b5d1fad9ef..81e5fc93bc 100644 --- a/exercises/pascals-triangle/PascalsTriangleTest.cs +++ b/exercises/pascals-triangle/PascalsTriangleTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.3.0 of the canonical data. -using Xunit; using System; +using Xunit; public class PascalsTriangleTest { diff --git a/exercises/perfect-numbers/PerfectNumbersTest.cs b/exercises/perfect-numbers/PerfectNumbersTest.cs index 7fc8dd88fc..35487c1bc5 100644 --- a/exercises/perfect-numbers/PerfectNumbersTest.cs +++ b/exercises/perfect-numbers/PerfectNumbersTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class PerfectNumbersTest { diff --git a/exercises/phone-number/PhoneNumberTest.cs b/exercises/phone-number/PhoneNumberTest.cs index 7ffaa32460..d388cfb707 100644 --- a/exercises/phone-number/PhoneNumberTest.cs +++ b/exercises/phone-number/PhoneNumberTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.4.0 of the canonical data. -using Xunit; using System; +using Xunit; public class PhoneNumberTest { diff --git a/exercises/pov/PovTest.cs b/exercises/pov/PovTest.cs index cdc07dd868..acfc683f46 100644 --- a/exercises/pov/PovTest.cs +++ b/exercises/pov/PovTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.3.0 of the canonical data. -using Xunit; using System; +using Xunit; public class PovTest { diff --git a/exercises/proverb/ProverbTest.cs b/exercises/proverb/ProverbTest.cs index 72a23eea98..af7371410e 100644 --- a/exercises/proverb/ProverbTest.cs +++ b/exercises/proverb/ProverbTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class ProverbTest { diff --git a/exercises/queen-attack/QueenAttackTest.cs b/exercises/queen-attack/QueenAttackTest.cs index 5b85d6459e..cda7d9298d 100644 --- a/exercises/queen-attack/QueenAttackTest.cs +++ b/exercises/queen-attack/QueenAttackTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 2.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class QueenAttackTest { diff --git a/exercises/react/ReactTest.cs b/exercises/react/ReactTest.cs index df01056e82..12a4bbf1e8 100644 --- a/exercises/react/ReactTest.cs +++ b/exercises/react/ReactTest.cs @@ -1,8 +1,8 @@ // This file was auto-generated based on version 2.0.0 of the canonical data. -using Xunit; -using System; using FakeItEasy; +using System; +using Xunit; public class ReactTest { diff --git a/exercises/rectangles/RectanglesTest.cs b/exercises/rectangles/RectanglesTest.cs index 115ab5e4eb..d94f27fb90 100644 --- a/exercises/rectangles/RectanglesTest.cs +++ b/exercises/rectangles/RectanglesTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class RectanglesTest { diff --git a/exercises/saddle-points/SaddlePointsTest.cs b/exercises/saddle-points/SaddlePointsTest.cs index db0c869a53..0e913a31ab 100644 --- a/exercises/saddle-points/SaddlePointsTest.cs +++ b/exercises/saddle-points/SaddlePointsTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class SaddlePointsTest { diff --git a/exercises/say/SayTest.cs b/exercises/say/SayTest.cs index 4b831f8de2..8f5d7a0915 100644 --- a/exercises/say/SayTest.cs +++ b/exercises/say/SayTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class SayTest { diff --git a/exercises/sieve/SieveTest.cs b/exercises/sieve/SieveTest.cs index b30083c964..f7e934c0f5 100644 --- a/exercises/sieve/SieveTest.cs +++ b/exercises/sieve/SieveTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class SieveTest { diff --git a/exercises/simple-cipher/SimpleCipherTest.cs b/exercises/simple-cipher/SimpleCipherTest.cs index f2c89995b4..5dd3b8ac85 100644 --- a/exercises/simple-cipher/SimpleCipherTest.cs +++ b/exercises/simple-cipher/SimpleCipherTest.cs @@ -1,7 +1,7 @@ -// This file was auto-generated based on version 1.0.0 of the canonical data. +// This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class SimpleCipherTest { @@ -9,14 +9,14 @@ public class SimpleCipherTest public void Random_key_cipher_can_encode() { var sut = new SimpleCipher(); - Assert.Equal(sut.Key.Substring(0, 10), sut.Encode("aaaaaaaaaa")); + Assert.Equal("cipher.key.substring(0, plaintext.length)", sut.Encode("aaaaaaaaaa")); } [Fact(Skip = "Remove to run test")] public void Random_key_cipher_can_decode() { var sut = new SimpleCipher(); - Assert.Equal("aaaaaaaaaa", sut.Decode(sut.Key.Substring(0, 10))); + Assert.Equal("aaaaaaaaaa", sut.Decode("cipher.key.substring(0, expected.length)")); } [Fact(Skip = "Remove to run test")] diff --git a/exercises/sublist/SublistTest.cs b/exercises/sublist/SublistTest.cs index 18b3d89683..1a8005f6e9 100644 --- a/exercises/sublist/SublistTest.cs +++ b/exercises/sublist/SublistTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System.Collections.Generic; +using Xunit; public class SublistTest { diff --git a/exercises/sum-of-multiples/SumOfMultiplesTest.cs b/exercises/sum-of-multiples/SumOfMultiplesTest.cs index 3befa60321..d2e97016a7 100644 --- a/exercises/sum-of-multiples/SumOfMultiplesTest.cs +++ b/exercises/sum-of-multiples/SumOfMultiplesTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.2.0 of the canonical data. -using Xunit; using System; +using Xunit; public class SumOfMultiplesTest { diff --git a/exercises/tournament/TournamentTest.cs b/exercises/tournament/TournamentTest.cs index 881efaad14..98f4880f7d 100644 --- a/exercises/tournament/TournamentTest.cs +++ b/exercises/tournament/TournamentTest.cs @@ -1,9 +1,9 @@ // This file was auto-generated based on version 1.4.0 of the canonical data. -using Xunit; using System; using System.IO; using System.Text; +using Xunit; public class TournamentTest { diff --git a/exercises/variable-length-quantity/VariableLengthQuantityTest.cs b/exercises/variable-length-quantity/VariableLengthQuantityTest.cs index b71cca1166..891314b416 100644 --- a/exercises/variable-length-quantity/VariableLengthQuantityTest.cs +++ b/exercises/variable-length-quantity/VariableLengthQuantityTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class VariableLengthQuantityTest { diff --git a/exercises/word-count/WordCountTest.cs b/exercises/word-count/WordCountTest.cs index 8e592381d5..309e3049b3 100644 --- a/exercises/word-count/WordCountTest.cs +++ b/exercises/word-count/WordCountTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.2.0 of the canonical data. -using Xunit; using System.Collections.Generic; +using Xunit; public class WordCountTest { diff --git a/exercises/word-search/WordSearchTest.cs b/exercises/word-search/WordSearchTest.cs index 219a0db813..eb7add4f35 100644 --- a/exercises/word-search/WordSearchTest.cs +++ b/exercises/word-search/WordSearchTest.cs @@ -1,8 +1,8 @@ // This file was auto-generated based on version 1.2.1 of the canonical data. -using Xunit; using System; using System.Collections.Generic; +using Xunit; public class WordSearchTest { diff --git a/exercises/wordy/WordyTest.cs b/exercises/wordy/WordyTest.cs index 92adbc262d..aa2ff5436a 100644 --- a/exercises/wordy/WordyTest.cs +++ b/exercises/wordy/WordyTest.cs @@ -1,7 +1,7 @@ // This file was auto-generated based on version 1.1.0 of the canonical data. -using Xunit; using System; +using Xunit; public class WordyTest { diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index c00dd112b5..383d551c6b 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -27,7 +27,7 @@ public void Regenerate(CanonicalData canonicalData) private IEnumerable GetNamespaces(IEnumerable testData) { - var usingNamespaces = new HashSet { "Xunit" }; + var usingNamespaces = new SortedSet { "Xunit" }; foreach (var data in testData.Where(x => x.ExceptionThrown != null)) usingNamespaces.Add(data.ExceptionThrown.Namespace); From 6de8d02f1785def89c097388349825a11f1c4c32 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 24 Jun 2018 10:19:59 +0200 Subject: [PATCH 23/97] generator: Make GeneratorExercise API more consistent --- generators/Exercises/AllYourBase.cs | 5 +- generators/Exercises/Alphametics.cs | 7 +- generators/Exercises/BinarySearch.cs | 5 +- generators/Exercises/BinarySearchTree.cs | 7 +- generators/Exercises/BookStore.cs | 5 +- generators/Exercises/Bowling.cs | 22 +++-- generators/Exercises/CircularBuffer.cs | 5 +- generators/Exercises/ComplexNumbers.cs | 5 +- generators/Exercises/Dominoes.cs | 5 +- generators/Exercises/Etl.cs | 5 +- generators/Exercises/Gigasecond.cs | 5 +- generators/Exercises/GoCounting.cs | 9 +- generators/Exercises/Grep.cs | 60 ++++++++---- generators/Exercises/ListOps.cs | 10 +- generators/Exercises/Markdown.cs | 7 +- generators/Exercises/Meetup.cs | 7 +- generators/Exercises/Minesweeper.cs | 5 +- generators/Exercises/NucleotideCount.cs | 5 +- generators/Exercises/OcrNumbers.cs | 5 +- generators/Exercises/Proverb.cs | 5 +- generators/Exercises/React.cs | 10 +- generators/Exercises/Rectangles.cs | 5 +- generators/Exercises/SaddlePoints.cs | 5 +- generators/Exercises/SimpleCipher.cs | 7 +- generators/Exercises/Sublist.cs | 5 +- generators/Exercises/SumOfMultiples.cs | 5 +- generators/Exercises/Tournament.cs | 24 +++-- .../Exercises/VariableLengthQuantity.cs | 5 +- generators/Exercises/WordCount.cs | 5 +- generators/Exercises/WordSearch.cs | 8 +- generators/GeneratorExercise.cs | 96 ++++++++----------- generators/Output/TestClass.cs | 4 +- generators/Output/TestData.cs | 5 + 33 files changed, 227 insertions(+), 146 deletions(-) diff --git a/generators/Exercises/AllYourBase.cs b/generators/Exercises/AllYourBase.cs index 042d846031..a01445dc11 100644 --- a/generators/Exercises/AllYourBase.cs +++ b/generators/Exercises/AllYourBase.cs @@ -15,6 +15,9 @@ protected override void UpdateTestData(TestData data) data.UseVariableForExpected = true; } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/Alphametics.cs b/generators/Exercises/Alphametics.cs index 1c769c85d0..d1aacdfbab 100644 --- a/generators/Exercises/Alphametics.cs +++ b/generators/Exercises/Alphametics.cs @@ -24,6 +24,9 @@ private static dynamic ConvertExpected(TestData canonicalDataCase) return expected.ToDictionary(kv => kv.Key[0], kv => int.Parse(kv.Value.ToString())); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; - } + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Dictionary).Namespace); + } +} } \ No newline at end of file diff --git a/generators/Exercises/BinarySearch.cs b/generators/Exercises/BinarySearch.cs index dfb1174c2c..7c4d305408 100644 --- a/generators/Exercises/BinarySearch.cs +++ b/generators/Exercises/BinarySearch.cs @@ -14,6 +14,9 @@ protected override void UpdateTestData(TestData data) data.SetConstructorInputParameters("array"); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index 427f835dd5..263374c4f1 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -28,11 +28,14 @@ public IEnumerable TestAsserts(string traverse = "") public class BinarySearchTree : GeneratorExercise { - protected override IEnumerable AdditionalNamespaces => new[] { typeof(IQueryable).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(IQueryable).Namespace); + } private StringBuilder _testFactCodeLines; private void AddCodeLine(string line) => _testFactCodeLines.Append(line + "\r\n"); - + protected override void UpdateTestMethodBody(TestMethodBody body) { body.Assert = RenderTestMethodBodyAssert(body); diff --git a/generators/Exercises/BookStore.cs b/generators/Exercises/BookStore.cs index f2ea093db2..149ac0a37f 100644 --- a/generators/Exercises/BookStore.cs +++ b/generators/Exercises/BookStore.cs @@ -15,6 +15,9 @@ protected override void UpdateTestData(TestData data) data.UseVariablesForInput = true; } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index 65a531a0c1..f618642377 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -101,23 +101,27 @@ private static IEnumerable RenderTestMethodBodyAct(TestMethodBody testMe return new[] { template }; } - protected override IEnumerable RenderAdditionalMethods() + protected override void UpdateTestClass(TestClass @class) { - return new[] { -@" + AddDoRollMethod(@class); + } + + private static void AddDoRollMethod(TestClass @class) + { + @class.Methods.Add(@" public void DoRoll(ICollection rolls, BowlingGame sut) { foreach (var roll in rolls) { sut.Roll(roll); } -}" }; +}"); } - - protected override IEnumerable AdditionalNamespaces => new[] + + protected override void UpdateNamespaces(ISet namespaces) { - typeof(Array).Namespace, - typeof(ICollection<>).Namespace - }; + namespaces.Add(typeof(Array).Namespace); + namespaces.Add(typeof(ICollection<>).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/CircularBuffer.cs index 7abcc1223e..2c01d0629a 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/CircularBuffer.cs @@ -62,6 +62,9 @@ private static string RenderOverwriteOperation(dynamic operation) private static string RenderClearOperation() => "buffer.Clear();"; - protected override IEnumerable AdditionalNamespaces => new[] { typeof(InvalidOperationException).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(InvalidOperationException).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index e587e76ac1..6f3f996f43 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -49,7 +49,10 @@ private static IEnumerable RenderComplexNumberAssert(TestMethodBody test return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Math).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Math).Namespace); + } private static object ConvertToType(dynamic rawValue) { diff --git a/generators/Exercises/Dominoes.cs b/generators/Exercises/Dominoes.cs index 56485a1935..b99e6532b3 100644 --- a/generators/Exercises/Dominoes.cs +++ b/generators/Exercises/Dominoes.cs @@ -14,7 +14,10 @@ protected override void UpdateTestData(TestData data) data.Input["dominoes"] = ConvertInput(data.Input["dominoes"]); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Tuple).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Tuple).Namespace); + } private static UnescapedValue ConvertInput(dynamic input) { diff --git a/generators/Exercises/Etl.cs b/generators/Exercises/Etl.cs index 3a0dc9cbf1..845b72cfb3 100644 --- a/generators/Exercises/Etl.cs +++ b/generators/Exercises/Etl.cs @@ -24,6 +24,9 @@ private static IDictionary ConvertInput(IDictionary int.Parse(kv.Key), kv => (string[])kv.Value) }; - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Dictionary).Namespace); + } } } diff --git a/generators/Exercises/Gigasecond.cs b/generators/Exercises/Gigasecond.cs index 54fe3288d9..ddf48fef05 100644 --- a/generators/Exercises/Gigasecond.cs +++ b/generators/Exercises/Gigasecond.cs @@ -13,7 +13,10 @@ protected override void UpdateTestData(TestData data) data.Expected = new UnescapedValue(FormatDateTime((DateTime)data.Expected)); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(DateTime).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(DateTime).Namespace); + } private static string FormatDateTime(DateTime dateTime) { diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index 655d86b995..4c54b001ea 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -87,11 +87,10 @@ private static string FormatOwner(dynamic owner) private static string FormatTerritory(dynamic territory) => ValueFormatter.Format((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); - - protected override IEnumerable AdditionalNamespaces => new[] + + protected override void UpdateNamespaces(ISet namespaces) { - typeof(ArgumentException).Namespace, - typeof(Dictionary).Namespace - }; + namespaces.Add(typeof(Dictionary).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Grep.cs index 773db23dcb..844546a771 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Grep.cs @@ -32,19 +32,22 @@ private static dynamic ConvertExpected(dynamic expected) protected override void UpdateTestClass(TestClass @class) { @class.TemplateName = "TestClassDisposable"; + + AddAdditionalMethods(@class); } - protected override IEnumerable AdditionalNamespaces => new[] + private static void AddAdditionalMethods(TestClass @class) { - typeof(IDisposable).Namespace, - typeof(File).Namespace - }; + AddIliadData(@class); + AddMidsummerNightData(@class); + AddParadiseLostData(@class); + AddConstructor(@class); + AddDisposeMethod(@class); + } - protected override IEnumerable RenderAdditionalMethods() + private static void AddIliadData(TestClass @class) { - return new[] - { - @" + @class.Methods.Add(@" private const string IliadFileName = ""iliad.txt""; private const string IliadContents = ""Achilles sing, O Goddess! Peleus' son;\n"" + @@ -55,8 +58,12 @@ protected override IEnumerable RenderAdditionalMethods() ""To dogs and to all ravening fowls a prey,\n"" + ""When fierce dispute had separated once\n"" + ""The noble Chief Achilles from the son\n"" + - ""Of Atreus, Agamemnon, King of men.\n"";", - @" + ""Of Atreus, Agamemnon, King of men.\n"";"); + } + + private static void AddMidsummerNightData(TestClass @class) + { + @class.Methods.Add(@" private const string MidsummerNightFileName = ""midsummer-night.txt""; private const string MidsummerNightContents = ""I do entreat your grace to pardon me.\n"" + @@ -65,8 +72,12 @@ protected override IEnumerable RenderAdditionalMethods() ""In such a presence here to plead my thoughts;\n"" + ""But I beseech your grace that I may know\n"" + ""The worst that may befall me in this case,\n"" + - ""If I refuse to wed Demetrius.\n"";", - @" + ""If I refuse to wed Demetrius.\n"";"); + } + + private static void AddParadiseLostData(TestClass @class) + { + @class.Methods.Add(@" private const string ParadiseLostFileName = ""paradise-lost.txt""; private const string ParadiseLostContents = ""Of Mans First Disobedience, and the Fruit\n"" + @@ -76,24 +87,37 @@ protected override IEnumerable RenderAdditionalMethods() ""Restore us, and regain the blissful Seat,\n"" + ""Sing Heav'nly Muse, that on the secret top\n"" + ""Of Oreb, or of Sinai, didst inspire\n"" + - ""That Shepherd, who first taught the chosen Seed\n"";", - @" + ""That Shepherd, who first taught the chosen Seed\n"";"); + } + + private static void AddConstructor(TestClass @class) + { + @class.Methods.Add(@" public GrepTest() { Directory.SetCurrentDirectory(Path.GetTempPath()); File.WriteAllText(IliadFileName, IliadContents); File.WriteAllText(MidsummerNightFileName, MidsummerNightContents); File.WriteAllText(ParadiseLostFileName, ParadiseLostContents); -}", - @" +}"); + } + + private static void AddDisposeMethod(TestClass @class) + { + @class.Methods.Add(@" public void Dispose() { Directory.SetCurrentDirectory(Path.GetTempPath()); File.Delete(IliadFileName); File.Delete(MidsummerNightFileName); File.Delete(ParadiseLostFileName); -}" - }; +}"); + } + + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(IDisposable).Namespace); + namespaces.Add(typeof(File).Namespace); } } } diff --git a/generators/Exercises/ListOps.cs b/generators/Exercises/ListOps.cs index 45d5386e08..45fb436804 100644 --- a/generators/Exercises/ListOps.cs +++ b/generators/Exercises/ListOps.cs @@ -99,11 +99,11 @@ private static dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) return value; } - - protected override IEnumerable AdditionalNamespaces => new[] + + protected override void UpdateNamespaces(ISet namespaces) { - typeof(Func).Namespace, - typeof(List).Namespace - }; + namespaces.Add(typeof(Func).Namespace); + namespaces.Add(typeof(List).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/Markdown.cs b/generators/Exercises/Markdown.cs index b8a580aecd..9b033b1f6c 100644 --- a/generators/Exercises/Markdown.cs +++ b/generators/Exercises/Markdown.cs @@ -10,12 +10,9 @@ protected override void UpdateTestData(TestData data) data.UseVariableForExpected = true; } - protected override TestMethod CreateTestMethod(TestData canonicalDataCase, int index) + protected override void UpdateTestMethod(TestMethod method) { - var testMethod = base.CreateTestMethod(canonicalDataCase, index); - testMethod.Skip = false; - - return testMethod; + method.Skip = false; } } } \ No newline at end of file diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 4dc43ccef6..2af5ebd65c 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -28,7 +28,7 @@ protected override void UpdateTestData(TestData data) data.Input[ParamDayOfWeek] = new UnescapedValue($"DayOfWeek.{((string)data.Input[ParamDayOfWeek]).Transform(To.SentenceCase)}"); } - + protected override void UpdateTestMethodBody(TestMethodBody body) { body.Assert = RenderTestMethodBodyAssert(body); @@ -41,6 +41,9 @@ private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody tes return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(DayOfWeek).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(DayOfWeek).Namespace); + } } } diff --git a/generators/Exercises/Minesweeper.cs b/generators/Exercises/Minesweeper.cs index 5b84f03495..b68387f775 100644 --- a/generators/Exercises/Minesweeper.cs +++ b/generators/Exercises/Minesweeper.cs @@ -30,6 +30,9 @@ private static UnescapedValue ToMultiLineString(IEnumerable input) return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + } } } diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index 9073f888b2..e03b383721 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -19,7 +19,10 @@ protected override void UpdateTestData(TestData data) private static dynamic ConvertExpected(dynamic expected) => ((Dictionary)expected).ToDictionary(kv => kv.Key[0], kv => int.Parse($"{kv.Value}")); - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Dictionary).Namespace); + } protected override void UpdateTestMethodBody(TestMethodBody body) { diff --git a/generators/Exercises/OcrNumbers.cs b/generators/Exercises/OcrNumbers.cs index db7109930a..95ca83b9e6 100644 --- a/generators/Exercises/OcrNumbers.cs +++ b/generators/Exercises/OcrNumbers.cs @@ -24,6 +24,9 @@ private static UnescapedValue ToDigitStringRepresentation(IEnumerable input) return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + } } } diff --git a/generators/Exercises/Proverb.cs b/generators/Exercises/Proverb.cs index f4d5ce1c6b..1df38a90a9 100644 --- a/generators/Exercises/Proverb.cs +++ b/generators/Exercises/Proverb.cs @@ -14,6 +14,9 @@ protected override void UpdateTestData(TestData data) data.Expected = ConvertHelper.ToArray(data.Expected); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/React.cs b/generators/Exercises/React.cs index 609b7b79e2..dfa50b3161 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/React.cs @@ -127,12 +127,12 @@ private static string RenderOperation(dynamic operation) private static IEnumerable RenderTestMethodBodyAssert() => new[] { "" }; - - protected override IEnumerable AdditionalNamespaces => new[] + + protected override void UpdateNamespaces(ISet namespaces) { - typeof(EventHandler).Namespace, - "FakeItEasy" - }; + namespaces.Add(typeof(EventHandler).Namespace); + namespaces.Add("FakeItEasy"); + } private static string ToVariableName(dynamic value) => ((string)value).Camelize(); } diff --git a/generators/Exercises/Rectangles.cs b/generators/Exercises/Rectangles.cs index db17ba8aa2..df6c165e99 100644 --- a/generators/Exercises/Rectangles.cs +++ b/generators/Exercises/Rectangles.cs @@ -13,6 +13,9 @@ protected override void UpdateTestData(TestData data) data.UseVariablesForInput = true; } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/SaddlePoints.cs index c01b4c2ca6..31c18a12a9 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/SaddlePoints.cs @@ -25,7 +25,10 @@ protected override void UpdateTestData(TestData data) } } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(string).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(string).Namespace); + } private static dynamic ToMultiDimensionalArray(dynamic array) { diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/SimpleCipher.cs index c198816a7a..b370bfe811 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/SimpleCipher.cs @@ -42,7 +42,7 @@ protected override void UpdateTestData(TestData data) data.Expected = new UnescapedValue("sut.Key.Substring(0, 10)"); } } - + protected override void UpdateTestMethodBody(TestMethodBody body) { body.Assert = RenderTestMethodBodyAssert(body); @@ -63,6 +63,9 @@ private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody tes } } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(ArgumentException).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(ArgumentException).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/Sublist.cs b/generators/Exercises/Sublist.cs index 015238772a..c159cb0128 100644 --- a/generators/Exercises/Sublist.cs +++ b/generators/Exercises/Sublist.cs @@ -16,7 +16,10 @@ protected override void UpdateTestData(TestData data) data.Expected = new UnescapedValue($"SublistType.{(data.Expected as string).Dehumanize()}"); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(IList).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(IList).Namespace); + } private static UnescapedValue InputValues(int[] list) { diff --git a/generators/Exercises/SumOfMultiples.cs b/generators/Exercises/SumOfMultiples.cs index 80323a4dce..2ce3f67791 100644 --- a/generators/Exercises/SumOfMultiples.cs +++ b/generators/Exercises/SumOfMultiples.cs @@ -12,6 +12,9 @@ protected override void UpdateTestData(TestData data) data.Input["factors"] = ConvertHelper.ToArray(data.Input["factors"]); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index ad40928f02..f83931c32a 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -18,13 +18,13 @@ protected override void UpdateTestData(TestData data) data.Input["rows"] = ConvertHelper.ToMultiLineString(data.Input["rows"], ""); data.Expected = ConvertHelper.ToMultiLineString(data.Expected); } - - protected override IEnumerable AdditionalNamespaces => new[] + + protected override void UpdateNamespaces(ISet namespaces) { - typeof(Array).Namespace, - typeof(Stream).Namespace, - typeof(UTF8Encoding).Namespace - }; + namespaces.Add(typeof(Array).Namespace); + namespaces.Add(typeof(Stream).Namespace); + namespaces.Add(typeof(UTF8Encoding).Namespace); + } protected override void UpdateTestMethodBody(TestMethodBody body) @@ -38,9 +38,14 @@ private static IEnumerable RenderTestMethodBodyAssert() return new[] { TemplateRenderer.RenderInline(template, new { }) }; } - protected override IEnumerable RenderAdditionalMethods() + protected override void UpdateTestClass(TestClass @class) + { + AddRunTallyMethod(@class); + } + + private static void AddRunTallyMethod(TestClass @class) { - const string methods = @" + @class.Methods.Add(@" private string RunTally(string input) { var encoding = new UTF8Encoding(); @@ -51,8 +56,7 @@ private string RunTally(string input) Tournament.Tally(inStream, outStream); return encoding.GetString(outStream.ToArray()); } -}"; - return methods.Split(""); +}"); } } } diff --git a/generators/Exercises/VariableLengthQuantity.cs b/generators/Exercises/VariableLengthQuantity.cs index 0e0be99906..8adb049905 100644 --- a/generators/Exercises/VariableLengthQuantity.cs +++ b/generators/Exercises/VariableLengthQuantity.cs @@ -20,7 +20,10 @@ protected override void UpdateTestData(TestData data) data.Expected = FormatUInt32Array(data.Expected); } - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Array).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + } private static dynamic FormatUInt32Array(dynamic input) { diff --git a/generators/Exercises/WordCount.cs b/generators/Exercises/WordCount.cs index d34412063b..1fbe73cca4 100644 --- a/generators/Exercises/WordCount.cs +++ b/generators/Exercises/WordCount.cs @@ -16,6 +16,9 @@ protected override void UpdateTestData(TestData data) private static dynamic ConvertExpected(dynamic expected) => ((Dictionary)expected).ToDictionary(kv => kv.Key, kv => int.Parse(kv.Value.ToString())); - protected override IEnumerable AdditionalNamespaces => new[] { typeof(Dictionary).Namespace }; + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Dictionary).Namespace); + } } } diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index baf83dd637..c0e4a05a59 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -64,10 +64,10 @@ private static string FormatPosition(dynamic position) private static string FormatCoordinate(dynamic coordinate) => ValueFormatter.Format((coordinate["column"], coordinate["row"])); - protected override IEnumerable AdditionalNamespaces => new[] + protected override void UpdateNamespaces(ISet namespaces) { - typeof(ValueTuple).Namespace, - typeof(Dictionary>).Namespace - }; + namespaces.Add(typeof(ValueTuple).Namespace); + namespaces.Add(typeof(Dictionary>).Namespace); + } } } \ No newline at end of file diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index 383d551c6b..ade59a3256 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -19,90 +19,76 @@ public void Regenerate(CanonicalData canonicalData) ExerciseWriter.WriteToFile(this); } - public string Render() => CreateUpdatedTestClass().Render(); + public string Render() => CreateTestClass().Render(); - protected virtual IEnumerable AdditionalNamespaces => Enumerable.Empty(); - - protected virtual IEnumerable RenderAdditionalMethods() => Array.Empty(); - - private IEnumerable GetNamespaces(IEnumerable testData) + private IList RenderTestMethods(IEnumerable testData) { - var usingNamespaces = new SortedSet { "Xunit" }; - - foreach (var data in testData.Where(x => x.ExceptionThrown != null)) - usingNamespaces.Add(data.ExceptionThrown.Namespace); - - usingNamespaces.UnionWith(AdditionalNamespaces); - - return usingNamespaces; - } - - private IEnumerable RenderTestMethods(IEnumerable testData) - => testData - .Select(RenderTestMethod) - .Concat(RenderAdditionalMethods()) + var testMethods = testData + .Select(CreateTestMethod) .ToArray(); + + Array.ForEach(testMethods, UpdateTestMethod); - private TestClass CreateUpdatedTestClass() - { - var testClass = CreateTestClass(); - UpdateTestClass(testClass); - - return testClass; + return testMethods.Select(testMethod => testMethod.Render()).ToList(); } private TestClass CreateTestClass() { - var testData = CreateUpdatedTestData(); - - return new TestClass + var testData = CreateTestData(); + var testClass = new TestClass { ClassName = Name.ToTestClassName(), Methods = RenderTestMethods(testData), CanonicalDataVersion = _canonicalData.Version, Namespaces = GetNamespaces(testData) }; + + UpdateTestClass(testClass); + return testClass; } - + protected virtual void UpdateTestClass(TestClass @class) { } - private string RenderTestMethod(TestData data, int index) => CreateUpdatedTestMethod(data, index).Render(); - - protected virtual TestMethod CreateUpdatedTestMethod(TestData data, int index) + private ISet GetNamespaces(IEnumerable testData) { - var testMethod = CreateTestMethod(data, index); - UpdateTestMethod(testMethod); + var exceptionNamespaces = testData + .Where(x => x.ExceptionThrown != null) + .Select(x => x.ExceptionThrown.Namespace); + + var defaultNamespaces = new[] { "Xunit" }; - return testMethod; + var namespaces = new SortedSet(defaultNamespaces.Concat(exceptionNamespaces)); + UpdateNamespaces(namespaces); + + return namespaces; } - - protected virtual TestMethod CreateTestMethod(TestData data, int index) => new TestMethod + + protected virtual void UpdateNamespaces(ISet namespaces) + { + } + + private TestMethod CreateTestMethod(TestData data, int index) => new TestMethod { Skip = index > 0, - Name = ToTestMethodName(data), - Body = CreateUpdatedTestMethodBody(data) + Name = data.TestMethod, + Body = CreateTestMethodBody(data) }; protected virtual void UpdateTestMethod(TestMethod method) { } - private static string ToTestMethodName(TestData data) - => data.UseFullDescriptionPath - ? string.Join(" - ", data.DescriptionPath).ToTestMethodName() - : data.Description.ToTestMethodName(); - - private TestMethodBody CreateUpdatedTestMethodBody(TestData data) + private TestMethodBody CreateTestMethodBody(TestData data) { - var testMethodBody = CreateTestMethodBody(data); + var testMethodBody = CreateTestMethodBodyFromData(data); UpdateTestMethodBody(testMethodBody); return testMethodBody; } - private static TestMethodBody CreateTestMethodBody(TestData data) + private static TestMethodBody CreateTestMethodBodyFromData(TestData data) { if (data.ExceptionThrown != null) { @@ -124,19 +110,15 @@ protected virtual void UpdateTestMethodBody(TestMethodBody body) { } - private TestData[] CreateUpdatedTestData() + private TestData[] CreateTestData() { - var testData = CreateTestData(); + var testData = _canonicalData.Cases + .Select(canonicalDataCase => new TestData(_canonicalData, canonicalDataCase)) + .ToArray(); - foreach (var data in testData) - UpdateTestData(data); - + Array.ForEach(testData, UpdateTestData); return testData; } - - private TestData[] CreateTestData() => _canonicalData.Cases.Select(CreateTestData).ToArray(); - - private TestData CreateTestData(CanonicalDataCase canonicalDataCase) => new TestData(_canonicalData, canonicalDataCase); protected virtual void UpdateTestData(TestData data) { diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index 8c68ca198b..ab921cd968 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -6,8 +6,8 @@ public class TestClass { public string ClassName { get; set; } public string CanonicalDataVersion { get; set; } - public IEnumerable Methods { get; set; } - public IEnumerable Namespaces { get; set; } + public IList Methods { get; set; } + public ISet Namespaces { get; set; } public string TemplateName { get; set; } = "TestClass"; public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { ClassName, CanonicalDataVersion, Methods, UsingNamespaces = Namespaces }); diff --git a/generators/Output/TestData.cs b/generators/Output/TestData.cs index f6483f70d1..d16b5e3d18 100644 --- a/generators/Output/TestData.cs +++ b/generators/Output/TestData.cs @@ -41,6 +41,11 @@ public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase public bool UseVariableForTested { get; set; } public bool UseFullDescriptionPath { get; set; } + public string TestMethod => + UseFullDescriptionPath + ? string.Join(" - ", DescriptionPath).ToTestMethodName() + : Description.ToTestMethodName(); + public string TestedClass { get; set; } public string TestedMethod { get; set; } public TestedMethodType TestedMethodType { get; set; } From 0c9ddd86f8b286ce09ae5f0b6b477e2eb437e85b Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 24 Jun 2018 11:18:10 +0200 Subject: [PATCH 24/97] generators: Remove unneeded initialization --- generators/Input/TrackConfigFile.cs | 1 - generators/Output/TestMethodBody.cs | 19 ++++++------------- .../Output/TestMethodBodyWithEqualityCheck.cs | 9 ++++----- .../TestMethodBodyWithExceptionCheck.cs | 1 - 4 files changed, 10 insertions(+), 20 deletions(-) diff --git a/generators/Input/TrackConfigFile.cs b/generators/Input/TrackConfigFile.cs index bd49fe0fa2..c9b85dd828 100644 --- a/generators/Input/TrackConfigFile.cs +++ b/generators/Input/TrackConfigFile.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using Generators.Output; using Newtonsoft.Json; namespace Generators.Input diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index e3dc293deb..a0ef9865ed 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -10,13 +10,9 @@ public abstract class TestMethodBody private const string TestedVariableName = "actual"; private const string ExpectedVariableName = "expected"; - protected TestMethodBody(TestData data) - { - Data = data; - InitializeTemplateParameters(); - } + protected TestMethodBody(TestData data) => Data = data; - public string TemplateName { get; set; } = "TestMethodBody"; + public string TemplateName { get; } = "TestMethodBody"; public TestData Data { get; } @@ -35,6 +31,10 @@ protected TestMethodBody(TestData data) public virtual string Render() { + ArrangeTemplateParameters = ArrangeTemplateParameters ?? new { Variables }; + ActTemplateParameters = ActTemplateParameters ?? new { }; + AssertTemplateParameters = AssertTemplateParameters ?? new { ExpectedParameter, TestedValue }; + Arrange = Arrange ?? RenderTestMethodBodyArrange(); Act = Act ?? RenderTestMethodBodyAct(); Assert = Assert ?? RenderTestMethodBodyAssert(); @@ -42,13 +42,6 @@ public virtual string Render() return TemplateRenderer.RenderPartial(TemplateName, new { Arrange, Act, Assert }); } - protected void InitializeTemplateParameters() - { - ArrangeTemplateParameters = new { Variables }; - ActTemplateParameters = new { }; - AssertTemplateParameters = new { ExpectedParameter, TestedValue }; - } - protected string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; protected string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); protected string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Data.Expected); diff --git a/generators/Output/TestMethodBodyWithEqualityCheck.cs b/generators/Output/TestMethodBodyWithEqualityCheck.cs index cc67e003b6..c2bd4c4890 100644 --- a/generators/Output/TestMethodBodyWithEqualityCheck.cs +++ b/generators/Output/TestMethodBodyWithEqualityCheck.cs @@ -6,14 +6,13 @@ public class TestMethodBodyWithEqualityCheck : TestMethodBody { public TestMethodBodyWithEqualityCheck(TestData data) : base(data) { - Data.UseVariableForExpected = Data.UseVariableForExpected && !ExpectedIsEmptyEnumerable; - InitializeTemplateParameters(); - - AssertTemplateName = ExpectedIsEmptyEnumerable ? "AssertEqual_Empty" : "AssertEqual"; + Data.UseVariableForExpected = Data.UseVariableForExpected && !UseEmptyAssert; + + AssertTemplateName = UseEmptyAssert ? "AssertEqual_Empty" : "AssertEqual"; AssertTemplateParameters = new { ExpectedParameter, TestedValue }; } - private bool ExpectedIsEmptyEnumerable => + private bool UseEmptyAssert => !(Data.Expected is string) && Data.Expected is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; diff --git a/generators/Output/TestMethodBodyWithExceptionCheck.cs b/generators/Output/TestMethodBodyWithExceptionCheck.cs index d947ab7ee1..49905b3cb9 100644 --- a/generators/Output/TestMethodBodyWithExceptionCheck.cs +++ b/generators/Output/TestMethodBodyWithExceptionCheck.cs @@ -6,7 +6,6 @@ public TestMethodBodyWithExceptionCheck(TestData data) : base(data) { Data.UseVariableForExpected = false; Data.UseVariableForTested = false; - InitializeTemplateParameters(); AssertTemplateName = "AssertThrowsException"; AssertTemplateParameters = new { ExceptionType, TestedValue }; From 4ce46a99efd5af4bf8dd156a6758541c1c2be894 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 24 Jun 2018 11:26:37 +0200 Subject: [PATCH 25/97] generators: Rename ExerciseWriter to TestClassFile --- generators/GeneratorExercise.cs | 11 ++++++----- generators/Output/ExerciseWriter.cs | 20 -------------------- generators/Output/TestClass.cs | 1 + generators/Output/TestClassFile.cs | 24 ++++++++++++++++++++++++ 4 files changed, 31 insertions(+), 25 deletions(-) delete mode 100644 generators/Output/ExerciseWriter.cs create mode 100644 generators/Output/TestClassFile.cs diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index ade59a3256..ac50c31dec 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -16,11 +16,11 @@ public void Regenerate(CanonicalData canonicalData) { _canonicalData = canonicalData; - ExerciseWriter.WriteToFile(this); + var testClass = CreateTestClass(); + var testClassFile = new TestClassFile(testClass); + testClassFile.Write(); } - public string Render() => CreateTestClass().Render(); - private IList RenderTestMethods(IEnumerable testData) { var testMethods = testData @@ -37,9 +37,10 @@ private TestClass CreateTestClass() var testData = CreateTestData(); var testClass = new TestClass { - ClassName = Name.ToTestClassName(), - Methods = RenderTestMethods(testData), + Exercise = _canonicalData.Exercise, CanonicalDataVersion = _canonicalData.Version, + ClassName = _canonicalData.Exercise.ToTestClassName(), + Methods = RenderTestMethods(testData), Namespaces = GetNamespaces(testData) }; diff --git a/generators/Output/ExerciseWriter.cs b/generators/Output/ExerciseWriter.cs deleted file mode 100644 index c85da596c2..0000000000 --- a/generators/Output/ExerciseWriter.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.IO; - -namespace Generators.Output -{ - public class ExerciseWriter - { - public static void WriteToFile(GeneratorExercise generatorExercise) - { - var testClassFilePath = TestClassFilePath(generatorExercise); - var testClassContents = generatorExercise.Render(); - - Directory.CreateDirectory(Path.GetDirectoryName(testClassFilePath)); - File.WriteAllText(testClassFilePath, testClassContents); - } - - private static string TestClassFilePath(GeneratorExercise generatorExercise) => Path.Combine("..", "exercises", generatorExercise.Name, TestClassFileName(generatorExercise)); - - private static string TestClassFileName(GeneratorExercise generatorExercise) => $"{generatorExercise.Name.ToTestClassName()}.cs"; - } -} \ No newline at end of file diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index ab921cd968..f85a2eea67 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -4,6 +4,7 @@ namespace Generators.Output { public class TestClass { + public string Exercise { get; set; } public string ClassName { get; set; } public string CanonicalDataVersion { get; set; } public IList Methods { get; set; } diff --git a/generators/Output/TestClassFile.cs b/generators/Output/TestClassFile.cs new file mode 100644 index 0000000000..c5e3a566be --- /dev/null +++ b/generators/Output/TestClassFile.cs @@ -0,0 +1,24 @@ +using System.IO; + +namespace Generators.Output +{ + public class TestClassFile + { + private readonly TestClass _testClass; + + public TestClassFile(TestClass testClass) => _testClass = testClass; + + public void Write() + { + var testClassFilePath = TestClassFilePath; + var testClassContents = _testClass.Render(); + + Directory.CreateDirectory(Path.GetDirectoryName(testClassFilePath)); + File.WriteAllText(testClassFilePath, testClassContents); + } + + private string TestClassFilePath => Path.Combine("..", "exercises", _testClass.Exercise, TestClassFileName); + + private string TestClassFileName => $"{_testClass.ClassName}.cs"; + } +} \ No newline at end of file From 51caf2277a352e76cb849e7f73424db2fba0671b Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 24 Jun 2018 11:31:07 +0200 Subject: [PATCH 26/97] generators: Move template specific code to separate namespace --- generators/Exercises/Allergies.cs | 1 + generators/Exercises/BinarySearchTree.cs | 1 + generators/Exercises/Bowling.cs | 1 + generators/Exercises/Clock.cs | 1 + generators/Exercises/ComplexNumbers.cs | 1 + generators/Exercises/Connect.cs | 1 + generators/Exercises/Meetup.cs | 1 + generators/Exercises/Minesweeper.cs | 1 + generators/Exercises/NucleotideCount.cs | 1 + generators/Exercises/OcrNumbers.cs | 1 + generators/Exercises/QueenAttack.cs | 1 + generators/Exercises/RationalNumbers.cs | 1 + generators/Exercises/RobotSimulator.cs | 1 + generators/Exercises/RunLengthEncoding.cs | 1 + generators/Exercises/Tournament.cs | 1 + generators/Exercises/TwoBucket.cs | 1 + generators/Output/{ => Templates}/IndentFilter.cs | 2 +- generators/Output/{ => Templates}/TemplateRenderer.cs | 4 ++-- generators/Output/TestClass.cs | 1 + generators/Output/TestMethod.cs | 2 ++ generators/Output/TestMethodBody.cs | 1 + 21 files changed, 23 insertions(+), 3 deletions(-) rename generators/Output/{ => Templates}/IndentFilter.cs (89%) rename generators/Output/{ => Templates}/TemplateRenderer.cs (90%) diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Allergies.cs index ad965885c4..0c9ffed939 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Allergies.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/BinarySearchTree.cs index 263374c4f1..7ced8061bc 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/BinarySearchTree.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Text; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Bowling.cs index f618642377..7fb9d5e48b 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Bowling.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Text; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Clock.cs index 95dee1fb41..698133cf18 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Clock.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/ComplexNumbers.cs index 6f3f996f43..f8189419e5 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/ComplexNumbers.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using Generators.Output; +using Generators.Output.Templates; using Newtonsoft.Json.Linq; namespace Generators.Exercises diff --git a/generators/Exercises/Connect.cs b/generators/Exercises/Connect.cs index a84a8fbce1..bd21dbd0ce 100644 --- a/generators/Exercises/Connect.cs +++ b/generators/Exercises/Connect.cs @@ -1,5 +1,6 @@ using System.Collections; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Meetup.cs index 2af5ebd65c..50b75242cc 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Meetup.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Generators.Output; +using Generators.Output.Templates; using Humanizer; namespace Generators.Exercises diff --git a/generators/Exercises/Minesweeper.cs b/generators/Exercises/Minesweeper.cs index b68387f775..1a90fd1ceb 100644 --- a/generators/Exercises/Minesweeper.cs +++ b/generators/Exercises/Minesweeper.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Generators.Output; +using Generators.Output.Templates; using Newtonsoft.Json.Linq; namespace Generators.Exercises diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index e03b383721..92637a17d4 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/OcrNumbers.cs b/generators/Exercises/OcrNumbers.cs index 95ca83b9e6..4eb237772f 100644 --- a/generators/Exercises/OcrNumbers.cs +++ b/generators/Exercises/OcrNumbers.cs @@ -2,6 +2,7 @@ using System.Collections; using System.Collections.Generic; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/QueenAttack.cs b/generators/Exercises/QueenAttack.cs index 33ab8db864..5213d7d744 100644 --- a/generators/Exercises/QueenAttack.cs +++ b/generators/Exercises/QueenAttack.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/RationalNumbers.cs b/generators/Exercises/RationalNumbers.cs index 2f3f812780..7dae494f68 100644 --- a/generators/Exercises/RationalNumbers.cs +++ b/generators/Exercises/RationalNumbers.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index 2d8bb7adad..725dc4c307 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Text; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/RunLengthEncoding.cs index beb83556ef..51ee5406ff 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/RunLengthEncoding.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index f83931c32a..4935c9b7ca 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -4,6 +4,7 @@ using System.Text; using Generators.Input; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Exercises/TwoBucket.cs b/generators/Exercises/TwoBucket.cs index 3f4cf8a2ed..1860150a9e 100644 --- a/generators/Exercises/TwoBucket.cs +++ b/generators/Exercises/TwoBucket.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Generators.Output; +using Generators.Output.Templates; namespace Generators.Exercises { diff --git a/generators/Output/IndentFilter.cs b/generators/Output/Templates/IndentFilter.cs similarity index 89% rename from generators/Output/IndentFilter.cs rename to generators/Output/Templates/IndentFilter.cs index 03251d3159..8e72109e81 100644 --- a/generators/Output/IndentFilter.cs +++ b/generators/Output/Templates/IndentFilter.cs @@ -1,7 +1,7 @@ using System; using System.Linq; -namespace Generators.Output +namespace Generators.Output.Templates { public static class IndentFilter { diff --git a/generators/Output/TemplateRenderer.cs b/generators/Output/Templates/TemplateRenderer.cs similarity index 90% rename from generators/Output/TemplateRenderer.cs rename to generators/Output/Templates/TemplateRenderer.cs index 573b40af9d..ab7297b32a 100644 --- a/generators/Output/TemplateRenderer.cs +++ b/generators/Output/Templates/TemplateRenderer.cs @@ -2,11 +2,11 @@ using DotLiquid; using DotLiquid.FileSystems; -namespace Generators.Output +namespace Generators.Output.Templates { public static class TemplateRenderer { - private static readonly string EmbeddedTemplatesNamespace = $"{typeof(TemplateRenderer).Namespace}.Templates"; + private static readonly string EmbeddedTemplatesNamespace = typeof(TemplateRenderer).Namespace; static TemplateRenderer() { diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index f85a2eea67..da79fb725d 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using Generators.Output.Templates; namespace Generators.Output { diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index 3679441ea8..47f4d2b1c8 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -1,3 +1,5 @@ +using Generators.Output.Templates; + namespace Generators.Output { public class TestMethod diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index a0ef9865ed..a76635b761 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Generators.Output.Templates; namespace Generators.Output { From 9fe5b48c2e398fff9ef0f6e5eda67622c981f2c2 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 24 Jun 2018 11:34:16 +0200 Subject: [PATCH 27/97] generators: Move helpers to separate namespace --- generators/CustomExercise.cs | 3 ++- generators/ExerciseCollection.cs | 1 + generators/Exercises/AllYourBase.cs | 1 + generators/Exercises/BeerSong.cs | 3 ++- generators/Exercises/BinarySearch.cs | 1 + generators/Exercises/BookStore.cs | 1 + generators/Exercises/FoodChain.cs | 3 ++- generators/Exercises/GoCounting.cs | 1 + generators/Exercises/House.cs | 3 ++- generators/Exercises/NucleotideCount.cs | 1 + generators/Exercises/Proverb.cs | 1 + generators/Exercises/RobotSimulator.cs | 1 + generators/Exercises/SumOfMultiples.cs | 1 + generators/Exercises/Tournament.cs | 1 + generators/Exercises/Transpose.cs | 1 + generators/Exercises/TwelveDays.cs | 3 ++- generators/Exercises/WordSearch.cs | 1 + generators/GeneratorExercise.cs | 1 + generators/{Input => Helpers}/ConvertHelper.cs | 2 +- generators/{Output => Helpers}/NameExtensions.cs | 2 +- generators/{Output => Helpers}/TypesExtensions.cs | 2 +- generators/Output/TestData.cs | 1 + generators/Output/TestMethodBody.cs | 1 + generators/Output/ValueFormatter.cs | 1 + generators/Program.cs | 1 + 25 files changed, 30 insertions(+), 8 deletions(-) rename generators/{Input => Helpers}/ConvertHelper.cs (94%) rename generators/{Output => Helpers}/NameExtensions.cs (97%) rename generators/{Output => Helpers}/TypesExtensions.cs (92%) diff --git a/generators/CustomExercise.cs b/generators/CustomExercise.cs index 3eae5f16ce..27855beb5c 100644 --- a/generators/CustomExercise.cs +++ b/generators/CustomExercise.cs @@ -1,4 +1,5 @@ -using Generators.Output; +using Generators.Helpers; +using Generators.Output; namespace Generators { diff --git a/generators/ExerciseCollection.cs b/generators/ExerciseCollection.cs index fd56bd3e62..2563d40296 100644 --- a/generators/ExerciseCollection.cs +++ b/generators/ExerciseCollection.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using Generators.Helpers; using Generators.Input; using Generators.Output; diff --git a/generators/Exercises/AllYourBase.cs b/generators/Exercises/AllYourBase.cs index a01445dc11..931cfc36af 100644 --- a/generators/Exercises/AllYourBase.cs +++ b/generators/Exercises/AllYourBase.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Generators.Helpers; using Generators.Input; using Generators.Output; diff --git a/generators/Exercises/BeerSong.cs b/generators/Exercises/BeerSong.cs index b3b5568eaf..9c41f669ea 100644 --- a/generators/Exercises/BeerSong.cs +++ b/generators/Exercises/BeerSong.cs @@ -1,4 +1,5 @@ -using Generators.Input; +using Generators.Helpers; +using Generators.Input; using Generators.Output; namespace Generators.Exercises diff --git a/generators/Exercises/BinarySearch.cs b/generators/Exercises/BinarySearch.cs index 7c4d305408..7204d8adf6 100644 --- a/generators/Exercises/BinarySearch.cs +++ b/generators/Exercises/BinarySearch.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Generators.Helpers; using Generators.Input; using Generators.Output; diff --git a/generators/Exercises/BookStore.cs b/generators/Exercises/BookStore.cs index 149ac0a37f..bf55f4be93 100644 --- a/generators/Exercises/BookStore.cs +++ b/generators/Exercises/BookStore.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Generators.Helpers; using Generators.Input; using Generators.Output; diff --git a/generators/Exercises/FoodChain.cs b/generators/Exercises/FoodChain.cs index b2216c7535..ae4fde4c34 100644 --- a/generators/Exercises/FoodChain.cs +++ b/generators/Exercises/FoodChain.cs @@ -1,4 +1,5 @@ -using Generators.Input; +using Generators.Helpers; +using Generators.Input; using Generators.Output; namespace Generators.Exercises diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/GoCounting.cs index 4c54b001ea..48d8893479 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/GoCounting.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Generators.Helpers; using Generators.Input; using Generators.Output; using Humanizer; diff --git a/generators/Exercises/House.cs b/generators/Exercises/House.cs index a3ffff2b57..201634d4ea 100644 --- a/generators/Exercises/House.cs +++ b/generators/Exercises/House.cs @@ -1,4 +1,5 @@ -using Generators.Input; +using Generators.Helpers; +using Generators.Input; using Generators.Output; namespace Generators.Exercises diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/NucleotideCount.cs index 92637a17d4..9e36908d35 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/NucleotideCount.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using Generators.Helpers; using Generators.Output; using Generators.Output.Templates; diff --git a/generators/Exercises/Proverb.cs b/generators/Exercises/Proverb.cs index 1df38a90a9..f147b455ea 100644 --- a/generators/Exercises/Proverb.cs +++ b/generators/Exercises/Proverb.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Generators.Helpers; using Generators.Input; using Generators.Output; diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/RobotSimulator.cs index 725dc4c307..037134ec3b 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/RobotSimulator.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Text; +using Generators.Helpers; using Generators.Output; using Generators.Output.Templates; diff --git a/generators/Exercises/SumOfMultiples.cs b/generators/Exercises/SumOfMultiples.cs index 2ce3f67791..7eae84b4b3 100644 --- a/generators/Exercises/SumOfMultiples.cs +++ b/generators/Exercises/SumOfMultiples.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using Generators.Helpers; using Generators.Input; using Generators.Output; diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Tournament.cs index 4935c9b7ca..c3c5f87b38 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Tournament.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Text; +using Generators.Helpers; using Generators.Input; using Generators.Output; using Generators.Output.Templates; diff --git a/generators/Exercises/Transpose.cs b/generators/Exercises/Transpose.cs index ddef564d29..d90b9f0980 100644 --- a/generators/Exercises/Transpose.cs +++ b/generators/Exercises/Transpose.cs @@ -1,3 +1,4 @@ +using Generators.Helpers; using Generators.Input; using Generators.Output; diff --git a/generators/Exercises/TwelveDays.cs b/generators/Exercises/TwelveDays.cs index 7dc0e5ea04..597432b3f7 100644 --- a/generators/Exercises/TwelveDays.cs +++ b/generators/Exercises/TwelveDays.cs @@ -1,4 +1,5 @@ -using Generators.Input; +using Generators.Helpers; +using Generators.Input; using Generators.Output; namespace Generators.Exercises diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/WordSearch.cs index c0e4a05a59..9296069b99 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/WordSearch.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Generators.Helpers; using Generators.Input; using Generators.Output; diff --git a/generators/GeneratorExercise.cs b/generators/GeneratorExercise.cs index ac50c31dec..a2f33c57d6 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/GeneratorExercise.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Generators.Helpers; using Generators.Input; using Generators.Output; diff --git a/generators/Input/ConvertHelper.cs b/generators/Helpers/ConvertHelper.cs similarity index 94% rename from generators/Input/ConvertHelper.cs rename to generators/Helpers/ConvertHelper.cs index e055b353f5..81623efe48 100644 --- a/generators/Input/ConvertHelper.cs +++ b/generators/Helpers/ConvertHelper.cs @@ -1,4 +1,4 @@ -namespace Generators.Input +namespace Generators.Helpers { public static class ConvertHelper { diff --git a/generators/Output/NameExtensions.cs b/generators/Helpers/NameExtensions.cs similarity index 97% rename from generators/Output/NameExtensions.cs rename to generators/Helpers/NameExtensions.cs index fa3d5ae768..6fb14370e1 100644 --- a/generators/Output/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -2,7 +2,7 @@ using System.Text.RegularExpressions; using Humanizer; -namespace Generators.Output +namespace Generators.Helpers { public static class NameExtensions { diff --git a/generators/Output/TypesExtensions.cs b/generators/Helpers/TypesExtensions.cs similarity index 92% rename from generators/Output/TypesExtensions.cs rename to generators/Helpers/TypesExtensions.cs index 9880aa684b..13220f43f1 100644 --- a/generators/Output/TypesExtensions.cs +++ b/generators/Helpers/TypesExtensions.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Generators.Output +namespace Generators.Helpers { public static class TypesExtensions { diff --git a/generators/Output/TestData.cs b/generators/Output/TestData.cs index d16b5e3d18..741b8adc53 100644 --- a/generators/Output/TestData.cs +++ b/generators/Output/TestData.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Generators.Helpers; using Generators.Input; namespace Generators.Output diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index a76635b761..befada2ed8 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Generators.Helpers; using Generators.Output.Templates; namespace Generators.Output diff --git a/generators/Output/ValueFormatter.cs b/generators/Output/ValueFormatter.cs index bd973ff969..e0956a8628 100644 --- a/generators/Output/ValueFormatter.cs +++ b/generators/Output/ValueFormatter.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using Generators.Helpers; using Newtonsoft.Json.Linq; namespace Generators.Output diff --git a/generators/Program.cs b/generators/Program.cs index 3c5d2880ea..3b5f2643be 100644 --- a/generators/Program.cs +++ b/generators/Program.cs @@ -1,5 +1,6 @@ using System; using CommandLine; +using Generators.Helpers; using Generators.Input; using Generators.Output; using Serilog; From 761ee4498543bbca8c6007d951457591e9621d50 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 24 Jun 2018 11:36:28 +0200 Subject: [PATCH 28/97] generators: Remove unneeded generator scripts --- generators/generate.ps1 | 2 -- generators/generate.sh | 4 ---- 2 files changed, 6 deletions(-) delete mode 100644 generators/generate.ps1 delete mode 100644 generators/generate.sh diff --git a/generators/generate.ps1 b/generators/generate.ps1 deleted file mode 100644 index e43799710c..0000000000 --- a/generators/generate.ps1 +++ /dev/null @@ -1,2 +0,0 @@ -Invoke-Expression "dotnet restore" -Invoke-Expression "dotnet run" \ No newline at end of file diff --git a/generators/generate.sh b/generators/generate.sh deleted file mode 100644 index 2f8a56bcd6..0000000000 --- a/generators/generate.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env bash - -exec dotnet restore -exec dotnet run \ No newline at end of file From 5c246fb83d9e9c1e7c054184d4129145638917d4 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 24 Jun 2018 11:43:45 +0200 Subject: [PATCH 29/97] generators: Update namespace --- generators/{ => Exercises}/CustomExercise.cs | 5 ++--- generators/{ => Exercises}/DeprecatedExercise.cs | 2 +- generators/{ => Exercises}/Exercise.cs | 2 +- generators/{ => Exercises}/ExerciseCollection.cs | 7 +++---- generators/{ => Exercises}/GeneratorExercise.cs | 8 ++++---- generators/Exercises/{ => Generators}/Acronym.cs | 2 +- generators/Exercises/{ => Generators}/AllYourBase.cs | 7 +++---- generators/Exercises/{ => Generators}/Allergies.cs | 6 +++--- generators/Exercises/{ => Generators}/Alphametics.cs | 4 ++-- generators/Exercises/{ => Generators}/Anagram.cs | 4 ++-- .../Exercises/{ => Generators}/ArmstrongNumbers.cs | 2 +- generators/Exercises/{ => Generators}/AtbashCipher.cs | 2 +- generators/Exercises/{ => Generators}/BeerSong.cs | 7 +++---- generators/Exercises/{ => Generators}/BinarySearch.cs | 7 +++---- .../Exercises/{ => Generators}/BinarySearchTree.cs | 6 +++--- generators/Exercises/{ => Generators}/Bob.cs | 2 +- generators/Exercises/{ => Generators}/BookStore.cs | 7 +++---- generators/Exercises/{ => Generators}/Bowling.cs | 6 +++--- generators/Exercises/{ => Generators}/BracketPush.cs | 4 ++-- generators/Exercises/{ => Generators}/Change.cs | 4 ++-- generators/Exercises/{ => Generators}/CircularBuffer.cs | 4 ++-- generators/Exercises/{ => Generators}/Clock.cs | 6 +++--- .../Exercises/{ => Generators}/CollatzConjecture.cs | 4 ++-- generators/Exercises/{ => Generators}/ComplexNumbers.cs | 6 +++--- generators/Exercises/{ => Generators}/Connect.cs | 6 +++--- generators/Exercises/{ => Generators}/CryptoSquare.cs | 4 ++-- generators/Exercises/{ => Generators}/CustomSet.cs | 4 ++-- generators/Exercises/{ => Generators}/Diamond.cs | 2 +- .../Exercises/{ => Generators}/DifferenceOfSquares.cs | 4 ++-- generators/Exercises/{ => Generators}/Dominoes.cs | 4 ++-- generators/Exercises/{ => Generators}/Etl.cs | 4 ++-- generators/Exercises/{ => Generators}/FlattenArray.cs | 4 ++-- generators/Exercises/{ => Generators}/FoodChain.cs | 7 +++---- generators/Exercises/{ => Generators}/Forth.cs | 4 ++-- generators/Exercises/{ => Generators}/Gigasecond.cs | 4 ++-- generators/Exercises/{ => Generators}/GoCounting.cs | 7 +++---- generators/Exercises/{ => Generators}/Grains.cs | 4 ++-- generators/Exercises/{ => Generators}/Grep.cs | 4 ++-- generators/Exercises/{ => Generators}/Hamming.cs | 4 ++-- generators/Exercises/{ => Generators}/HelloWorld.cs | 2 +- generators/Exercises/{ => Generators}/House.cs | 7 +++---- generators/Exercises/{ => Generators}/IsbnVerifier.cs | 2 +- generators/Exercises/{ => Generators}/Isogram.cs | 2 +- .../Exercises/{ => Generators}/KindergartenGarden.cs | 4 ++-- .../Exercises/{ => Generators}/LargestSeriesProduct.cs | 4 ++-- generators/Exercises/{ => Generators}/Leap.cs | 4 ++-- generators/Exercises/{ => Generators}/ListOps.cs | 4 ++-- generators/Exercises/{ => Generators}/Luhn.cs | 4 ++-- generators/Exercises/{ => Generators}/Markdown.cs | 4 ++-- generators/Exercises/{ => Generators}/Matrix.cs | 4 ++-- generators/Exercises/{ => Generators}/Meetup.cs | 6 +++--- generators/Exercises/{ => Generators}/Minesweeper.cs | 6 +++--- generators/Exercises/{ => Generators}/NthPrime.cs | 4 ++-- generators/Exercises/{ => Generators}/NucleotideCount.cs | 8 ++++---- generators/Exercises/{ => Generators}/OcrNumbers.cs | 6 +++--- .../Exercises/{ => Generators}/PalindromeProducts.cs | 4 ++-- generators/Exercises/{ => Generators}/Pangram.cs | 2 +- generators/Exercises/{ => Generators}/PascalsTriangle.cs | 4 ++-- generators/Exercises/{ => Generators}/PerfectNumbers.cs | 4 ++-- generators/Exercises/{ => Generators}/PhoneNumber.cs | 4 ++-- generators/Exercises/{ => Generators}/PigLatin.cs | 2 +- generators/Exercises/{ => Generators}/Poker.cs | 4 ++-- generators/Exercises/{ => Generators}/Pov.cs | 4 ++-- generators/Exercises/{ => Generators}/PrimeFactors.cs | 2 +- .../Exercises/{ => Generators}/ProteinTranslation.cs | 2 +- generators/Exercises/{ => Generators}/Proverb.cs | 7 +++---- generators/Exercises/{ => Generators}/QueenAttack.cs | 6 +++--- generators/Exercises/{ => Generators}/RailFenceCipher.cs | 4 ++-- generators/Exercises/{ => Generators}/Raindrops.cs | 2 +- generators/Exercises/{ => Generators}/RationalNumbers.cs | 6 +++--- generators/Exercises/{ => Generators}/React.cs | 4 ++-- generators/Exercises/{ => Generators}/Rectangles.cs | 4 ++-- generators/Exercises/{ => Generators}/ReverseString.cs | 2 +- .../Exercises/{ => Generators}/RnaTranscription.cs | 4 ++-- generators/Exercises/{ => Generators}/RobotSimulator.cs | 8 ++++---- generators/Exercises/{ => Generators}/RomanNumerals.cs | 4 ++-- .../Exercises/{ => Generators}/RotationalCipher.cs | 2 +- .../Exercises/{ => Generators}/RunLengthEncoding.cs | 6 +++--- generators/Exercises/{ => Generators}/SaddlePoints.cs | 4 ++-- generators/Exercises/{ => Generators}/Say.cs | 4 ++-- generators/Exercises/{ => Generators}/ScaleGenerator.cs | 4 ++-- generators/Exercises/{ => Generators}/ScrabbleScore.cs | 2 +- generators/Exercises/{ => Generators}/SecretHandshake.cs | 2 +- generators/Exercises/{ => Generators}/Sieve.cs | 4 ++-- generators/Exercises/{ => Generators}/SimpleCipher.cs | 4 ++-- generators/Exercises/{ => Generators}/SpaceAge.cs | 4 ++-- generators/Exercises/{ => Generators}/SpiralMatrix.cs | 4 ++-- generators/Exercises/{ => Generators}/Sublist.cs | 4 ++-- generators/Exercises/{ => Generators}/SumOfMultiples.cs | 7 +++---- generators/Exercises/{ => Generators}/Tournament.cs | 9 ++++----- generators/Exercises/{ => Generators}/Transpose.cs | 7 +++---- generators/Exercises/{ => Generators}/Triangle.cs | 4 ++-- generators/Exercises/{ => Generators}/TwelveDays.cs | 7 +++---- generators/Exercises/{ => Generators}/TwoBucket.cs | 6 +++--- generators/Exercises/{ => Generators}/TwoFer.cs | 4 ++-- .../Exercises/{ => Generators}/VariableLengthQuantity.cs | 4 ++-- generators/Exercises/{ => Generators}/WordCount.cs | 4 ++-- generators/Exercises/{ => Generators}/WordSearch.cs | 7 +++---- generators/Exercises/{ => Generators}/Wordy.cs | 4 ++-- generators/Exercises/{ => Generators}/Yacht.cs | 4 ++-- generators/Exercises/{ => Generators}/ZebraPuzzle.cs | 4 ++-- generators/Exercises/{ => Generators}/Zipper.cs | 4 ++-- generators/{ => Exercises}/MissingDataExercise.cs | 2 +- generators/{ => Exercises}/TestedMethodType.cs | 2 +- generators/{ => Exercises}/UnimplementedExercise.cs | 2 +- generators/GeneratorStatus.cs | 2 +- generators/Generators.csproj | 1 + generators/Helpers/ConvertHelper.cs | 2 +- generators/Helpers/NameExtensions.cs | 2 +- generators/Helpers/TypesExtensions.cs | 2 +- generators/Input/CanonicalData.cs | 2 +- generators/Input/CanonicalDataCase.cs | 2 +- generators/Input/CanonicalDataCaseParser.cs | 2 +- generators/Input/CanonicalDataFile.cs | 2 +- generators/Input/CanonicalDataParser.cs | 2 +- generators/Input/TrackConfigFile.cs | 2 +- generators/Options.cs | 2 +- generators/Output/FormattingExtensions.cs | 2 +- generators/Output/Templates/IndentFilter.cs | 2 +- generators/Output/Templates/TemplateRenderer.cs | 2 +- generators/Output/TestClass.cs | 4 ++-- generators/Output/TestClassFile.cs | 2 +- generators/Output/TestData.cs | 7 ++++--- generators/Output/TestMethod.cs | 4 ++-- generators/Output/TestMethodBody.cs | 7 ++++--- generators/Output/TestMethodBodyWithBooleanCheck.cs | 2 +- generators/Output/TestMethodBodyWithEqualityCheck.cs | 2 +- generators/Output/TestMethodBodyWithExceptionCheck.cs | 2 +- generators/Output/TestMethodBodyWithNullCheck.cs | 2 +- generators/Output/UnescapedValue.cs | 2 +- generators/Output/ValueFormatter.cs | 4 ++-- generators/Program.cs | 8 ++++---- 132 files changed, 261 insertions(+), 273 deletions(-) rename generators/{ => Exercises}/CustomExercise.cs (64%) rename generators/{ => Exercises}/DeprecatedExercise.cs (81%) rename generators/{ => Exercises}/Exercise.cs (70%) rename generators/{ => Exercises}/ExerciseCollection.cs (95%) rename generators/{ => Exercises}/GeneratorExercise.cs (96%) rename generators/Exercises/{ => Generators}/Acronym.cs (54%) rename generators/Exercises/{ => Generators}/AllYourBase.cs (85%) rename generators/Exercises/{ => Generators}/Allergies.cs (92%) rename generators/Exercises/{ => Generators}/Alphametics.cs (92%) rename generators/Exercises/{ => Generators}/Anagram.cs (79%) rename generators/Exercises/{ => Generators}/ArmstrongNumbers.cs (57%) rename generators/Exercises/{ => Generators}/AtbashCipher.cs (56%) rename generators/Exercises/{ => Generators}/BeerSong.cs (70%) rename generators/Exercises/{ => Generators}/BinarySearch.cs (83%) rename generators/Exercises/{ => Generators}/BinarySearchTree.cs (96%) rename generators/Exercises/{ => Generators}/Bob.cs (52%) rename generators/Exercises/{ => Generators}/BookStore.cs (84%) rename generators/Exercises/{ => Generators}/Bowling.cs (97%) rename generators/Exercises/{ => Generators}/BracketPush.cs (77%) rename generators/Exercises/{ => Generators}/Change.cs (82%) rename generators/Exercises/{ => Generators}/CircularBuffer.cs (96%) rename generators/Exercises/{ => Generators}/Clock.cs (96%) rename generators/Exercises/{ => Generators}/CollatzConjecture.cs (77%) rename generators/Exercises/{ => Generators}/ComplexNumbers.cs (96%) rename generators/Exercises/{ => Generators}/Connect.cs (92%) rename generators/Exercises/{ => Generators}/CryptoSquare.cs (75%) rename generators/Exercises/{ => Generators}/CustomSet.cs (94%) rename generators/Exercises/{ => Generators}/Diamond.cs (82%) rename generators/Exercises/{ => Generators}/DifferenceOfSquares.cs (88%) rename generators/Exercises/{ => Generators}/Dominoes.cs (93%) rename generators/Exercises/{ => Generators}/Etl.cs (93%) rename generators/Exercises/{ => Generators}/FlattenArray.cs (90%) rename generators/Exercises/{ => Generators}/FoodChain.cs (79%) rename generators/Exercises/{ => Generators}/Forth.cs (85%) rename generators/Exercises/{ => Generators}/Gigasecond.cs (92%) rename generators/Exercises/{ => Generators}/GoCounting.cs (97%) rename generators/Exercises/{ => Generators}/Grains.cs (85%) rename generators/Exercises/{ => Generators}/Grep.cs (98%) rename generators/Exercises/{ => Generators}/Hamming.cs (76%) rename generators/Exercises/{ => Generators}/HelloWorld.cs (57%) rename generators/Exercises/{ => Generators}/House.cs (78%) rename generators/Exercises/{ => Generators}/IsbnVerifier.cs (56%) rename generators/Exercises/{ => Generators}/Isogram.cs (56%) rename generators/Exercises/{ => Generators}/KindergartenGarden.cs (90%) rename generators/Exercises/{ => Generators}/LargestSeriesProduct.cs (83%) rename generators/Exercises/{ => Generators}/Leap.cs (69%) rename generators/Exercises/{ => Generators}/ListOps.cs (98%) rename generators/Exercises/{ => Generators}/Luhn.cs (70%) rename generators/Exercises/{ => Generators}/Markdown.cs (81%) rename generators/Exercises/{ => Generators}/Matrix.cs (83%) rename generators/Exercises/{ => Generators}/Meetup.cs (93%) rename generators/Exercises/{ => Generators}/Minesweeper.cs (91%) rename generators/Exercises/{ => Generators}/NthPrime.cs (80%) rename generators/Exercises/{ => Generators}/NucleotideCount.cs (93%) rename generators/Exercises/{ => Generators}/OcrNumbers.cs (90%) rename generators/Exercises/{ => Generators}/PalindromeProducts.cs (95%) rename generators/Exercises/{ => Generators}/Pangram.cs (54%) rename generators/Exercises/{ => Generators}/PascalsTriangle.cs (86%) rename generators/Exercises/{ => Generators}/PerfectNumbers.cs (85%) rename generators/Exercises/{ => Generators}/PhoneNumber.cs (79%) rename generators/Exercises/{ => Generators}/PigLatin.cs (54%) rename generators/Exercises/{ => Generators}/Poker.cs (77%) rename generators/Exercises/{ => Generators}/Pov.cs (94%) rename generators/Exercises/{ => Generators}/PrimeFactors.cs (56%) rename generators/Exercises/{ => Generators}/ProteinTranslation.cs (58%) rename generators/Exercises/{ => Generators}/Proverb.cs (83%) rename generators/Exercises/{ => Generators}/QueenAttack.cs (96%) rename generators/Exercises/{ => Generators}/RailFenceCipher.cs (79%) rename generators/Exercises/{ => Generators}/Raindrops.cs (55%) rename generators/Exercises/{ => Generators}/RationalNumbers.cs (96%) rename generators/Exercises/{ => Generators}/React.cs (98%) rename generators/Exercises/{ => Generators}/Rectangles.cs (87%) rename generators/Exercises/{ => Generators}/ReverseString.cs (57%) rename generators/Exercises/{ => Generators}/RnaTranscription.cs (77%) rename generators/Exercises/{ => Generators}/RobotSimulator.cs (96%) rename generators/Exercises/{ => Generators}/RomanNumerals.cs (76%) rename generators/Exercises/{ => Generators}/RotationalCipher.cs (59%) rename generators/Exercises/{ => Generators}/RunLengthEncoding.cs (91%) rename generators/Exercises/{ => Generators}/SaddlePoints.cs (95%) rename generators/Exercises/{ => Generators}/Say.cs (79%) rename generators/Exercises/{ => Generators}/ScaleGenerator.cs (71%) rename generators/Exercises/{ => Generators}/ScrabbleScore.cs (56%) rename generators/Exercises/{ => Generators}/SecretHandshake.cs (57%) rename generators/Exercises/{ => Generators}/Sieve.cs (80%) rename generators/Exercises/{ => Generators}/SimpleCipher.cs (96%) rename generators/Exercises/{ => Generators}/SpaceAge.cs (79%) rename generators/Exercises/{ => Generators}/SpiralMatrix.cs (92%) rename generators/Exercises/{ => Generators}/Sublist.cs (92%) rename generators/Exercises/{ => Generators}/SumOfMultiples.cs (80%) rename generators/Exercises/{ => Generators}/Tournament.cs (92%) rename generators/Exercises/{ => Generators}/Transpose.cs (80%) rename generators/Exercises/{ => Generators}/Triangle.cs (90%) rename generators/Exercises/{ => Generators}/TwelveDays.cs (79%) rename generators/Exercises/{ => Generators}/TwoBucket.cs (94%) rename generators/Exercises/{ => Generators}/TwoFer.cs (69%) rename generators/Exercises/{ => Generators}/VariableLengthQuantity.cs (94%) rename generators/Exercises/{ => Generators}/WordCount.cs (90%) rename generators/Exercises/{ => Generators}/WordSearch.cs (96%) rename generators/Exercises/{ => Generators}/Wordy.cs (76%) rename generators/Exercises/{ => Generators}/Yacht.cs (84%) rename generators/Exercises/{ => Generators}/ZebraPuzzle.cs (79%) rename generators/Exercises/{ => Generators}/Zipper.cs (97%) rename generators/{ => Exercises}/MissingDataExercise.cs (81%) rename generators/{ => Exercises}/TestedMethodType.cs (73%) rename generators/{ => Exercises}/UnimplementedExercise.cs (82%) diff --git a/generators/CustomExercise.cs b/generators/Exercises/CustomExercise.cs similarity index 64% rename from generators/CustomExercise.cs rename to generators/Exercises/CustomExercise.cs index 27855beb5c..e7ce08c115 100644 --- a/generators/CustomExercise.cs +++ b/generators/Exercises/CustomExercise.cs @@ -1,7 +1,6 @@ -using Generators.Helpers; -using Generators.Output; +using Exercism.CSharp.Helpers; -namespace Generators +namespace Exercism.CSharp.Exercises { public abstract class CustomExercise : Exercise { diff --git a/generators/DeprecatedExercise.cs b/generators/Exercises/DeprecatedExercise.cs similarity index 81% rename from generators/DeprecatedExercise.cs rename to generators/Exercises/DeprecatedExercise.cs index eb4e1d7219..2535769eca 100644 --- a/generators/DeprecatedExercise.cs +++ b/generators/Exercises/DeprecatedExercise.cs @@ -1,4 +1,4 @@ -namespace Generators +namespace Exercism.CSharp.Exercises { public class DeprecatedExercise : Exercise { diff --git a/generators/Exercise.cs b/generators/Exercises/Exercise.cs similarity index 70% rename from generators/Exercise.cs rename to generators/Exercises/Exercise.cs index 1bae8f399c..5dfb2c72d6 100644 --- a/generators/Exercise.cs +++ b/generators/Exercises/Exercise.cs @@ -1,4 +1,4 @@ -namespace Generators +namespace Exercism.CSharp.Exercises { public abstract class Exercise { diff --git a/generators/ExerciseCollection.cs b/generators/Exercises/ExerciseCollection.cs similarity index 95% rename from generators/ExerciseCollection.cs rename to generators/Exercises/ExerciseCollection.cs index 2563d40296..bfd20c2c8a 100644 --- a/generators/ExerciseCollection.cs +++ b/generators/Exercises/ExerciseCollection.cs @@ -3,11 +3,10 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Input; -namespace Generators +namespace Exercism.CSharp.Exercises { public class ExerciseCollection : IEnumerable { diff --git a/generators/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs similarity index 96% rename from generators/GeneratorExercise.cs rename to generators/Exercises/GeneratorExercise.cs index a2f33c57d6..7caf2fdd08 100644 --- a/generators/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Input; +using Exercism.CSharp.Output; -namespace Generators +namespace Exercism.CSharp.Exercises { public abstract class GeneratorExercise : Exercise { diff --git a/generators/Exercises/Acronym.cs b/generators/Exercises/Generators/Acronym.cs similarity index 54% rename from generators/Exercises/Acronym.cs rename to generators/Exercises/Generators/Acronym.cs index 1846d6196c..c499d3b646 100644 --- a/generators/Exercises/Acronym.cs +++ b/generators/Exercises/Generators/Acronym.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Acronym : GeneratorExercise { diff --git a/generators/Exercises/AllYourBase.cs b/generators/Exercises/Generators/AllYourBase.cs similarity index 85% rename from generators/Exercises/AllYourBase.cs rename to generators/Exercises/Generators/AllYourBase.cs index 931cfc36af..90df667c66 100644 --- a/generators/Exercises/AllYourBase.cs +++ b/generators/Exercises/Generators/AllYourBase.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class AllYourBase : GeneratorExercise { diff --git a/generators/Exercises/Allergies.cs b/generators/Exercises/Generators/Allergies.cs similarity index 92% rename from generators/Exercises/Allergies.cs rename to generators/Exercises/Generators/Allergies.cs index 0c9ffed939..f4ab24c025 100644 --- a/generators/Exercises/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Allergies : GeneratorExercise { diff --git a/generators/Exercises/Alphametics.cs b/generators/Exercises/Generators/Alphametics.cs similarity index 92% rename from generators/Exercises/Alphametics.cs rename to generators/Exercises/Generators/Alphametics.cs index d1aacdfbab..ed6918ee7f 100644 --- a/generators/Exercises/Alphametics.cs +++ b/generators/Exercises/Generators/Alphametics.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Alphametics : GeneratorExercise { diff --git a/generators/Exercises/Anagram.cs b/generators/Exercises/Generators/Anagram.cs similarity index 79% rename from generators/Exercises/Anagram.cs rename to generators/Exercises/Generators/Anagram.cs index a711195c59..578b7b197d 100644 --- a/generators/Exercises/Anagram.cs +++ b/generators/Exercises/Generators/Anagram.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Anagram : GeneratorExercise { diff --git a/generators/Exercises/ArmstrongNumbers.cs b/generators/Exercises/Generators/ArmstrongNumbers.cs similarity index 57% rename from generators/Exercises/ArmstrongNumbers.cs rename to generators/Exercises/Generators/ArmstrongNumbers.cs index e3235cb727..b6528565a8 100644 --- a/generators/Exercises/ArmstrongNumbers.cs +++ b/generators/Exercises/Generators/ArmstrongNumbers.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class ArmstrongNumbers : GeneratorExercise { diff --git a/generators/Exercises/AtbashCipher.cs b/generators/Exercises/Generators/AtbashCipher.cs similarity index 56% rename from generators/Exercises/AtbashCipher.cs rename to generators/Exercises/Generators/AtbashCipher.cs index a863a35ac9..6d50d69339 100644 --- a/generators/Exercises/AtbashCipher.cs +++ b/generators/Exercises/Generators/AtbashCipher.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class AtbashCipher : GeneratorExercise { diff --git a/generators/Exercises/BeerSong.cs b/generators/Exercises/Generators/BeerSong.cs similarity index 70% rename from generators/Exercises/BeerSong.cs rename to generators/Exercises/Generators/BeerSong.cs index 9c41f669ea..a9340be08c 100644 --- a/generators/Exercises/BeerSong.cs +++ b/generators/Exercises/Generators/BeerSong.cs @@ -1,8 +1,7 @@ -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class BeerSong : GeneratorExercise { diff --git a/generators/Exercises/BinarySearch.cs b/generators/Exercises/Generators/BinarySearch.cs similarity index 83% rename from generators/Exercises/BinarySearch.cs rename to generators/Exercises/Generators/BinarySearch.cs index 7204d8adf6..471e625596 100644 --- a/generators/Exercises/BinarySearch.cs +++ b/generators/Exercises/Generators/BinarySearch.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class BinarySearch : GeneratorExercise { diff --git a/generators/Exercises/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs similarity index 96% rename from generators/Exercises/BinarySearchTree.cs rename to generators/Exercises/Generators/BinarySearchTree.cs index 7ced8061bc..12bc88d69a 100644 --- a/generators/Exercises/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class ExpectedDataBinaryTree { diff --git a/generators/Exercises/Bob.cs b/generators/Exercises/Generators/Bob.cs similarity index 52% rename from generators/Exercises/Bob.cs rename to generators/Exercises/Generators/Bob.cs index b8377340d4..5d7b21b71d 100644 --- a/generators/Exercises/Bob.cs +++ b/generators/Exercises/Generators/Bob.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Bob : GeneratorExercise { diff --git a/generators/Exercises/BookStore.cs b/generators/Exercises/Generators/BookStore.cs similarity index 84% rename from generators/Exercises/BookStore.cs rename to generators/Exercises/Generators/BookStore.cs index bf55f4be93..7aa4febd74 100644 --- a/generators/Exercises/BookStore.cs +++ b/generators/Exercises/Generators/BookStore.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class BookStore : GeneratorExercise { diff --git a/generators/Exercises/Bowling.cs b/generators/Exercises/Generators/Bowling.cs similarity index 97% rename from generators/Exercises/Bowling.cs rename to generators/Exercises/Generators/Bowling.cs index 7fb9d5e48b..a1feda8e73 100644 --- a/generators/Exercises/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Text; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Bowling : GeneratorExercise { diff --git a/generators/Exercises/BracketPush.cs b/generators/Exercises/Generators/BracketPush.cs similarity index 77% rename from generators/Exercises/BracketPush.cs rename to generators/Exercises/Generators/BracketPush.cs index a27ca6cd63..86e9a80efd 100644 --- a/generators/Exercises/BracketPush.cs +++ b/generators/Exercises/Generators/BracketPush.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class BracketPush : GeneratorExercise { diff --git a/generators/Exercises/Change.cs b/generators/Exercises/Generators/Change.cs similarity index 82% rename from generators/Exercises/Change.cs rename to generators/Exercises/Generators/Change.cs index 26ca481738..f2e187be8b 100644 --- a/generators/Exercises/Change.cs +++ b/generators/Exercises/Generators/Change.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Change : GeneratorExercise { diff --git a/generators/Exercises/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs similarity index 96% rename from generators/Exercises/CircularBuffer.cs rename to generators/Exercises/Generators/CircularBuffer.cs index 2c01d0629a..a4644b8d56 100644 --- a/generators/Exercises/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class CircularBuffer : GeneratorExercise { diff --git a/generators/Exercises/Clock.cs b/generators/Exercises/Generators/Clock.cs similarity index 96% rename from generators/Exercises/Clock.cs rename to generators/Exercises/Generators/Clock.cs index 698133cf18..902ad819a7 100644 --- a/generators/Exercises/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Clock : GeneratorExercise { diff --git a/generators/Exercises/CollatzConjecture.cs b/generators/Exercises/Generators/CollatzConjecture.cs similarity index 77% rename from generators/Exercises/CollatzConjecture.cs rename to generators/Exercises/Generators/CollatzConjecture.cs index 78b28fbb16..14bf6ee4ae 100644 --- a/generators/Exercises/CollatzConjecture.cs +++ b/generators/Exercises/Generators/CollatzConjecture.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class CollatzConjecture : GeneratorExercise { diff --git a/generators/Exercises/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs similarity index 96% rename from generators/Exercises/ComplexNumbers.cs rename to generators/Exercises/Generators/ComplexNumbers.cs index f8189419e5..715e7868a7 100644 --- a/generators/Exercises/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; using Newtonsoft.Json.Linq; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class ComplexNumbers : GeneratorExercise { diff --git a/generators/Exercises/Connect.cs b/generators/Exercises/Generators/Connect.cs similarity index 92% rename from generators/Exercises/Connect.cs rename to generators/Exercises/Generators/Connect.cs index bd21dbd0ce..ad7e63fbaa 100644 --- a/generators/Exercises/Connect.cs +++ b/generators/Exercises/Generators/Connect.cs @@ -1,8 +1,8 @@ using System.Collections; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Connect : GeneratorExercise { diff --git a/generators/Exercises/CryptoSquare.cs b/generators/Exercises/Generators/CryptoSquare.cs similarity index 75% rename from generators/Exercises/CryptoSquare.cs rename to generators/Exercises/Generators/CryptoSquare.cs index 632d79f52e..73b37cd865 100644 --- a/generators/Exercises/CryptoSquare.cs +++ b/generators/Exercises/Generators/CryptoSquare.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class CryptoSquare : GeneratorExercise { diff --git a/generators/Exercises/CustomSet.cs b/generators/Exercises/Generators/CustomSet.cs similarity index 94% rename from generators/Exercises/CustomSet.cs rename to generators/Exercises/Generators/CustomSet.cs index 45aed2db07..bafa3332d1 100644 --- a/generators/Exercises/CustomSet.cs +++ b/generators/Exercises/Generators/CustomSet.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class CustomSet : GeneratorExercise { diff --git a/generators/Exercises/Diamond.cs b/generators/Exercises/Generators/Diamond.cs similarity index 82% rename from generators/Exercises/Diamond.cs rename to generators/Exercises/Generators/Diamond.cs index 9bb2fea8e5..787196d117 100644 --- a/generators/Exercises/Diamond.cs +++ b/generators/Exercises/Generators/Diamond.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { // This class derives from CustomExercise instead of GeneratorExercise // as it has custom (property-based) tests that cannot be generated from diff --git a/generators/Exercises/DifferenceOfSquares.cs b/generators/Exercises/Generators/DifferenceOfSquares.cs similarity index 88% rename from generators/Exercises/DifferenceOfSquares.cs rename to generators/Exercises/Generators/DifferenceOfSquares.cs index 6e6eb9cc89..a3d43b36c8 100644 --- a/generators/Exercises/DifferenceOfSquares.cs +++ b/generators/Exercises/Generators/DifferenceOfSquares.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class DifferenceOfSquares : GeneratorExercise { diff --git a/generators/Exercises/Dominoes.cs b/generators/Exercises/Generators/Dominoes.cs similarity index 93% rename from generators/Exercises/Dominoes.cs rename to generators/Exercises/Generators/Dominoes.cs index b99e6532b3..07896b1a11 100644 --- a/generators/Exercises/Dominoes.cs +++ b/generators/Exercises/Generators/Dominoes.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; using Newtonsoft.Json.Linq; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Dominoes : GeneratorExercise { diff --git a/generators/Exercises/Etl.cs b/generators/Exercises/Generators/Etl.cs similarity index 93% rename from generators/Exercises/Etl.cs rename to generators/Exercises/Generators/Etl.cs index 845b72cfb3..caab37b717 100644 --- a/generators/Exercises/Etl.cs +++ b/generators/Exercises/Generators/Etl.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Etl : GeneratorExercise { diff --git a/generators/Exercises/FlattenArray.cs b/generators/Exercises/Generators/FlattenArray.cs similarity index 90% rename from generators/Exercises/FlattenArray.cs rename to generators/Exercises/Generators/FlattenArray.cs index 8bbd515585..ad264fde29 100644 --- a/generators/Exercises/FlattenArray.cs +++ b/generators/Exercises/Generators/FlattenArray.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class FlattenArray : GeneratorExercise { diff --git a/generators/Exercises/FoodChain.cs b/generators/Exercises/Generators/FoodChain.cs similarity index 79% rename from generators/Exercises/FoodChain.cs rename to generators/Exercises/Generators/FoodChain.cs index ae4fde4c34..ff2b4c4c59 100644 --- a/generators/Exercises/FoodChain.cs +++ b/generators/Exercises/Generators/FoodChain.cs @@ -1,8 +1,7 @@ -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class FoodChain : GeneratorExercise { diff --git a/generators/Exercises/Forth.cs b/generators/Exercises/Generators/Forth.cs similarity index 85% rename from generators/Exercises/Forth.cs rename to generators/Exercises/Generators/Forth.cs index 8eea6bc3f1..e88812958e 100644 --- a/generators/Exercises/Forth.cs +++ b/generators/Exercises/Generators/Forth.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Forth : GeneratorExercise { diff --git a/generators/Exercises/Gigasecond.cs b/generators/Exercises/Generators/Gigasecond.cs similarity index 92% rename from generators/Exercises/Gigasecond.cs rename to generators/Exercises/Generators/Gigasecond.cs index ddf48fef05..7ae498cd40 100644 --- a/generators/Exercises/Gigasecond.cs +++ b/generators/Exercises/Generators/Gigasecond.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Gigasecond : GeneratorExercise { diff --git a/generators/Exercises/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs similarity index 97% rename from generators/Exercises/GoCounting.cs rename to generators/Exercises/Generators/GoCounting.cs index 48d8893479..b2c5d80adc 100644 --- a/generators/Exercises/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -1,13 +1,12 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; using Humanizer; using Newtonsoft.Json.Linq; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class GoCounting : GeneratorExercise { diff --git a/generators/Exercises/Grains.cs b/generators/Exercises/Generators/Grains.cs similarity index 85% rename from generators/Exercises/Grains.cs rename to generators/Exercises/Generators/Grains.cs index ee0455f14a..88dff4cb07 100644 --- a/generators/Exercises/Grains.cs +++ b/generators/Exercises/Generators/Grains.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Grains : GeneratorExercise { diff --git a/generators/Exercises/Grep.cs b/generators/Exercises/Generators/Grep.cs similarity index 98% rename from generators/Exercises/Grep.cs rename to generators/Exercises/Generators/Grep.cs index 844546a771..9cc79daa56 100644 --- a/generators/Exercises/Grep.cs +++ b/generators/Exercises/Generators/Grep.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Grep : GeneratorExercise { diff --git a/generators/Exercises/Hamming.cs b/generators/Exercises/Generators/Hamming.cs similarity index 76% rename from generators/Exercises/Hamming.cs rename to generators/Exercises/Generators/Hamming.cs index 0c459bebed..c6adb5efda 100644 --- a/generators/Exercises/Hamming.cs +++ b/generators/Exercises/Generators/Hamming.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Hamming : GeneratorExercise { diff --git a/generators/Exercises/HelloWorld.cs b/generators/Exercises/Generators/HelloWorld.cs similarity index 57% rename from generators/Exercises/HelloWorld.cs rename to generators/Exercises/Generators/HelloWorld.cs index c9d2389994..1ff6c0962e 100644 --- a/generators/Exercises/HelloWorld.cs +++ b/generators/Exercises/Generators/HelloWorld.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class HelloWorld : GeneratorExercise { diff --git a/generators/Exercises/House.cs b/generators/Exercises/Generators/House.cs similarity index 78% rename from generators/Exercises/House.cs rename to generators/Exercises/Generators/House.cs index 201634d4ea..101938a37f 100644 --- a/generators/Exercises/House.cs +++ b/generators/Exercises/Generators/House.cs @@ -1,8 +1,7 @@ -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class House : GeneratorExercise { diff --git a/generators/Exercises/IsbnVerifier.cs b/generators/Exercises/Generators/IsbnVerifier.cs similarity index 56% rename from generators/Exercises/IsbnVerifier.cs rename to generators/Exercises/Generators/IsbnVerifier.cs index 64449be9a4..28574ad5fa 100644 --- a/generators/Exercises/IsbnVerifier.cs +++ b/generators/Exercises/Generators/IsbnVerifier.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class IsbnVerifier : GeneratorExercise { diff --git a/generators/Exercises/Isogram.cs b/generators/Exercises/Generators/Isogram.cs similarity index 56% rename from generators/Exercises/Isogram.cs rename to generators/Exercises/Generators/Isogram.cs index c775f93cf5..451708229c 100644 --- a/generators/Exercises/Isogram.cs +++ b/generators/Exercises/Generators/Isogram.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Isogram : GeneratorExercise { diff --git a/generators/Exercises/KindergartenGarden.cs b/generators/Exercises/Generators/KindergartenGarden.cs similarity index 90% rename from generators/Exercises/KindergartenGarden.cs rename to generators/Exercises/Generators/KindergartenGarden.cs index df7b806a87..b21b260ffe 100644 --- a/generators/Exercises/KindergartenGarden.cs +++ b/generators/Exercises/Generators/KindergartenGarden.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; using Humanizer; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class KindergartenGarden : GeneratorExercise { diff --git a/generators/Exercises/LargestSeriesProduct.cs b/generators/Exercises/Generators/LargestSeriesProduct.cs similarity index 83% rename from generators/Exercises/LargestSeriesProduct.cs rename to generators/Exercises/Generators/LargestSeriesProduct.cs index c4edfcfe0c..9d906181ba 100644 --- a/generators/Exercises/LargestSeriesProduct.cs +++ b/generators/Exercises/Generators/LargestSeriesProduct.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class LargestSeriesProduct : GeneratorExercise { diff --git a/generators/Exercises/Leap.cs b/generators/Exercises/Generators/Leap.cs similarity index 69% rename from generators/Exercises/Leap.cs rename to generators/Exercises/Generators/Leap.cs index 3ce0e329a0..1a37da5ef8 100644 --- a/generators/Exercises/Leap.cs +++ b/generators/Exercises/Generators/Leap.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Leap : GeneratorExercise { diff --git a/generators/Exercises/ListOps.cs b/generators/Exercises/Generators/ListOps.cs similarity index 98% rename from generators/Exercises/ListOps.cs rename to generators/Exercises/Generators/ListOps.cs index 45fb436804..8972d7d31f 100644 --- a/generators/Exercises/ListOps.cs +++ b/generators/Exercises/Generators/ListOps.cs @@ -2,10 +2,10 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; using Newtonsoft.Json.Linq; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class ListOps : GeneratorExercise { diff --git a/generators/Exercises/Luhn.cs b/generators/Exercises/Generators/Luhn.cs similarity index 70% rename from generators/Exercises/Luhn.cs rename to generators/Exercises/Generators/Luhn.cs index ff0fb1f419..124e032e66 100644 --- a/generators/Exercises/Luhn.cs +++ b/generators/Exercises/Generators/Luhn.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Luhn : GeneratorExercise { diff --git a/generators/Exercises/Markdown.cs b/generators/Exercises/Generators/Markdown.cs similarity index 81% rename from generators/Exercises/Markdown.cs rename to generators/Exercises/Generators/Markdown.cs index 9b033b1f6c..72f2bc6a6c 100644 --- a/generators/Exercises/Markdown.cs +++ b/generators/Exercises/Generators/Markdown.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Markdown : GeneratorExercise { diff --git a/generators/Exercises/Matrix.cs b/generators/Exercises/Generators/Matrix.cs similarity index 83% rename from generators/Exercises/Matrix.cs rename to generators/Exercises/Generators/Matrix.cs index 6eed35a30f..f837da89a4 100644 --- a/generators/Exercises/Matrix.cs +++ b/generators/Exercises/Generators/Matrix.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Matrix : GeneratorExercise { diff --git a/generators/Exercises/Meetup.cs b/generators/Exercises/Generators/Meetup.cs similarity index 93% rename from generators/Exercises/Meetup.cs rename to generators/Exercises/Generators/Meetup.cs index 50b75242cc..79a9f0068b 100644 --- a/generators/Exercises/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; using Humanizer; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Meetup : GeneratorExercise { diff --git a/generators/Exercises/Minesweeper.cs b/generators/Exercises/Generators/Minesweeper.cs similarity index 91% rename from generators/Exercises/Minesweeper.cs rename to generators/Exercises/Generators/Minesweeper.cs index 1a90fd1ceb..5e5ed6ccc7 100644 --- a/generators/Exercises/Minesweeper.cs +++ b/generators/Exercises/Generators/Minesweeper.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; using Newtonsoft.Json.Linq; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Minesweeper : GeneratorExercise { diff --git a/generators/Exercises/NthPrime.cs b/generators/Exercises/Generators/NthPrime.cs similarity index 80% rename from generators/Exercises/NthPrime.cs rename to generators/Exercises/Generators/NthPrime.cs index f4553c39cf..1a7f678c2c 100644 --- a/generators/Exercises/NthPrime.cs +++ b/generators/Exercises/Generators/NthPrime.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class NthPrime : GeneratorExercise { diff --git a/generators/Exercises/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs similarity index 93% rename from generators/Exercises/NucleotideCount.cs rename to generators/Exercises/Generators/NucleotideCount.cs index 9e36908d35..cd379f267f 100644 --- a/generators/Exercises/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Linq; -using Generators.Helpers; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class NucleotideCount : GeneratorExercise { diff --git a/generators/Exercises/OcrNumbers.cs b/generators/Exercises/Generators/OcrNumbers.cs similarity index 90% rename from generators/Exercises/OcrNumbers.cs rename to generators/Exercises/Generators/OcrNumbers.cs index 4eb237772f..d28f2c59b1 100644 --- a/generators/Exercises/OcrNumbers.cs +++ b/generators/Exercises/Generators/OcrNumbers.cs @@ -1,10 +1,10 @@ using System; using System.Collections; using System.Collections.Generic; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class OcrNumbers : GeneratorExercise { diff --git a/generators/Exercises/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs similarity index 95% rename from generators/Exercises/PalindromeProducts.cs rename to generators/Exercises/Generators/PalindromeProducts.cs index f57ce7acd0..5951632a2c 100644 --- a/generators/Exercises/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; using Newtonsoft.Json.Linq; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class PalindromeProducts : GeneratorExercise { diff --git a/generators/Exercises/Pangram.cs b/generators/Exercises/Generators/Pangram.cs similarity index 54% rename from generators/Exercises/Pangram.cs rename to generators/Exercises/Generators/Pangram.cs index 032e8c741e..72811a1ea6 100644 --- a/generators/Exercises/Pangram.cs +++ b/generators/Exercises/Generators/Pangram.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Pangram : GeneratorExercise { diff --git a/generators/Exercises/PascalsTriangle.cs b/generators/Exercises/Generators/PascalsTriangle.cs similarity index 86% rename from generators/Exercises/PascalsTriangle.cs rename to generators/Exercises/Generators/PascalsTriangle.cs index 1cbd05d546..20ad61e651 100644 --- a/generators/Exercises/PascalsTriangle.cs +++ b/generators/Exercises/Generators/PascalsTriangle.cs @@ -1,8 +1,8 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; using Newtonsoft.Json.Linq; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class PascalsTriangle : GeneratorExercise { diff --git a/generators/Exercises/PerfectNumbers.cs b/generators/Exercises/Generators/PerfectNumbers.cs similarity index 85% rename from generators/Exercises/PerfectNumbers.cs rename to generators/Exercises/Generators/PerfectNumbers.cs index c1e438c4a5..b884776187 100644 --- a/generators/Exercises/PerfectNumbers.cs +++ b/generators/Exercises/Generators/PerfectNumbers.cs @@ -1,8 +1,8 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; using Humanizer; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class PerfectNumbers : GeneratorExercise { diff --git a/generators/Exercises/PhoneNumber.cs b/generators/Exercises/Generators/PhoneNumber.cs similarity index 79% rename from generators/Exercises/PhoneNumber.cs rename to generators/Exercises/Generators/PhoneNumber.cs index de49184cb5..9542f8468d 100644 --- a/generators/Exercises/PhoneNumber.cs +++ b/generators/Exercises/Generators/PhoneNumber.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class PhoneNumber : GeneratorExercise { diff --git a/generators/Exercises/PigLatin.cs b/generators/Exercises/Generators/PigLatin.cs similarity index 54% rename from generators/Exercises/PigLatin.cs rename to generators/Exercises/Generators/PigLatin.cs index 1dcfacb4fc..7bb47b3043 100644 --- a/generators/Exercises/PigLatin.cs +++ b/generators/Exercises/Generators/PigLatin.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class PigLatin : GeneratorExercise { diff --git a/generators/Exercises/Poker.cs b/generators/Exercises/Generators/Poker.cs similarity index 77% rename from generators/Exercises/Poker.cs rename to generators/Exercises/Generators/Poker.cs index 941bba5208..3460574e7b 100644 --- a/generators/Exercises/Poker.cs +++ b/generators/Exercises/Generators/Poker.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Poker : GeneratorExercise { diff --git a/generators/Exercises/Pov.cs b/generators/Exercises/Generators/Pov.cs similarity index 94% rename from generators/Exercises/Pov.cs rename to generators/Exercises/Generators/Pov.cs index abb0cef7fe..bbad024a6f 100644 --- a/generators/Exercises/Pov.cs +++ b/generators/Exercises/Generators/Pov.cs @@ -1,9 +1,9 @@ using System; using System.Linq; using System.Text; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Pov : GeneratorExercise { diff --git a/generators/Exercises/PrimeFactors.cs b/generators/Exercises/Generators/PrimeFactors.cs similarity index 56% rename from generators/Exercises/PrimeFactors.cs rename to generators/Exercises/Generators/PrimeFactors.cs index d16a8e744a..9bf490d197 100644 --- a/generators/Exercises/PrimeFactors.cs +++ b/generators/Exercises/Generators/PrimeFactors.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class PrimeFactors : GeneratorExercise { diff --git a/generators/Exercises/ProteinTranslation.cs b/generators/Exercises/Generators/ProteinTranslation.cs similarity index 58% rename from generators/Exercises/ProteinTranslation.cs rename to generators/Exercises/Generators/ProteinTranslation.cs index 932ebe262a..05bbe01925 100644 --- a/generators/Exercises/ProteinTranslation.cs +++ b/generators/Exercises/Generators/ProteinTranslation.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class ProteinTranslation : GeneratorExercise { diff --git a/generators/Exercises/Proverb.cs b/generators/Exercises/Generators/Proverb.cs similarity index 83% rename from generators/Exercises/Proverb.cs rename to generators/Exercises/Generators/Proverb.cs index f147b455ea..90ceecae52 100644 --- a/generators/Exercises/Proverb.cs +++ b/generators/Exercises/Generators/Proverb.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Proverb : GeneratorExercise { diff --git a/generators/Exercises/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs similarity index 96% rename from generators/Exercises/QueenAttack.cs rename to generators/Exercises/Generators/QueenAttack.cs index 5213d7d744..a197af700d 100644 --- a/generators/Exercises/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class QueenAttack : GeneratorExercise { diff --git a/generators/Exercises/RailFenceCipher.cs b/generators/Exercises/Generators/RailFenceCipher.cs similarity index 79% rename from generators/Exercises/RailFenceCipher.cs rename to generators/Exercises/Generators/RailFenceCipher.cs index 47a60dd447..c1fbcbb068 100644 --- a/generators/Exercises/RailFenceCipher.cs +++ b/generators/Exercises/Generators/RailFenceCipher.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class RailFenceCipher : GeneratorExercise { diff --git a/generators/Exercises/Raindrops.cs b/generators/Exercises/Generators/Raindrops.cs similarity index 55% rename from generators/Exercises/Raindrops.cs rename to generators/Exercises/Generators/Raindrops.cs index f2eb064e5d..21d7f356b7 100644 --- a/generators/Exercises/Raindrops.cs +++ b/generators/Exercises/Generators/Raindrops.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Raindrops : GeneratorExercise { diff --git a/generators/Exercises/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs similarity index 96% rename from generators/Exercises/RationalNumbers.cs rename to generators/Exercises/Generators/RationalNumbers.cs index 7dae494f68..a40a00b6cf 100644 --- a/generators/Exercises/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public struct RationalNumber { diff --git a/generators/Exercises/React.cs b/generators/Exercises/Generators/React.cs similarity index 98% rename from generators/Exercises/React.cs rename to generators/Exercises/Generators/React.cs index dfa50b3161..efe1d28672 100644 --- a/generators/Exercises/React.cs +++ b/generators/Exercises/Generators/React.cs @@ -3,10 +3,10 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; -using Generators.Output; +using Exercism.CSharp.Output; using Humanizer; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class React : GeneratorExercise { diff --git a/generators/Exercises/Rectangles.cs b/generators/Exercises/Generators/Rectangles.cs similarity index 87% rename from generators/Exercises/Rectangles.cs rename to generators/Exercises/Generators/Rectangles.cs index df6c165e99..951c171514 100644 --- a/generators/Exercises/Rectangles.cs +++ b/generators/Exercises/Generators/Rectangles.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Rectangles : GeneratorExercise { diff --git a/generators/Exercises/ReverseString.cs b/generators/Exercises/Generators/ReverseString.cs similarity index 57% rename from generators/Exercises/ReverseString.cs rename to generators/Exercises/Generators/ReverseString.cs index 59132fd5ab..76bb7e04f7 100644 --- a/generators/Exercises/ReverseString.cs +++ b/generators/Exercises/Generators/ReverseString.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class ReverseString : GeneratorExercise { diff --git a/generators/Exercises/RnaTranscription.cs b/generators/Exercises/Generators/RnaTranscription.cs similarity index 77% rename from generators/Exercises/RnaTranscription.cs rename to generators/Exercises/Generators/RnaTranscription.cs index c96664bd1d..eb1a44c367 100644 --- a/generators/Exercises/RnaTranscription.cs +++ b/generators/Exercises/Generators/RnaTranscription.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class RnaTranscription : GeneratorExercise { diff --git a/generators/Exercises/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs similarity index 96% rename from generators/Exercises/RobotSimulator.cs rename to generators/Exercises/Generators/RobotSimulator.cs index 037134ec3b..76ffb481b5 100644 --- a/generators/Exercises/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Text; -using Generators.Helpers; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class RobotSimulator : GeneratorExercise { diff --git a/generators/Exercises/RomanNumerals.cs b/generators/Exercises/Generators/RomanNumerals.cs similarity index 76% rename from generators/Exercises/RomanNumerals.cs rename to generators/Exercises/Generators/RomanNumerals.cs index 1f31b91c2c..b18316784a 100644 --- a/generators/Exercises/RomanNumerals.cs +++ b/generators/Exercises/Generators/RomanNumerals.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class RomanNumerals : GeneratorExercise { diff --git a/generators/Exercises/RotationalCipher.cs b/generators/Exercises/Generators/RotationalCipher.cs similarity index 59% rename from generators/Exercises/RotationalCipher.cs rename to generators/Exercises/Generators/RotationalCipher.cs index e8fcccbbf4..b491972cb3 100644 --- a/generators/Exercises/RotationalCipher.cs +++ b/generators/Exercises/Generators/RotationalCipher.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class RotationalCipher : GeneratorExercise { diff --git a/generators/Exercises/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs similarity index 91% rename from generators/Exercises/RunLengthEncoding.cs rename to generators/Exercises/Generators/RunLengthEncoding.cs index 51ee5406ff..586e2eef5d 100644 --- a/generators/Exercises/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class RunLengthEncoding : GeneratorExercise { diff --git a/generators/Exercises/SaddlePoints.cs b/generators/Exercises/Generators/SaddlePoints.cs similarity index 95% rename from generators/Exercises/SaddlePoints.cs rename to generators/Exercises/Generators/SaddlePoints.cs index 31c18a12a9..20991ac52e 100644 --- a/generators/Exercises/SaddlePoints.cs +++ b/generators/Exercises/Generators/SaddlePoints.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; -using Generators.Output; +using Exercism.CSharp.Output; using Newtonsoft.Json.Linq; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class SaddlePoints : GeneratorExercise { diff --git a/generators/Exercises/Say.cs b/generators/Exercises/Generators/Say.cs similarity index 79% rename from generators/Exercises/Say.cs rename to generators/Exercises/Generators/Say.cs index 90e8b350c1..b5dab4cb01 100644 --- a/generators/Exercises/Say.cs +++ b/generators/Exercises/Generators/Say.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Say : GeneratorExercise { diff --git a/generators/Exercises/ScaleGenerator.cs b/generators/Exercises/Generators/ScaleGenerator.cs similarity index 71% rename from generators/Exercises/ScaleGenerator.cs rename to generators/Exercises/Generators/ScaleGenerator.cs index 39bcce2fdd..a4a8e6aa12 100644 --- a/generators/Exercises/ScaleGenerator.cs +++ b/generators/Exercises/Generators/ScaleGenerator.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class ScaleGenerator : GeneratorExercise { diff --git a/generators/Exercises/ScrabbleScore.cs b/generators/Exercises/Generators/ScrabbleScore.cs similarity index 56% rename from generators/Exercises/ScrabbleScore.cs rename to generators/Exercises/Generators/ScrabbleScore.cs index bf156d878d..cb8435c1c8 100644 --- a/generators/Exercises/ScrabbleScore.cs +++ b/generators/Exercises/Generators/ScrabbleScore.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class ScrabbleScore : GeneratorExercise { diff --git a/generators/Exercises/SecretHandshake.cs b/generators/Exercises/Generators/SecretHandshake.cs similarity index 57% rename from generators/Exercises/SecretHandshake.cs rename to generators/Exercises/Generators/SecretHandshake.cs index 32d93e1195..830da3066f 100644 --- a/generators/Exercises/SecretHandshake.cs +++ b/generators/Exercises/Generators/SecretHandshake.cs @@ -1,4 +1,4 @@ -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class SecretHandshake : GeneratorExercise { diff --git a/generators/Exercises/Sieve.cs b/generators/Exercises/Generators/Sieve.cs similarity index 80% rename from generators/Exercises/Sieve.cs rename to generators/Exercises/Generators/Sieve.cs index e8b3dd20ba..734d7b94ce 100644 --- a/generators/Exercises/Sieve.cs +++ b/generators/Exercises/Generators/Sieve.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Sieve : GeneratorExercise { diff --git a/generators/Exercises/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs similarity index 96% rename from generators/Exercises/SimpleCipher.cs rename to generators/Exercises/Generators/SimpleCipher.cs index b370bfe811..65a24a3533 100644 --- a/generators/Exercises/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class SimpleCipher : GeneratorExercise { diff --git a/generators/Exercises/SpaceAge.cs b/generators/Exercises/Generators/SpaceAge.cs similarity index 79% rename from generators/Exercises/SpaceAge.cs rename to generators/Exercises/Generators/SpaceAge.cs index 93996569a0..a2f4b21f3b 100644 --- a/generators/Exercises/SpaceAge.cs +++ b/generators/Exercises/Generators/SpaceAge.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class SpaceAge : GeneratorExercise { diff --git a/generators/Exercises/SpiralMatrix.cs b/generators/Exercises/Generators/SpiralMatrix.cs similarity index 92% rename from generators/Exercises/SpiralMatrix.cs rename to generators/Exercises/Generators/SpiralMatrix.cs index a8031e891d..177d7dde2e 100644 --- a/generators/Exercises/SpiralMatrix.cs +++ b/generators/Exercises/Generators/SpiralMatrix.cs @@ -1,8 +1,8 @@ using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; using Newtonsoft.Json.Linq; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class SpiralMatrix : GeneratorExercise { diff --git a/generators/Exercises/Sublist.cs b/generators/Exercises/Generators/Sublist.cs similarity index 92% rename from generators/Exercises/Sublist.cs rename to generators/Exercises/Generators/Sublist.cs index c159cb0128..88d61ea6df 100644 --- a/generators/Exercises/Sublist.cs +++ b/generators/Exercises/Generators/Sublist.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; using Humanizer; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Sublist : GeneratorExercise { diff --git a/generators/Exercises/SumOfMultiples.cs b/generators/Exercises/Generators/SumOfMultiples.cs similarity index 80% rename from generators/Exercises/SumOfMultiples.cs rename to generators/Exercises/Generators/SumOfMultiples.cs index 7eae84b4b3..87bb195105 100644 --- a/generators/Exercises/SumOfMultiples.cs +++ b/generators/Exercises/Generators/SumOfMultiples.cs @@ -1,10 +1,9 @@ using System; using System.Collections.Generic; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class SumOfMultiples : GeneratorExercise { diff --git a/generators/Exercises/Tournament.cs b/generators/Exercises/Generators/Tournament.cs similarity index 92% rename from generators/Exercises/Tournament.cs rename to generators/Exercises/Generators/Tournament.cs index c3c5f87b38..dd52d60be3 100644 --- a/generators/Exercises/Tournament.cs +++ b/generators/Exercises/Generators/Tournament.cs @@ -2,12 +2,11 @@ using System.Collections.Generic; using System.IO; using System.Text; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Tournament : GeneratorExercise { diff --git a/generators/Exercises/Transpose.cs b/generators/Exercises/Generators/Transpose.cs similarity index 80% rename from generators/Exercises/Transpose.cs rename to generators/Exercises/Generators/Transpose.cs index d90b9f0980..cdea765ab6 100644 --- a/generators/Exercises/Transpose.cs +++ b/generators/Exercises/Generators/Transpose.cs @@ -1,8 +1,7 @@ -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Transpose : GeneratorExercise { diff --git a/generators/Exercises/Triangle.cs b/generators/Exercises/Generators/Triangle.cs similarity index 90% rename from generators/Exercises/Triangle.cs rename to generators/Exercises/Generators/Triangle.cs index 65996608f9..e68035cd8f 100644 --- a/generators/Exercises/Triangle.cs +++ b/generators/Exercises/Generators/Triangle.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Triangle : GeneratorExercise { diff --git a/generators/Exercises/TwelveDays.cs b/generators/Exercises/Generators/TwelveDays.cs similarity index 79% rename from generators/Exercises/TwelveDays.cs rename to generators/Exercises/Generators/TwelveDays.cs index 597432b3f7..7c688f9b53 100644 --- a/generators/Exercises/TwelveDays.cs +++ b/generators/Exercises/Generators/TwelveDays.cs @@ -1,8 +1,7 @@ -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class TwelveDays : GeneratorExercise { diff --git a/generators/Exercises/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs similarity index 94% rename from generators/Exercises/TwoBucket.cs rename to generators/Exercises/Generators/TwoBucket.cs index 1860150a9e..ddfdd5847c 100644 --- a/generators/Exercises/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; -using Generators.Output; -using Generators.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Templates; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class TwoBucket : GeneratorExercise { diff --git a/generators/Exercises/TwoFer.cs b/generators/Exercises/Generators/TwoFer.cs similarity index 69% rename from generators/Exercises/TwoFer.cs rename to generators/Exercises/Generators/TwoFer.cs index 6c7d2a472e..cd9dd7c807 100644 --- a/generators/Exercises/TwoFer.cs +++ b/generators/Exercises/Generators/TwoFer.cs @@ -1,6 +1,6 @@ -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class TwoFer : GeneratorExercise { diff --git a/generators/Exercises/VariableLengthQuantity.cs b/generators/Exercises/Generators/VariableLengthQuantity.cs similarity index 94% rename from generators/Exercises/VariableLengthQuantity.cs rename to generators/Exercises/Generators/VariableLengthQuantity.cs index 8adb049905..2c22ec5743 100644 --- a/generators/Exercises/VariableLengthQuantity.cs +++ b/generators/Exercises/Generators/VariableLengthQuantity.cs @@ -2,9 +2,9 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class VariableLengthQuantity : GeneratorExercise { diff --git a/generators/Exercises/WordCount.cs b/generators/Exercises/Generators/WordCount.cs similarity index 90% rename from generators/Exercises/WordCount.cs rename to generators/Exercises/Generators/WordCount.cs index 1fbe73cca4..c52423ba0f 100644 --- a/generators/Exercises/WordCount.cs +++ b/generators/Exercises/Generators/WordCount.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class WordCount : GeneratorExercise { diff --git a/generators/Exercises/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs similarity index 96% rename from generators/Exercises/WordSearch.cs rename to generators/Exercises/Generators/WordSearch.cs index 9296069b99..0f50af9ee8 100644 --- a/generators/Exercises/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class WordSearch : GeneratorExercise { diff --git a/generators/Exercises/Wordy.cs b/generators/Exercises/Generators/Wordy.cs similarity index 76% rename from generators/Exercises/Wordy.cs rename to generators/Exercises/Generators/Wordy.cs index e631bcf758..c4af612289 100644 --- a/generators/Exercises/Wordy.cs +++ b/generators/Exercises/Generators/Wordy.cs @@ -1,7 +1,7 @@ using System; -using Generators.Output; +using Exercism.CSharp.Output; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Wordy : GeneratorExercise { diff --git a/generators/Exercises/Yacht.cs b/generators/Exercises/Generators/Yacht.cs similarity index 84% rename from generators/Exercises/Yacht.cs rename to generators/Exercises/Generators/Yacht.cs index 6b7fb2df01..09e11c75fc 100644 --- a/generators/Exercises/Yacht.cs +++ b/generators/Exercises/Generators/Yacht.cs @@ -1,7 +1,7 @@ -using Generators.Output; +using Exercism.CSharp.Output; using Humanizer; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Yacht : GeneratorExercise { diff --git a/generators/Exercises/ZebraPuzzle.cs b/generators/Exercises/Generators/ZebraPuzzle.cs similarity index 79% rename from generators/Exercises/ZebraPuzzle.cs rename to generators/Exercises/Generators/ZebraPuzzle.cs index 9a916984f3..f1663a02be 100644 --- a/generators/Exercises/ZebraPuzzle.cs +++ b/generators/Exercises/Generators/ZebraPuzzle.cs @@ -1,7 +1,7 @@ -using Generators.Output; +using Exercism.CSharp.Output; using Humanizer; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class ZebraPuzzle : GeneratorExercise { diff --git a/generators/Exercises/Zipper.cs b/generators/Exercises/Generators/Zipper.cs similarity index 97% rename from generators/Exercises/Zipper.cs rename to generators/Exercises/Generators/Zipper.cs index c95a2b5c15..bda8fa6151 100644 --- a/generators/Exercises/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Output; +using Exercism.CSharp.Output; using Humanizer; -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Zipper : GeneratorExercise { diff --git a/generators/MissingDataExercise.cs b/generators/Exercises/MissingDataExercise.cs similarity index 81% rename from generators/MissingDataExercise.cs rename to generators/Exercises/MissingDataExercise.cs index f92f3f47db..c5951349ec 100644 --- a/generators/MissingDataExercise.cs +++ b/generators/Exercises/MissingDataExercise.cs @@ -1,4 +1,4 @@ -namespace Generators +namespace Exercism.CSharp.Exercises { public class MissingDataExercise : Exercise { diff --git a/generators/TestedMethodType.cs b/generators/Exercises/TestedMethodType.cs similarity index 73% rename from generators/TestedMethodType.cs rename to generators/Exercises/TestedMethodType.cs index 0e8938029d..46d7b8bc7e 100644 --- a/generators/TestedMethodType.cs +++ b/generators/Exercises/TestedMethodType.cs @@ -1,4 +1,4 @@ -namespace Generators +namespace Exercism.CSharp.Exercises { public enum TestedMethodType { diff --git a/generators/UnimplementedExercise.cs b/generators/Exercises/UnimplementedExercise.cs similarity index 82% rename from generators/UnimplementedExercise.cs rename to generators/Exercises/UnimplementedExercise.cs index f2f28666d4..a1a88088fb 100644 --- a/generators/UnimplementedExercise.cs +++ b/generators/Exercises/UnimplementedExercise.cs @@ -1,4 +1,4 @@ -namespace Generators +namespace Exercism.CSharp.Exercises { public class UnimplementedExercise : Exercise { diff --git a/generators/GeneratorStatus.cs b/generators/GeneratorStatus.cs index adf127e104..72c849a741 100644 --- a/generators/GeneratorStatus.cs +++ b/generators/GeneratorStatus.cs @@ -1,4 +1,4 @@ -namespace Generators +namespace Exercism.CSharp { public enum GeneratorStatus { diff --git a/generators/Generators.csproj b/generators/Generators.csproj index 94eadd94a9..9dd54a4cf5 100644 --- a/generators/Generators.csproj +++ b/generators/Generators.csproj @@ -2,6 +2,7 @@ Exe netcoreapp2.0 + Exercism.CSharp diff --git a/generators/Helpers/ConvertHelper.cs b/generators/Helpers/ConvertHelper.cs index 81623efe48..69f3e51943 100644 --- a/generators/Helpers/ConvertHelper.cs +++ b/generators/Helpers/ConvertHelper.cs @@ -1,4 +1,4 @@ -namespace Generators.Helpers +namespace Exercism.CSharp.Helpers { public static class ConvertHelper { diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index 6fb14370e1..a8459d398e 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -2,7 +2,7 @@ using System.Text.RegularExpressions; using Humanizer; -namespace Generators.Helpers +namespace Exercism.CSharp.Helpers { public static class NameExtensions { diff --git a/generators/Helpers/TypesExtensions.cs b/generators/Helpers/TypesExtensions.cs index 13220f43f1..01ba6a96bf 100644 --- a/generators/Helpers/TypesExtensions.cs +++ b/generators/Helpers/TypesExtensions.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Generators.Helpers +namespace Exercism.CSharp.Helpers { public static class TypesExtensions { diff --git a/generators/Input/CanonicalData.cs b/generators/Input/CanonicalData.cs index e83573b6c3..f2b6133ab4 100644 --- a/generators/Input/CanonicalData.cs +++ b/generators/Input/CanonicalData.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Generators.Input +namespace Exercism.CSharp.Input { public class CanonicalData { diff --git a/generators/Input/CanonicalDataCase.cs b/generators/Input/CanonicalDataCase.cs index 4a606180b1..6f648e5a47 100644 --- a/generators/Input/CanonicalDataCase.cs +++ b/generators/Input/CanonicalDataCase.cs @@ -1,6 +1,6 @@ using System.Collections.Generic; -namespace Generators.Input +namespace Exercism.CSharp.Input { public class CanonicalDataCase { diff --git a/generators/Input/CanonicalDataCaseParser.cs b/generators/Input/CanonicalDataCaseParser.cs index 6823349de6..41cc4c399f 100644 --- a/generators/Input/CanonicalDataCaseParser.cs +++ b/generators/Input/CanonicalDataCaseParser.cs @@ -3,7 +3,7 @@ using System.Linq; using Newtonsoft.Json.Linq; -namespace Generators.Input +namespace Exercism.CSharp.Input { public static class CanonicalDataCaseParser { diff --git a/generators/Input/CanonicalDataFile.cs b/generators/Input/CanonicalDataFile.cs index e9b3e5d22c..135642e129 100644 --- a/generators/Input/CanonicalDataFile.cs +++ b/generators/Input/CanonicalDataFile.cs @@ -3,7 +3,7 @@ using LibGit2Sharp; using Serilog; -namespace Generators.Input +namespace Exercism.CSharp.Input { public class CanonicalDataFile { diff --git a/generators/Input/CanonicalDataParser.cs b/generators/Input/CanonicalDataParser.cs index d54f2b0e5d..f72ba65fb3 100644 --- a/generators/Input/CanonicalDataParser.cs +++ b/generators/Input/CanonicalDataParser.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using Newtonsoft.Json.Linq; -namespace Generators.Input +namespace Exercism.CSharp.Input { public class CanonicalDataParser { diff --git a/generators/Input/TrackConfigFile.cs b/generators/Input/TrackConfigFile.cs index c9b85dd828..34e7418074 100644 --- a/generators/Input/TrackConfigFile.cs +++ b/generators/Input/TrackConfigFile.cs @@ -3,7 +3,7 @@ using System.Linq; using Newtonsoft.Json; -namespace Generators.Input +namespace Exercism.CSharp.Input { public static class TrackConfigFile { diff --git a/generators/Options.cs b/generators/Options.cs index ccba12b5f8..dfb4fdea0e 100644 --- a/generators/Options.cs +++ b/generators/Options.cs @@ -2,7 +2,7 @@ using System.IO; using CommandLine; -namespace Generators +namespace Exercism.CSharp { public class Options { diff --git a/generators/Output/FormattingExtensions.cs b/generators/Output/FormattingExtensions.cs index 0f5c48381e..121d71f222 100644 --- a/generators/Output/FormattingExtensions.cs +++ b/generators/Output/FormattingExtensions.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -namespace Generators.Output +namespace Exercism.CSharp.Output { public static class FormattingExtensions { diff --git a/generators/Output/Templates/IndentFilter.cs b/generators/Output/Templates/IndentFilter.cs index 8e72109e81..f6a601f9df 100644 --- a/generators/Output/Templates/IndentFilter.cs +++ b/generators/Output/Templates/IndentFilter.cs @@ -1,7 +1,7 @@ using System; using System.Linq; -namespace Generators.Output.Templates +namespace Exercism.CSharp.Output.Templates { public static class IndentFilter { diff --git a/generators/Output/Templates/TemplateRenderer.cs b/generators/Output/Templates/TemplateRenderer.cs index ab7297b32a..2742533724 100644 --- a/generators/Output/Templates/TemplateRenderer.cs +++ b/generators/Output/Templates/TemplateRenderer.cs @@ -2,7 +2,7 @@ using DotLiquid; using DotLiquid.FileSystems; -namespace Generators.Output.Templates +namespace Exercism.CSharp.Output.Templates { public static class TemplateRenderer { diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index da79fb725d..e04cdede38 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; -using Generators.Output.Templates; +using Exercism.CSharp.Output.Templates; -namespace Generators.Output +namespace Exercism.CSharp.Output { public class TestClass { diff --git a/generators/Output/TestClassFile.cs b/generators/Output/TestClassFile.cs index c5e3a566be..32c5150b64 100644 --- a/generators/Output/TestClassFile.cs +++ b/generators/Output/TestClassFile.cs @@ -1,6 +1,6 @@ using System.IO; -namespace Generators.Output +namespace Exercism.CSharp.Output { public class TestClassFile { diff --git a/generators/Output/TestData.cs b/generators/Output/TestData.cs index 741b8adc53..20448a5e9e 100644 --- a/generators/Output/TestData.cs +++ b/generators/Output/TestData.cs @@ -1,10 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Helpers; -using Generators.Input; +using Exercism.CSharp.Exercises; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Input; -namespace Generators.Output +namespace Exercism.CSharp.Output { public class TestData { diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index 47f4d2b1c8..ac08cd4ac9 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -1,6 +1,6 @@ -using Generators.Output.Templates; +using Exercism.CSharp.Output.Templates; -namespace Generators.Output +namespace Exercism.CSharp.Output { public class TestMethod { diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index befada2ed8..8d18a91ea4 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -1,10 +1,11 @@ using System; using System.Collections.Generic; using System.Linq; -using Generators.Helpers; -using Generators.Output.Templates; +using Exercism.CSharp.Exercises; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output.Templates; -namespace Generators.Output +namespace Exercism.CSharp.Output { public abstract class TestMethodBody { diff --git a/generators/Output/TestMethodBodyWithBooleanCheck.cs b/generators/Output/TestMethodBodyWithBooleanCheck.cs index c1f72a424a..72c9f7e96a 100644 --- a/generators/Output/TestMethodBodyWithBooleanCheck.cs +++ b/generators/Output/TestMethodBodyWithBooleanCheck.cs @@ -1,6 +1,6 @@ using System; -namespace Generators.Output +namespace Exercism.CSharp.Output { public class TestMethodBodyWithBooleanCheck : TestMethodBody { diff --git a/generators/Output/TestMethodBodyWithEqualityCheck.cs b/generators/Output/TestMethodBodyWithEqualityCheck.cs index c2bd4c4890..09f91676fe 100644 --- a/generators/Output/TestMethodBodyWithEqualityCheck.cs +++ b/generators/Output/TestMethodBodyWithEqualityCheck.cs @@ -1,6 +1,6 @@ using System.Collections; -namespace Generators.Output +namespace Exercism.CSharp.Output { public class TestMethodBodyWithEqualityCheck : TestMethodBody { diff --git a/generators/Output/TestMethodBodyWithExceptionCheck.cs b/generators/Output/TestMethodBodyWithExceptionCheck.cs index 49905b3cb9..752fc07f07 100644 --- a/generators/Output/TestMethodBodyWithExceptionCheck.cs +++ b/generators/Output/TestMethodBodyWithExceptionCheck.cs @@ -1,4 +1,4 @@ -namespace Generators.Output +namespace Exercism.CSharp.Output { public class TestMethodBodyWithExceptionCheck : TestMethodBody { diff --git a/generators/Output/TestMethodBodyWithNullCheck.cs b/generators/Output/TestMethodBodyWithNullCheck.cs index d4e854ae4e..674f2920b8 100644 --- a/generators/Output/TestMethodBodyWithNullCheck.cs +++ b/generators/Output/TestMethodBodyWithNullCheck.cs @@ -1,4 +1,4 @@ -namespace Generators.Output +namespace Exercism.CSharp.Output { public class TestMethodBodyWithNullCheck : TestMethodBody { diff --git a/generators/Output/UnescapedValue.cs b/generators/Output/UnescapedValue.cs index cb97bdfac9..666b6cfd40 100644 --- a/generators/Output/UnescapedValue.cs +++ b/generators/Output/UnescapedValue.cs @@ -1,6 +1,6 @@ using DotLiquid; -namespace Generators.Output +namespace Exercism.CSharp.Output { public class UnescapedValue : ILiquidizable { diff --git a/generators/Output/ValueFormatter.cs b/generators/Output/ValueFormatter.cs index e0956a8628..c488aa22b0 100644 --- a/generators/Output/ValueFormatter.cs +++ b/generators/Output/ValueFormatter.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -using Generators.Helpers; +using Exercism.CSharp.Helpers; using Newtonsoft.Json.Linq; -namespace Generators.Output +namespace Exercism.CSharp.Output { public static class ValueFormatter { diff --git a/generators/Program.cs b/generators/Program.cs index 3b5f2643be..f6e73186c6 100644 --- a/generators/Program.cs +++ b/generators/Program.cs @@ -1,11 +1,11 @@ using System; using CommandLine; -using Generators.Helpers; -using Generators.Input; -using Generators.Output; +using Exercism.CSharp.Exercises; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Input; using Serilog; -namespace Generators +namespace Exercism.CSharp { public static class Program { From a16860b11decf4cad8e26d0d3dd4cf4f409d746d Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 25 Jun 2018 10:07:20 +0200 Subject: [PATCH 30/97] generators: Add separate test method for empty assertion --- generators/Exercises/GeneratorExercise.cs | 3 +++ generators/Helpers/DynamicExtensions.cs | 15 +++++++++++++++ ...sertEqual_Empty.liquid => _AssertEmpty.liquid} | 0 generators/Output/TestMethodBodyWithEmptyCheck.cs | 13 +++++++++++++ .../Output/TestMethodBodyWithEqualityCheck.cs | 11 +---------- 5 files changed, 32 insertions(+), 10 deletions(-) create mode 100644 generators/Helpers/DynamicExtensions.cs rename generators/Output/Templates/{_AssertEqual_Empty.liquid => _AssertEmpty.liquid} (100%) create mode 100644 generators/Output/TestMethodBodyWithEmptyCheck.cs diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index 7caf2fdd08..fad64bd734 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -104,6 +104,9 @@ private static TestMethodBody CreateTestMethodBodyFromData(TestData data) case null: return new TestMethodBodyWithNullCheck(data); default: + if ((data.Expected as object).IsEmptyEnumerable()) + return new TestMethodBodyWithEmptyCheck(data); + return new TestMethodBodyWithEqualityCheck(data); } } diff --git a/generators/Helpers/DynamicExtensions.cs b/generators/Helpers/DynamicExtensions.cs new file mode 100644 index 0000000000..bf7f9b68bc --- /dev/null +++ b/generators/Helpers/DynamicExtensions.cs @@ -0,0 +1,15 @@ +using System.Collections; + +namespace Exercism.CSharp.Helpers +{ + public static class DynamicExtensions + { + public static bool IsEmptyEnumerable(this object value) + { + if (value is string) + return false; + + return value is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; + } + } +} \ No newline at end of file diff --git a/generators/Output/Templates/_AssertEqual_Empty.liquid b/generators/Output/Templates/_AssertEmpty.liquid similarity index 100% rename from generators/Output/Templates/_AssertEqual_Empty.liquid rename to generators/Output/Templates/_AssertEmpty.liquid diff --git a/generators/Output/TestMethodBodyWithEmptyCheck.cs b/generators/Output/TestMethodBodyWithEmptyCheck.cs new file mode 100644 index 0000000000..bfb0cee499 --- /dev/null +++ b/generators/Output/TestMethodBodyWithEmptyCheck.cs @@ -0,0 +1,13 @@ +namespace Exercism.CSharp.Output +{ + public class TestMethodBodyWithEmptyCheck : TestMethodBody + { + public TestMethodBodyWithEmptyCheck(TestData data) : base(data) + { + Data.UseVariableForExpected = false; + + AssertTemplateName = "AssertEmpty"; + AssertTemplateParameters = new { ExpectedParameter, TestedValue }; + } + } +} \ No newline at end of file diff --git a/generators/Output/TestMethodBodyWithEqualityCheck.cs b/generators/Output/TestMethodBodyWithEqualityCheck.cs index 09f91676fe..7d24466227 100644 --- a/generators/Output/TestMethodBodyWithEqualityCheck.cs +++ b/generators/Output/TestMethodBodyWithEqualityCheck.cs @@ -1,20 +1,11 @@ -using System.Collections; - namespace Exercism.CSharp.Output { public class TestMethodBodyWithEqualityCheck : TestMethodBody { public TestMethodBodyWithEqualityCheck(TestData data) : base(data) { - Data.UseVariableForExpected = Data.UseVariableForExpected && !UseEmptyAssert; - - AssertTemplateName = UseEmptyAssert ? "AssertEqual_Empty" : "AssertEqual"; + AssertTemplateName = "AssertEqual"; AssertTemplateParameters = new { ExpectedParameter, TestedValue }; } - - private bool UseEmptyAssert => - !(Data.Expected is string) && - Data.Expected is IEnumerable enumerable - && enumerable.GetEnumerator().MoveNext() == false; } } \ No newline at end of file From bacbd8a945504a30c8364decab18f26dd4bdbd1f Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 25 Jun 2018 10:08:34 +0200 Subject: [PATCH 31/97] generators: Improve naming of test method body implementations --- generators/Exercises/GeneratorExercise.cs | 10 +++++----- ...nCheck.cs => TestMethodBodyWithBooleanAssertion.cs} | 4 ++-- ...ptyCheck.cs => TestMethodBodyWithEmptyAssertion.cs} | 4 ++-- ...Check.cs => TestMethodBodyWithEqualityAssertion.cs} | 4 ++-- ...heck.cs => TestMethodBodyWithExceptionAssertion.cs} | 4 ++-- ...NullCheck.cs => TestMethodBodyWithNullAssertion.cs} | 4 ++-- 6 files changed, 15 insertions(+), 15 deletions(-) rename generators/Output/{TestMethodBodyWithBooleanCheck.cs => TestMethodBodyWithBooleanAssertion.cs} (67%) rename generators/Output/{TestMethodBodyWithEmptyCheck.cs => TestMethodBodyWithEmptyAssertion.cs} (64%) rename generators/Output/{TestMethodBodyWithEqualityCheck.cs => TestMethodBodyWithEqualityAssertion.cs} (56%) rename generators/Output/{TestMethodBodyWithExceptionCheck.cs => TestMethodBodyWithExceptionAssertion.cs} (70%) rename generators/Output/{TestMethodBodyWithNullCheck.cs => TestMethodBodyWithNullAssertion.cs} (55%) diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index fad64bd734..cd14e89f96 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -94,20 +94,20 @@ private static TestMethodBody CreateTestMethodBodyFromData(TestData data) { if (data.ExceptionThrown != null) { - return new TestMethodBodyWithExceptionCheck(data); + return new TestMethodBodyWithExceptionAssertion(data); } switch (data.Expected) { case bool _: - return new TestMethodBodyWithBooleanCheck(data); + return new TestMethodBodyWithBooleanAssertion(data); case null: - return new TestMethodBodyWithNullCheck(data); + return new TestMethodBodyWithNullAssertion(data); default: if ((data.Expected as object).IsEmptyEnumerable()) - return new TestMethodBodyWithEmptyCheck(data); + return new TestMethodBodyWithEmptyAssertion(data); - return new TestMethodBodyWithEqualityCheck(data); + return new TestMethodBodyWithEqualityAssertion(data); } } diff --git a/generators/Output/TestMethodBodyWithBooleanCheck.cs b/generators/Output/TestMethodBodyWithBooleanAssertion.cs similarity index 67% rename from generators/Output/TestMethodBodyWithBooleanCheck.cs rename to generators/Output/TestMethodBodyWithBooleanAssertion.cs index 72c9f7e96a..c822fcfa76 100644 --- a/generators/Output/TestMethodBodyWithBooleanCheck.cs +++ b/generators/Output/TestMethodBodyWithBooleanAssertion.cs @@ -2,9 +2,9 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithBooleanCheck : TestMethodBody + public class TestMethodBodyWithBooleanAssertion : TestMethodBody { - public TestMethodBodyWithBooleanCheck(TestData data) : base(data) + public TestMethodBodyWithBooleanAssertion(TestData data) : base(data) { AssertTemplateName = "AssertBoolean"; AssertTemplateParameters = new { BooleanAssertMethod, TestedValue }; diff --git a/generators/Output/TestMethodBodyWithEmptyCheck.cs b/generators/Output/TestMethodBodyWithEmptyAssertion.cs similarity index 64% rename from generators/Output/TestMethodBodyWithEmptyCheck.cs rename to generators/Output/TestMethodBodyWithEmptyAssertion.cs index bfb0cee499..e17f2d4e27 100644 --- a/generators/Output/TestMethodBodyWithEmptyCheck.cs +++ b/generators/Output/TestMethodBodyWithEmptyAssertion.cs @@ -1,8 +1,8 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithEmptyCheck : TestMethodBody + public class TestMethodBodyWithEmptyAssertion : TestMethodBody { - public TestMethodBodyWithEmptyCheck(TestData data) : base(data) + public TestMethodBodyWithEmptyAssertion(TestData data) : base(data) { Data.UseVariableForExpected = false; diff --git a/generators/Output/TestMethodBodyWithEqualityCheck.cs b/generators/Output/TestMethodBodyWithEqualityAssertion.cs similarity index 56% rename from generators/Output/TestMethodBodyWithEqualityCheck.cs rename to generators/Output/TestMethodBodyWithEqualityAssertion.cs index 7d24466227..d41408ab46 100644 --- a/generators/Output/TestMethodBodyWithEqualityCheck.cs +++ b/generators/Output/TestMethodBodyWithEqualityAssertion.cs @@ -1,8 +1,8 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithEqualityCheck : TestMethodBody + public class TestMethodBodyWithEqualityAssertion : TestMethodBody { - public TestMethodBodyWithEqualityCheck(TestData data) : base(data) + public TestMethodBodyWithEqualityAssertion(TestData data) : base(data) { AssertTemplateName = "AssertEqual"; AssertTemplateParameters = new { ExpectedParameter, TestedValue }; diff --git a/generators/Output/TestMethodBodyWithExceptionCheck.cs b/generators/Output/TestMethodBodyWithExceptionAssertion.cs similarity index 70% rename from generators/Output/TestMethodBodyWithExceptionCheck.cs rename to generators/Output/TestMethodBodyWithExceptionAssertion.cs index 752fc07f07..02998f2c4c 100644 --- a/generators/Output/TestMethodBodyWithExceptionCheck.cs +++ b/generators/Output/TestMethodBodyWithExceptionAssertion.cs @@ -1,8 +1,8 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithExceptionCheck : TestMethodBody + public class TestMethodBodyWithExceptionAssertion : TestMethodBody { - public TestMethodBodyWithExceptionCheck(TestData data) : base(data) + public TestMethodBodyWithExceptionAssertion(TestData data) : base(data) { Data.UseVariableForExpected = false; Data.UseVariableForTested = false; diff --git a/generators/Output/TestMethodBodyWithNullCheck.cs b/generators/Output/TestMethodBodyWithNullAssertion.cs similarity index 55% rename from generators/Output/TestMethodBodyWithNullCheck.cs rename to generators/Output/TestMethodBodyWithNullAssertion.cs index 674f2920b8..34a05854e8 100644 --- a/generators/Output/TestMethodBodyWithNullCheck.cs +++ b/generators/Output/TestMethodBodyWithNullAssertion.cs @@ -1,8 +1,8 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithNullCheck : TestMethodBody + public class TestMethodBodyWithNullAssertion : TestMethodBody { - public TestMethodBodyWithNullCheck(TestData data) : base(data) + public TestMethodBodyWithNullAssertion(TestData data) : base(data) { AssertTemplateName = "AssertNull"; AssertTemplateParameters = new { TestedValue }; From a218912c205d310773671255101a4cfa839e2d6b Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 25 Jun 2018 10:18:24 +0200 Subject: [PATCH 32/97] generators: Don't use assert template parameters in generators --- generators/Exercises/Generators/BinarySearchTree.cs | 2 +- generators/Exercises/Generators/Clock.cs | 6 +++--- generators/Exercises/Generators/ComplexNumbers.cs | 2 +- generators/Exercises/Generators/Meetup.cs | 2 +- generators/Exercises/Generators/RationalNumbers.cs | 2 +- generators/Output/TestMethodBody.cs | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 12bc88d69a..38049d1ae7 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -68,7 +68,7 @@ protected IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMeth AddCodeLine($"Assert.Equal(new[] {{ {expectedArrayString} }}, tree.AsEnumerable());"); } - return new[] { TemplateRenderer.RenderInline(_testFactCodeLines.ToString(), testMethodBody.AssertTemplateParameters) }; + return new[] { _testFactCodeLines.ToString() }; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 902ad819a7..9f6c8b0b78 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -58,7 +58,7 @@ private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody tes private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) { const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString());"; - return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; + return new[] { TemplateRenderer.RenderInline(template, new { testMethodBody.ExpectedParameter, testMethodBody.TestedValue }) }; } private static IEnumerable RenderEqualToAssert(TestMethodBody testMethodBody) @@ -67,13 +67,13 @@ private static IEnumerable RenderEqualToAssert(TestMethodBody testMethod const string testedValue = "sut"; var expectedEqual = testMethodBody.Data.Expected; - testMethodBody.AssertTemplateParameters = new { expectedParameter, testedValue }; + var assertTemplateParameters = new { expectedParameter, testedValue }; var template = expectedEqual ? "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}); " : "Assert.NotEqual({{ ExpectedParameter }}, {{ TestedValue }});"; - return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; + return new[] { TemplateRenderer.RenderInline(template, assertTemplateParameters) }; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index 715e7868a7..38004e453c 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -47,7 +47,7 @@ private static IEnumerable RenderComplexNumberAssert(TestMethodBody test { const string template = "Assert.Equal({{ ExpectedParameter }}.Real(), {{ TestedValue }}.Real(), precision: 15);\r\nAssert.Equal({{ ExpectedParameter }}.Imaginary(), {{ TestedValue }}.Imaginary(), precision: 15);"; - return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; + return new[] { TemplateRenderer.RenderInline(template, new { testMethodBody.ExpectedParameter, testMethodBody.TestedValue}) }; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index 79a9f0068b..5549e60ee2 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -39,7 +39,7 @@ private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody tes { const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString(\"yyyy-MM-dd\"));"; - return new[] { TemplateRenderer.RenderInline(template, testMethodBody.AssertTemplateParameters) }; + return new[] { TemplateRenderer.RenderInline(template, new { testMethodBody.ExpectedParameter, testMethodBody.TestedValue }) }; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index a40a00b6cf..d0288d39fd 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -73,7 +73,7 @@ private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody tes break; } - return new[] { TemplateRenderer.RenderInline(assertCodeLine, testMethodBody.AssertTemplateParameters) }; + return new[] { assertCodeLine }; } private static int Precision(object rawValue) diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs index 8d18a91ea4..e5f5de3c08 100644 --- a/generators/Output/TestMethodBody.cs +++ b/generators/Output/TestMethodBody.cs @@ -45,9 +45,9 @@ public virtual string Render() return TemplateRenderer.RenderPartial(TemplateName, new { Arrange, Act, Assert }); } - protected string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; + public string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; protected string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); - protected string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Data.Expected); + public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Data.Expected); protected string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); From dfc170fb95b2ecf6049a6d667537e8b3ab96370e Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 25 Jun 2018 10:21:36 +0200 Subject: [PATCH 33/97] generators: Use consistent naming for TestMethodBody parameter --- generators/Exercises/Generators/Allergies.cs | 12 ++++----- .../Exercises/Generators/BinarySearchTree.cs | 4 +-- generators/Exercises/Generators/Bowling.cs | 26 +++++++++---------- .../Exercises/Generators/CircularBuffer.cs | 6 ++--- generators/Exercises/Generators/Clock.cs | 22 ++++++++-------- .../Exercises/Generators/ComplexNumbers.cs | 12 ++++----- generators/Exercises/Generators/GoCounting.cs | 8 +++--- generators/Exercises/Generators/Meetup.cs | 4 +-- .../Exercises/Generators/NucleotideCount.cs | 16 ++++++------ .../Generators/PalindromeProducts.cs | 6 ++--- .../Exercises/Generators/QueenAttack.cs | 18 ++++++------- .../Exercises/Generators/RationalNumbers.cs | 8 +++--- generators/Exercises/Generators/React.cs | 6 ++--- .../Exercises/Generators/RobotSimulator.cs | 20 +++++++------- .../Exercises/Generators/RunLengthEncoding.cs | 14 +++++----- .../Exercises/Generators/SimpleCipher.cs | 10 +++---- generators/Exercises/Generators/TwoBucket.cs | 12 ++++----- generators/Exercises/Generators/WordSearch.cs | 4 +-- generators/Exercises/Generators/Zipper.cs | 10 +++---- 19 files changed, 109 insertions(+), 109 deletions(-) diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index f4ab24c025..c688df8901 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -21,21 +21,21 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - return testMethodBody.Data.Property == "allergicTo" - ? RenderIsAllergicToAssert(testMethodBody) - : testMethodBody.Assert; + return body.Data.Property == "allergicTo" + ? RenderIsAllergicToAssert(body) + : body.Assert; } - private static IEnumerable RenderIsAllergicToAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderIsAllergicToAssert(TestMethodBody body) { const string template = @"{%- for allergy in Allergies -%} Assert.{% if allergy.result %}True{% else %}False{% endif %}(sut.IsAllergicTo(""{{ allergy.substance }}"")); {%- endfor -%}"; - var templateParameters = new { Allergies = testMethodBody.Data.Expected }; + var templateParameters = new { Allergies = body.Data.Expected }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } } diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 38049d1ae7..161481eb58 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -42,10 +42,10 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - protected IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + protected IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { _testFactCodeLines = new StringBuilder(); - var canonicalDataCase = testMethodBody.Data; + var canonicalDataCase = body.Data; var input = canonicalDataCase.Properties["input"] as Dictionary; var constructorData = input["treeData"] as string[]; diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index a1feda8e73..7fcf2adb93 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -31,15 +31,15 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody body) { var builder = new StringBuilder(); builder.AppendLine("var sut = new BowlingGame();"); - if (!testMethodBody.Data.Input.ContainsKey(PreviousRolls)) + if (!body.Data.Input.ContainsKey(PreviousRolls)) return new[] { builder.ToString() }; - if (testMethodBody.Data.Input[PreviousRolls] is int[] array) + if (body.Data.Input[PreviousRolls] is int[] array) { builder.Append("var previousRolls = new [] { "); builder.AppendJoin(", ", array); @@ -53,39 +53,39 @@ private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody te return new[] { builder.ToString() }; } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - if (testMethodBody.Data.ExceptionThrown != null && testMethodBody.Data.Input.ContainsKey("roll")) + if (body.Data.ExceptionThrown != null && body.Data.Input.ContainsKey("roll")) { const string template = "Assert.Throws(() => sut.Roll({{RollVal}}));"; var templateParams = new { - RollVal = testMethodBody.Data.Input["roll"] + RollVal = body.Data.Input["roll"] }; return new[] { TemplateRenderer.RenderInline(template, templateParams) }; } - if (testMethodBody.Data.ExceptionThrown == null || - testMethodBody.Data.Property != "score") - return testMethodBody.Assert; + if (body.Data.ExceptionThrown == null || + body.Data.Property != "score") + return body.Assert; const string throwTemplate = "Assert.Throws(() => sut.Score());"; return new[] { throwTemplate }; } - private static IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAct(TestMethodBody body) { var template = @"DoRoll(previousRolls, sut); "; - if (testMethodBody.Data.ExceptionThrown != null) + if (body.Data.ExceptionThrown != null) { return new[] { template }; } - if (testMethodBody.Data.Input.ContainsKey("roll")) + if (body.Data.Input.ContainsKey("roll")) { template += @"sut.Roll({{RolVal}}); @@ -93,7 +93,7 @@ private static IEnumerable RenderTestMethodBodyAct(TestMethodBody testMe "; var templateParameters = new { - RolVal = testMethodBody.Data.Input["roll"] + RolVal = body.Data.Input["roll"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index a4644b8d56..0a655e38b9 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -11,11 +11,11 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - yield return RenderSut(testMethodBody.Data); + yield return RenderSut(body.Data); - foreach (var operation in testMethodBody.Data.Input["operations"]) + foreach (var operation in body.Data.Input["operations"]) yield return RenderOperation(operation); } diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 9f6c8b0b78..928bed6c69 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -43,29 +43,29 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - if (testMethodBody.Data.Property == PropertyEqual) + if (body.Data.Property == PropertyEqual) { - return RenderEqualToAssert(testMethodBody); + return RenderEqualToAssert(body); } - return testMethodBody.Data.Property != PropertyCreate - ? RenderConsistencyToAssert(testMethodBody) - : testMethodBody.Assert; + return body.Data.Property != PropertyCreate + ? RenderConsistencyToAssert(body) + : body.Assert; } - private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderConsistencyToAssert(TestMethodBody body) { const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString());"; - return new[] { TemplateRenderer.RenderInline(template, new { testMethodBody.ExpectedParameter, testMethodBody.TestedValue }) }; + return new[] { TemplateRenderer.RenderInline(template, new { body.ExpectedParameter, body.TestedValue }) }; } - private static IEnumerable RenderEqualToAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderEqualToAssert(TestMethodBody body) { - var expectedParameter = testMethodBody.Data.Input[ParamClock1]; + var expectedParameter = body.Data.Input[ParamClock1]; const string testedValue = "sut"; - var expectedEqual = testMethodBody.Data.Expected; + var expectedEqual = body.Data.Expected; var assertTemplateParameters = new { expectedParameter, testedValue }; diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index 38004e453c..0bf6eb11cc 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -36,18 +36,18 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - return testMethodBody.Data.UseVariableForExpected - ? RenderComplexNumberAssert(testMethodBody) - : testMethodBody.Assert; + return body.Data.UseVariableForExpected + ? RenderComplexNumberAssert(body) + : body.Assert; } - private static IEnumerable RenderComplexNumberAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderComplexNumberAssert(TestMethodBody body) { const string template = "Assert.Equal({{ ExpectedParameter }}.Real(), {{ TestedValue }}.Real(), precision: 15);\r\nAssert.Equal({{ ExpectedParameter }}.Imaginary(), {{ TestedValue }}.Imaginary(), precision: 15);"; - return new[] { TemplateRenderer.RenderInline(template, new { testMethodBody.ExpectedParameter, testMethodBody.TestedValue}) }; + return new[] { TemplateRenderer.RenderInline(template, new { body.ExpectedParameter, body.TestedValue}) }; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index b2c5d80adc..031e11030c 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -57,14 +57,14 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - if (testMethodBody.Data.ExceptionThrown != null) + if (body.Data.ExceptionThrown != null) { - return testMethodBody.Assert; + return body.Assert; } - if (testMethodBody.Data.Property == "territories") + if (body.Data.Property == "territories") { return new[] { diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index 5549e60ee2..b8dbd664be 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -35,11 +35,11 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString(\"yyyy-MM-dd\"));"; - return new[] { TemplateRenderer.RenderInline(template, new { testMethodBody.ExpectedParameter, testMethodBody.TestedValue }) }; + return new[] { TemplateRenderer.RenderInline(template, new { body.ExpectedParameter, body.TestedValue }) }; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index cd379f267f..5208dc2439 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -31,32 +31,32 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - return testMethodBody.Data.UseVariableForExpected - ? RenderEqualBodyAssert(testMethodBody) - : RenderThrowsBodyAssert(testMethodBody); + return body.Data.UseVariableForExpected + ? RenderEqualBodyAssert(body) + : RenderThrowsBodyAssert(body); } - private static IEnumerable RenderEqualBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderEqualBodyAssert(TestMethodBody body) { const string template = @"Assert.Equal(expected, sut.{{ TestedMethodName }});"; var templateParameters = new { - TestedMethodName = testMethodBody.Data.Property.ToTestedMethodName() + TestedMethodName = body.Data.Property.ToTestedMethodName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private static IEnumerable RenderThrowsBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderThrowsBodyAssert(TestMethodBody body) { const string template = @"Assert.Throws(() => new NucleotideCount(""{{ Input }}""));"; var templateParameters = new { - Input = testMethodBody.Data.Input["strand"] + Input = body.Data.Input["strand"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index 5951632a2c..8f7e9f0f34 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -27,11 +27,11 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - if (testMethodBody.Data.ExceptionThrown != null) + if (body.Data.ExceptionThrown != null) { - return testMethodBody.Assert; + return body.Assert; } return new[] diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index a197af700d..912fd3843f 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -18,25 +18,25 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - if (testMethodBody.Data.Property == "canAttack") - return new[] { RenderCanAttackAssert(testMethodBody) }; + if (body.Data.Property == "canAttack") + return new[] { RenderCanAttackAssert(body) }; - return testMethodBody.Data.UseVariableForTested + return body.Data.UseVariableForTested ? Array.Empty() - : testMethodBody.Assert; + : body.Assert; } - private static string RenderCanAttackAssert(TestMethodBody testMethodBody) + private static string RenderCanAttackAssert(TestMethodBody body) { const string template = @"var whiteQueen = QueenAttack.Create({{whiteQueenX}},{{whiteQueenY}}); var blackQueen = QueenAttack.Create({{blackQueenX}},{{blackQueenY}}); Assert.{% if Expected %}True{% else %}False{% endif %}(QueenAttack.CanAttack(whiteQueen, blackQueen));"; - var whiteQueenPositions = GetCoordinatesFromPosition(testMethodBody.Data.Input["white_queen"]); - var blackQueenPositions = GetCoordinatesFromPosition(testMethodBody.Data.Input["black_queen"]); + var whiteQueenPositions = GetCoordinatesFromPosition(body.Data.Input["white_queen"]); + var blackQueenPositions = GetCoordinatesFromPosition(body.Data.Input["black_queen"]); var templateParameters = new { @@ -44,7 +44,7 @@ private static string RenderCanAttackAssert(TestMethodBody testMethodBody) whiteQueenY = whiteQueenPositions.Item2, blackQueenX = blackQueenPositions.Item1, blackQueenY = blackQueenPositions.Item2, - testMethodBody.Data.Expected + body.Data.Expected }; return TemplateRenderer.RenderInline(template, templateParameters); diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index d0288d39fd..811c2c64d3 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -23,11 +23,11 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - var input = testMethodBody.Data.Properties["input"] as Dictionary; - var operation = testMethodBody.Data.Properties["property"].ToString(); - var expected = testMethodBody.Data.Properties["expected"]; + var input = body.Data.Properties["input"] as Dictionary; + var operation = body.Data.Properties["property"].ToString(); + var expected = body.Data.Properties["expected"]; var operationName = char.ToUpper(operation[0]) + operation.Substring(1); var assertCodeLine = ""; const string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; diff --git a/generators/Exercises/Generators/React.cs b/generators/Exercises/Generators/React.cs index efe1d28672..a27cce5e9a 100644 --- a/generators/Exercises/Generators/React.cs +++ b/generators/Exercises/Generators/React.cs @@ -16,15 +16,15 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(); } - private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody body) { var arrange = new StringBuilder(); arrange.AppendLine("var sut = new Reactor();"); - var cells = RenderCells(testMethodBody.Data.Input["cells"]); + var cells = RenderCells(body.Data.Input["cells"]); arrange.AppendLine(cells); - var operations = RenderOperations(testMethodBody.Data.Input["operations"]); + var operations = RenderOperations(body.Data.Input["operations"]); arrange.AppendLine(operations); return new[] { arrange.ToString() }; diff --git a/generators/Exercises/Generators/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs index 76ffb481b5..00aadb7cd0 100644 --- a/generators/Exercises/Generators/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -32,44 +32,44 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAct(TestMethodBody body) { - switch (testMethodBody.Data.Property) + switch (body.Data.Property) { case "create": return Array.Empty(); - case "instructions": return RenderInstructionsMethodBodyAct(testMethodBody); - default: return RenderDefaultMethodBodyAct(testMethodBody); + case "instructions": return RenderInstructionsMethodBodyAct(body); + default: return RenderDefaultMethodBodyAct(body); } } - private static IEnumerable RenderDefaultMethodBodyAct(TestMethodBody testMethodBody) + private static IEnumerable RenderDefaultMethodBodyAct(TestMethodBody body) { const string template = @"sut.{{MethodInvocation}}();"; var templateParameters = new { - MethodInvocation = testMethodBody.Data.Property.ToTestedMethodName() + MethodInvocation = body.Data.Property.ToTestedMethodName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private static IEnumerable RenderInstructionsMethodBodyAct(TestMethodBody testMethodBody) + private static IEnumerable RenderInstructionsMethodBodyAct(TestMethodBody body) { const string template = @"sut.{{MethodInvocation}}(""{{Instructions}}"");"; var templateParameters = new { MethodInvocation = "Simulate", - Instructions = testMethodBody.Data.Input["instructions"] + Instructions = body.Data.Input["instructions"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - var expected = testMethodBody.Data.Expected as Dictionary; + var expected = body.Data.Expected as Dictionary; expected.TryGetValue("position", out var position); expected.TryGetValue("direction", out var direction); diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index 586e2eef5d..2e29b74b7b 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -16,21 +16,21 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - return testMethodBody.Data.Property == "consistency" - ? RenderConsistencyToAssert(testMethodBody) - : testMethodBody.Assert; + return body.Data.Property == "consistency" + ? RenderConsistencyToAssert(body) + : body.Assert; } - private static IEnumerable RenderConsistencyToAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderConsistencyToAssert(TestMethodBody body) { const string template = @"Assert.Equal(""{{Expected}}"", {{TestedClassName}}.Decode({{TestedClassName}}.Encode(""{{Expected}}"")));"; var templateParameters = new { - testMethodBody.Data.Expected, - TestedClassName = testMethodBody.Data.TestedClass + body.Data.Expected, + TestedClassName = body.Data.TestedClass }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index 65a24a3533..ea425159f4 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -48,18 +48,18 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - switch (testMethodBody.Data.Property) + switch (body.Data.Property) { case "new": - var key = ValueFormatter.Format(testMethodBody.Data.Input["key"]); + var key = ValueFormatter.Format(body.Data.Input["key"]); return new[] { $"Assert.Throws(() => new SimpleCipher({key}));" }; case "key": - var pattern = ValueFormatter.Format(testMethodBody.Data.Expected["match"]); + var pattern = ValueFormatter.Format(body.Data.Expected["match"]); return new[] { $"Assert.Matches({pattern}, sut.Key);" }; default: - return testMethodBody.Assert; + return body.Assert; } } diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index ddfdd5847c..b01af91c85 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -21,19 +21,19 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAct(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAct(TestMethodBody body) { const string template = @"var result = {{MethodInvocation}};"; var templateParameters = new { - MethodInvocation = testMethodBody.TestedMethodInvocation + MethodInvocation = body.TestedMethodInvocation }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { const string template = @"Assert.Equal({{MovesExpected}}, result.Moves); @@ -42,9 +42,9 @@ private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody tes var templateParameters = new { - MovesExpected = testMethodBody.Data.Expected["moves"], - OtherBucketExpected = testMethodBody.Data.Expected["otherBucket"], - GoalBucketExpected = testMethodBody.Data.Expected["goalBucket"] + MovesExpected = body.Data.Expected["moves"], + OtherBucketExpected = body.Data.Expected["otherBucket"], + GoalBucketExpected = body.Data.Expected["goalBucket"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 0f50af9ee8..4af70ba977 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -39,9 +39,9 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - var expectedDictionary = testMethodBody.Data.Properties["expected"] as IDictionary; + var expectedDictionary = body.Data.Properties["expected"] as IDictionary; foreach (var kv in expectedDictionary) yield return RenderTestMethodBodyAssertForSearchWord(kv.Key, kv.Value); diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index bda8fa6151..543ad90aee 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -14,19 +14,19 @@ protected override void UpdateTestMethodBody(TestMethodBody body) body.Assert = RenderTestMethodBodyAssert(body); } - private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody body) { - var tree = RenderTree(testMethodBody.Data.Input["initialTree"]); + var tree = RenderTree(body.Data.Input["initialTree"]); yield return $"var tree = {tree};"; yield return "var sut = Zipper.FromTree(tree);"; - var operations = RenderOperations(testMethodBody.Data.Input["operations"]); + var operations = RenderOperations(body.Data.Input["operations"]); yield return $"var actual = sut{operations};"; } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody testMethodBody) + private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) { - var expected = RenderExpected(testMethodBody.Data.Expected); + var expected = RenderExpected(body.Data.Expected); if (expected == null) { yield return "Assert.Null(actual);"; From b3f5bdcd41c77c599e4b612d5991eafb6bc850e9 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 25 Jun 2018 14:10:58 +0200 Subject: [PATCH 34/97] generators: Simplified test method and class code --- generators/Exercises/GeneratorExercise.cs | 73 +++++------ generators/Exercises/Generators/Allergies.cs | 18 +-- .../Exercises/Generators/BinarySearchTree.cs | 8 +- generators/Exercises/Generators/Bowling.cs | 38 +++--- .../Exercises/Generators/CircularBuffer.cs | 10 +- generators/Exercises/Generators/Clock.cs | 28 ++--- .../Exercises/Generators/ComplexNumbers.cs | 16 +-- generators/Exercises/Generators/GoCounting.cs | 18 +-- generators/Exercises/Generators/Grep.cs | 2 +- generators/Exercises/Generators/Markdown.cs | 6 +- generators/Exercises/Generators/Meetup.cs | 8 +- .../Exercises/Generators/NucleotideCount.cs | 20 +-- .../Generators/PalindromeProducts.cs | 12 +- .../Exercises/Generators/QueenAttack.cs | 24 ++-- .../Exercises/Generators/RationalNumbers.cs | 14 +-- generators/Exercises/Generators/React.cs | 18 +-- .../Exercises/Generators/RobotSimulator.cs | 26 ++-- .../Exercises/Generators/RunLengthEncoding.cs | 20 +-- .../Exercises/Generators/SimpleCipher.cs | 14 +-- generators/Exercises/Generators/Tournament.cs | 12 +- generators/Exercises/Generators/TwoBucket.cs | 18 +-- generators/Exercises/Generators/WordSearch.cs | 12 +- generators/Exercises/Generators/Zipper.cs | 16 +-- generators/Input/CanonicalDataCase.cs | 7 +- generators/Input/CanonicalDataCaseParser.cs | 3 +- ...ception.liquid => _AssertException.liquid} | 0 generators/Output/Templates/_TestClass.liquid | 4 +- .../Templates/_TestClassDisposable.liquid | 14 --- .../Output/Templates/_TestMethod.liquid | 4 +- .../Output/Templates/_TestMethodBody.liquid | 9 -- generators/Output/TestClass.cs | 10 +- generators/Output/TestData.cs | 4 + generators/Output/TestMethod.cs | 115 +++++++++++++++++- generators/Output/TestMethodBody.cs | 114 ----------------- ...n.cs => TestMethodWithBooleanAssertion.cs} | 4 +- ...ion.cs => TestMethodWithEmptyAssertion.cs} | 4 +- ....cs => TestMethodWithEqualityAssertion.cs} | 4 +- ...cs => TestMethodWithExceptionAssertion.cs} | 6 +- ...tion.cs => TestMethodWithNullAssertion.cs} | 4 +- 39 files changed, 348 insertions(+), 389 deletions(-) rename generators/Output/Templates/{_AssertThrowsException.liquid => _AssertException.liquid} (100%) delete mode 100644 generators/Output/Templates/_TestClassDisposable.liquid delete mode 100644 generators/Output/Templates/_TestMethodBody.liquid delete mode 100644 generators/Output/TestMethodBody.cs rename generators/Output/{TestMethodBodyWithBooleanAssertion.cs => TestMethodWithBooleanAssertion.cs} (67%) rename generators/Output/{TestMethodBodyWithEmptyAssertion.cs => TestMethodWithEmptyAssertion.cs} (64%) rename generators/Output/{TestMethodBodyWithEqualityAssertion.cs => TestMethodWithEqualityAssertion.cs} (56%) rename generators/Output/{TestMethodBodyWithExceptionAssertion.cs => TestMethodWithExceptionAssertion.cs} (59%) rename generators/Output/{TestMethodBodyWithNullAssertion.cs => TestMethodWithNullAssertion.cs} (55%) diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index cd14e89f96..85d1b1dce5 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -10,39 +10,29 @@ namespace Exercism.CSharp.Exercises public abstract class GeneratorExercise : Exercise { private CanonicalData _canonicalData; + private TestData[] _testData; public override string Name => GetType().ToExerciseName(); public void Regenerate(CanonicalData canonicalData) { _canonicalData = canonicalData; + _testData = CreateTestData(); var testClass = CreateTestClass(); var testClassFile = new TestClassFile(testClass); testClassFile.Write(); } - private IList RenderTestMethods(IEnumerable testData) - { - var testMethods = testData - .Select(CreateTestMethod) - .ToArray(); - - Array.ForEach(testMethods, UpdateTestMethod); - - return testMethods.Select(testMethod => testMethod.Render()).ToList(); - } - private TestClass CreateTestClass() { - var testData = CreateTestData(); var testClass = new TestClass { Exercise = _canonicalData.Exercise, CanonicalDataVersion = _canonicalData.Version, ClassName = _canonicalData.Exercise.ToTestClassName(), - Methods = RenderTestMethods(testData), - Namespaces = GetNamespaces(testData) + Namespaces = GetNamespaces(), + Methods = RenderTestMethods() }; UpdateTestClass(testClass); @@ -53,9 +43,9 @@ protected virtual void UpdateTestClass(TestClass @class) { } - private ISet GetNamespaces(IEnumerable testData) + private ISet GetNamespaces() { - var exceptionNamespaces = testData + var exceptionNamespaces = _testData .Where(x => x.ExceptionThrown != null) .Select(x => x.ExceptionThrown.Namespace); @@ -71,60 +61,57 @@ protected virtual void UpdateNamespaces(ISet namespaces) { } - private TestMethod CreateTestMethod(TestData data, int index) => new TestMethod - { - Skip = index > 0, - Name = data.TestMethod, - Body = CreateTestMethodBody(data) - }; + private IList RenderTestMethods() + => CreateTestMethods() + .Select(testMethod => testMethod.Render()) + .ToList(); - protected virtual void UpdateTestMethod(TestMethod method) + private IEnumerable CreateTestMethods() { + var testMethods = _testData + .Select(CreateTestMethod) + .ToArray(); + + Array.ForEach(testMethods, UpdateTestMethod); + return testMethods; } - private TestMethodBody CreateTestMethodBody(TestData data) - { - var testMethodBody = CreateTestMethodBodyFromData(data); - UpdateTestMethodBody(testMethodBody); - - return testMethodBody; - } - - private static TestMethodBody CreateTestMethodBodyFromData(TestData data) + private static TestMethod CreateTestMethod(TestData data) { if (data.ExceptionThrown != null) - { - return new TestMethodBodyWithExceptionAssertion(data); - } + return new TestMethodWithExceptionAssertion(data); switch (data.Expected) { case bool _: - return new TestMethodBodyWithBooleanAssertion(data); + return new TestMethodWithBooleanAssertion(data); case null: - return new TestMethodBodyWithNullAssertion(data); + return new TestMethodWithNullAssertion(data); default: if ((data.Expected as object).IsEmptyEnumerable()) - return new TestMethodBodyWithEmptyAssertion(data); - - return new TestMethodBodyWithEqualityAssertion(data); + return new TestMethodWithEmptyAssertion(data); + + return new TestMethodWithEqualityAssertion(data); } } - - protected virtual void UpdateTestMethodBody(TestMethodBody body) + + protected virtual void UpdateTestMethod(TestMethod method) { } private TestData[] CreateTestData() { var testData = _canonicalData.Cases - .Select(canonicalDataCase => new TestData(_canonicalData, canonicalDataCase)) + .Select(CreateTestData) .ToArray(); Array.ForEach(testData, UpdateTestData); return testData; } + private TestData CreateTestData(CanonicalDataCase canonicalDataCase) + => new TestData(_canonicalData, canonicalDataCase); + protected virtual void UpdateTestData(TestData data) { } diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index c688df8901..e3398f8363 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -15,27 +15,27 @@ protected override void UpdateTestData(TestData data) data.SetConstructorInputParameters("score"); } - - protected override void UpdateTestMethodBody(TestMethodBody body) + + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - return body.Data.Property == "allergicTo" - ? RenderIsAllergicToAssert(body) - : body.Assert; + return method.Data.Property == "allergicTo" + ? RenderIsAllergicToAssert(method) + : method.Assert; } - private static IEnumerable RenderIsAllergicToAssert(TestMethodBody body) + private static IEnumerable RenderIsAllergicToAssert(TestMethod method) { const string template = @"{%- for allergy in Allergies -%} Assert.{% if allergy.result %}True{% else %}False{% endif %}(sut.IsAllergicTo(""{{ allergy.substance }}"")); {%- endfor -%}"; - var templateParameters = new { Allergies = body.Data.Expected }; + var templateParameters = new { Allergies = method.Data.Expected }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } } diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 161481eb58..f1d60fd032 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -37,15 +37,15 @@ protected override void UpdateNamespaces(ISet namespaces) private StringBuilder _testFactCodeLines; private void AddCodeLine(string line) => _testFactCodeLines.Append(line + "\r\n"); - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - protected IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private IEnumerable RenderAssert(TestMethod method) { _testFactCodeLines = new StringBuilder(); - var canonicalDataCase = body.Data; + var canonicalDataCase = method.Data; var input = canonicalDataCase.Properties["input"] as Dictionary; var constructorData = input["treeData"] as string[]; diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index 7fcf2adb93..ab1d8d4a46 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -23,23 +23,23 @@ protected override void UpdateTestData(TestData data) data.SetInputParameters(); } - - protected override void UpdateTestMethodBody(TestMethodBody body) + + protected override void UpdateTestMethod(TestMethod method) { - body.Arrange = RenderTestMethodBodyArrange(body); - body.Act = RenderTestMethodBodyAct(body); - body.Assert = RenderTestMethodBodyAssert(body); + method.Arrange = RenderArrange(method); + method.Act = RenderAct(method); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody body) + private static IEnumerable RenderArrange(TestMethod method) { var builder = new StringBuilder(); builder.AppendLine("var sut = new BowlingGame();"); - if (!body.Data.Input.ContainsKey(PreviousRolls)) + if (!method.Data.Input.ContainsKey(PreviousRolls)) return new[] { builder.ToString() }; - if (body.Data.Input[PreviousRolls] is int[] array) + if (method.Data.Input[PreviousRolls] is int[] array) { builder.Append("var previousRolls = new [] { "); builder.AppendJoin(", ", array); @@ -53,39 +53,39 @@ private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody bo return new[] { builder.ToString() }; } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - if (body.Data.ExceptionThrown != null && body.Data.Input.ContainsKey("roll")) + if (method.Data.ExceptionThrown != null && method.Data.Input.ContainsKey("roll")) { const string template = "Assert.Throws(() => sut.Roll({{RollVal}}));"; var templateParams = new { - RollVal = body.Data.Input["roll"] + RollVal = method.Data.Input["roll"] }; return new[] { TemplateRenderer.RenderInline(template, templateParams) }; } - if (body.Data.ExceptionThrown == null || - body.Data.Property != "score") - return body.Assert; + if (method.Data.ExceptionThrown == null || + method.Data.Property != "score") + return method.Assert; const string throwTemplate = "Assert.Throws(() => sut.Score());"; return new[] { throwTemplate }; } - private static IEnumerable RenderTestMethodBodyAct(TestMethodBody body) + private static IEnumerable RenderAct(TestMethod method) { var template = @"DoRoll(previousRolls, sut); "; - if (body.Data.ExceptionThrown != null) + if (method.Data.ExceptionThrown != null) { return new[] { template }; } - if (body.Data.Input.ContainsKey("roll")) + if (method.Data.Input.ContainsKey("roll")) { template += @"sut.Roll({{RolVal}}); @@ -93,7 +93,7 @@ private static IEnumerable RenderTestMethodBodyAct(TestMethodBody body) "; var templateParameters = new { - RolVal = body.Data.Input["roll"] + RolVal = method.Data.Input["roll"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } @@ -118,7 +118,7 @@ public void DoRoll(ICollection rolls, BowlingGame sut) } }"); } - + protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(Array).Namespace); diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index 0a655e38b9..5adb4ccbc6 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -6,16 +6,16 @@ namespace Exercism.CSharp.Exercises.Generators { public class CircularBuffer : GeneratorExercise { - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - yield return RenderSut(body.Data); + yield return RenderSut(method.Data); - foreach (var operation in body.Data.Input["operations"]) + foreach (var operation in method.Data.Input["operations"]) yield return RenderOperation(operation); } diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 928bed6c69..b748f2fc8a 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -37,35 +37,35 @@ protected override void UpdateTestData(TestData data) data.TestedMethod = "Equals"; } } - - protected override void UpdateTestMethodBody(TestMethodBody body) + + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - if (body.Data.Property == PropertyEqual) + if (method.Data.Property == PropertyEqual) { - return RenderEqualToAssert(body); + return RenderEqualToAssert(method); } - return body.Data.Property != PropertyCreate - ? RenderConsistencyToAssert(body) - : body.Assert; + return method.Data.Property != PropertyCreate + ? RenderConsistencyToAssert(method) + : method.Assert; } - private static IEnumerable RenderConsistencyToAssert(TestMethodBody body) + private static IEnumerable RenderConsistencyToAssert(TestMethod method) { const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString());"; - return new[] { TemplateRenderer.RenderInline(template, new { body.ExpectedParameter, body.TestedValue }) }; + return new[] { TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }) }; } - private static IEnumerable RenderEqualToAssert(TestMethodBody body) + private static IEnumerable RenderEqualToAssert(TestMethod method) { - var expectedParameter = body.Data.Input[ParamClock1]; + var expectedParameter = method.Data.Input[ParamClock1]; const string testedValue = "sut"; - var expectedEqual = body.Data.Expected; + var expectedEqual = method.Data.Expected; var assertTemplateParameters = new { expectedParameter, testedValue }; diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index 0bf6eb11cc..946c68cb5a 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -31,23 +31,23 @@ protected override void UpdateTestData(TestData data) private static string[] GetInputParameters(TestData canonicalDataCase, string constructorParamName) => canonicalDataCase.Input.Keys.Where(x => x != constructorParamName).ToArray(); - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - return body.Data.UseVariableForExpected - ? RenderComplexNumberAssert(body) - : body.Assert; + return method.Data.UseVariableForExpected + ? RenderComplexNumberAssert(method) + : method.Assert; } - private static IEnumerable RenderComplexNumberAssert(TestMethodBody body) + private static IEnumerable RenderComplexNumberAssert(TestMethod method) { const string template = "Assert.Equal({{ ExpectedParameter }}.Real(), {{ TestedValue }}.Real(), precision: 15);\r\nAssert.Equal({{ ExpectedParameter }}.Imaginary(), {{ TestedValue }}.Imaginary(), precision: 15);"; - return new[] { TemplateRenderer.RenderInline(template, new { body.ExpectedParameter, body.TestedValue}) }; + return new[] { TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }) }; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index 031e11030c..5fc0a55105 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -51,20 +51,20 @@ protected override void UpdateTestData(TestData data) data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } } - - protected override void UpdateTestMethodBody(TestMethodBody body) + + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - if (body.Data.ExceptionThrown != null) + if (method.Data.ExceptionThrown != null) { - return body.Assert; + return method.Assert; } - if (body.Data.Property == "territories") + if (method.Data.Property == "territories") { return new[] { @@ -87,10 +87,10 @@ private static string FormatOwner(dynamic owner) private static string FormatTerritory(dynamic territory) => ValueFormatter.Format((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); - + protected override void UpdateNamespaces(ISet namespaces) { - namespaces.Add(typeof(Dictionary).Namespace); + namespaces.Add(typeof(Dictionary).Namespace); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Grep.cs b/generators/Exercises/Generators/Grep.cs index 9cc79daa56..7cbf25c9e7 100644 --- a/generators/Exercises/Generators/Grep.cs +++ b/generators/Exercises/Generators/Grep.cs @@ -31,7 +31,7 @@ private static dynamic ConvertExpected(dynamic expected) protected override void UpdateTestClass(TestClass @class) { - @class.TemplateName = "TestClassDisposable"; + @class.IsDisposable = true; AddAdditionalMethods(@class); } diff --git a/generators/Exercises/Generators/Markdown.cs b/generators/Exercises/Generators/Markdown.cs index 72f2bc6a6c..9dfb31f1ab 100644 --- a/generators/Exercises/Generators/Markdown.cs +++ b/generators/Exercises/Generators/Markdown.cs @@ -8,11 +8,7 @@ protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; - } - - protected override void UpdateTestMethod(TestMethod method) - { - method.Skip = false; + data.Skip = false; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index b8dbd664be..e885df4482 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -30,16 +30,16 @@ protected override void UpdateTestData(TestData data) new UnescapedValue($"DayOfWeek.{((string)data.Input[ParamDayOfWeek]).Transform(To.SentenceCase)}"); } - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString(\"yyyy-MM-dd\"));"; - return new[] { TemplateRenderer.RenderInline(template, new { body.ExpectedParameter, body.TestedValue }) }; + return new[] { TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }) }; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index 5208dc2439..fdc7423e9d 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -26,37 +26,37 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(Dictionary).Namespace); } - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - return body.Data.UseVariableForExpected - ? RenderEqualBodyAssert(body) - : RenderThrowsBodyAssert(body); + return method.Data.UseVariableForExpected + ? RenderEqualAssert(method) + : RenderThrowsAssert(method); } - private static IEnumerable RenderEqualBodyAssert(TestMethodBody body) + private static IEnumerable RenderEqualAssert(TestMethod method) { const string template = @"Assert.Equal(expected, sut.{{ TestedMethodName }});"; var templateParameters = new { - TestedMethodName = body.Data.Property.ToTestedMethodName() + TestedMethodName = method.Data.Property.ToTestedMethodName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private static IEnumerable RenderThrowsBodyAssert(TestMethodBody body) + private static IEnumerable RenderThrowsAssert(TestMethod method) { const string template = @"Assert.Throws(() => new NucleotideCount(""{{ Input }}""));"; var templateParameters = new { - Input = body.Data.Input["strand"] + Input = method.Data.Input["strand"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index 8f7e9f0f34..7e9fa0324c 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -21,17 +21,17 @@ protected override void UpdateTestData(TestData data) data.Expected = (data.Expected["value"], FormatCoordinates(data.Expected["factors"])); } } - - protected override void UpdateTestMethodBody(TestMethodBody body) + + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - if (body.Data.ExceptionThrown != null) + if (method.Data.ExceptionThrown != null) { - return body.Assert; + return method.Assert; } return new[] diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index 912fd3843f..cfe095e5bb 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -12,31 +12,31 @@ protected override void UpdateTestData(TestData data) if (data.Property == "create") SetCreatePropertyData(data); } - - protected override void UpdateTestMethodBody(TestMethodBody body) + + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - if (body.Data.Property == "canAttack") - return new[] { RenderCanAttackAssert(body) }; + if (method.Data.Property == "canAttack") + return new[] { RenderCanAttackAssert(method) }; - return body.Data.UseVariableForTested + return method.Data.UseVariableForTested ? Array.Empty() - : body.Assert; + : method.Assert; } - private static string RenderCanAttackAssert(TestMethodBody body) + private static string RenderCanAttackAssert(TestMethod method) { const string template = @"var whiteQueen = QueenAttack.Create({{whiteQueenX}},{{whiteQueenY}}); var blackQueen = QueenAttack.Create({{blackQueenX}},{{blackQueenY}}); Assert.{% if Expected %}True{% else %}False{% endif %}(QueenAttack.CanAttack(whiteQueen, blackQueen));"; - var whiteQueenPositions = GetCoordinatesFromPosition(body.Data.Input["white_queen"]); - var blackQueenPositions = GetCoordinatesFromPosition(body.Data.Input["black_queen"]); + var whiteQueenPositions = GetCoordinatesFromPosition(method.Data.Input["white_queen"]); + var blackQueenPositions = GetCoordinatesFromPosition(method.Data.Input["black_queen"]); var templateParameters = new { @@ -44,7 +44,7 @@ private static string RenderCanAttackAssert(TestMethodBody body) whiteQueenY = whiteQueenPositions.Item2, blackQueenX = blackQueenPositions.Item1, blackQueenY = blackQueenPositions.Item2, - body.Data.Expected + method.Data.Expected }; return TemplateRenderer.RenderInline(template, templateParameters); diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index 811c2c64d3..bd7caa9735 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -17,17 +17,17 @@ public RationalNumber(IReadOnlyList n) } public class RationalNumbers : GeneratorExercise - { - protected override void UpdateTestMethodBody(TestMethodBody body) + { + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - var input = body.Data.Properties["input"] as Dictionary; - var operation = body.Data.Properties["property"].ToString(); - var expected = body.Data.Properties["expected"]; + var input = method.Data.Properties["input"] as Dictionary; + var operation = method.Data.Properties["property"].ToString(); + var expected = method.Data.Properties["expected"]; var operationName = char.ToUpper(operation[0]) + operation.Substring(1); var assertCodeLine = ""; const string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; diff --git a/generators/Exercises/Generators/React.cs b/generators/Exercises/Generators/React.cs index a27cce5e9a..02c3d7d68f 100644 --- a/generators/Exercises/Generators/React.cs +++ b/generators/Exercises/Generators/React.cs @@ -9,22 +9,22 @@ namespace Exercism.CSharp.Exercises.Generators { public class React : GeneratorExercise - { - protected override void UpdateTestMethodBody(TestMethodBody body) + { + protected override void UpdateTestMethod(TestMethod method) { - body.Arrange = RenderTestMethodBodyArrange(body); - body.Assert = RenderTestMethodBodyAssert(); + method.Arrange = RenderArrange(method); + method.Assert = RenderAssert(); } - private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody body) + private static IEnumerable RenderArrange(TestMethod method) { var arrange = new StringBuilder(); arrange.AppendLine("var sut = new Reactor();"); - var cells = RenderCells(body.Data.Input["cells"]); + var cells = RenderCells(method.Data.Input["cells"]); arrange.AppendLine(cells); - var operations = RenderOperations(body.Data.Input["operations"]); + var operations = RenderOperations(method.Data.Input["operations"]); arrange.AppendLine(operations); return new[] { arrange.ToString() }; @@ -125,9 +125,9 @@ private static string RenderOperation(dynamic operation) } } - private static IEnumerable RenderTestMethodBodyAssert() + private static IEnumerable RenderAssert() => new[] { "" }; - + protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(EventHandler).Namespace); diff --git a/generators/Exercises/Generators/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs index 00aadb7cd0..eac2b4c4f3 100644 --- a/generators/Exercises/Generators/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -26,50 +26,50 @@ protected override void UpdateTestData(TestData data) data.UseFullDescriptionPath = true; } - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Act = RenderTestMethodBodyAct(body); - body.Assert = RenderTestMethodBodyAssert(body); + method.Act = RenderAct(method); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAct(TestMethodBody body) + private static IEnumerable RenderAct(TestMethod method) { - switch (body.Data.Property) + switch (method.Data.Property) { case "create": return Array.Empty(); - case "instructions": return RenderInstructionsMethodBodyAct(body); - default: return RenderDefaultMethodBodyAct(body); + case "instructions": return RenderInstructionsAct(method); + default: return RenderDefaultAct(method); } } - private static IEnumerable RenderDefaultMethodBodyAct(TestMethodBody body) + private static IEnumerable RenderDefaultAct(TestMethod method) { const string template = @"sut.{{MethodInvocation}}();"; var templateParameters = new { - MethodInvocation = body.Data.Property.ToTestedMethodName() + MethodInvocation = method.Data.Property.ToTestedMethodName() }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private static IEnumerable RenderInstructionsMethodBodyAct(TestMethodBody body) + private static IEnumerable RenderInstructionsAct(TestMethod method) { const string template = @"sut.{{MethodInvocation}}(""{{Instructions}}"");"; var templateParameters = new { MethodInvocation = "Simulate", - Instructions = body.Data.Input["instructions"] + Instructions = method.Data.Input["instructions"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - var expected = body.Data.Expected as Dictionary; + var expected = method.Data.Expected as Dictionary; expected.TryGetValue("position", out var position); expected.TryGetValue("direction", out var direction); diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index 2e29b74b7b..b0ce819a58 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -10,27 +10,27 @@ protected override void UpdateTestData(TestData data) { data.Description = $"{data.Property} {data.Description}"; } - - protected override void UpdateTestMethodBody(TestMethodBody body) + + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - return body.Data.Property == "consistency" - ? RenderConsistencyToAssert(body) - : body.Assert; + return method.Data.Property == "consistency" + ? RenderConsistencyToAssert(method) + : method.Assert; } - private static IEnumerable RenderConsistencyToAssert(TestMethodBody body) + private static IEnumerable RenderConsistencyToAssert(TestMethod method) { const string template = @"Assert.Equal(""{{Expected}}"", {{TestedClassName}}.Decode({{TestedClassName}}.Encode(""{{Expected}}"")));"; var templateParameters = new { - body.Data.Expected, - TestedClassName = body.Data.TestedClass + method.Data.Expected, + TestedClassName = method.Data.TestedClass }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index ea425159f4..80739aa9b9 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -43,23 +43,23 @@ protected override void UpdateTestData(TestData data) } } - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - switch (body.Data.Property) + switch (method.Data.Property) { case "new": - var key = ValueFormatter.Format(body.Data.Input["key"]); + var key = ValueFormatter.Format(method.Data.Input["key"]); return new[] { $"Assert.Throws(() => new SimpleCipher({key}));" }; case "key": - var pattern = ValueFormatter.Format(body.Data.Expected["match"]); + var pattern = ValueFormatter.Format(method.Data.Expected["match"]); return new[] { $"Assert.Matches({pattern}, sut.Key);" }; default: - return body.Assert; + return method.Assert; } } diff --git a/generators/Exercises/Generators/Tournament.cs b/generators/Exercises/Generators/Tournament.cs index dd52d60be3..cbf9076d50 100644 --- a/generators/Exercises/Generators/Tournament.cs +++ b/generators/Exercises/Generators/Tournament.cs @@ -19,21 +19,21 @@ protected override void UpdateTestData(TestData data) data.Input["rows"] = ConvertHelper.ToMultiLineString(data.Input["rows"], ""); data.Expected = ConvertHelper.ToMultiLineString(data.Expected); } - + protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(Array).Namespace); namespaces.Add(typeof(Stream).Namespace); namespaces.Add(typeof(UTF8Encoding).Namespace); } - - - protected override void UpdateTestMethodBody(TestMethodBody body) + + + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(); + method.Assert = RenderAssert(); } - private static IEnumerable RenderTestMethodBodyAssert() + private static IEnumerable RenderAssert() { const string template = @"Assert.Equal(expected, RunTally(rows));"; return new[] { TemplateRenderer.RenderInline(template, new { }) }; diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index b01af91c85..6dac9cc2c0 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -15,25 +15,25 @@ protected override void UpdateTestData(TestData data) data.Input["startBucket"] = new UnescapedValue(startBucket == "two" ? "Bucket.Two" : "Bucket.One"); } - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Act = RenderTestMethodBodyAct(body); - body.Assert = RenderTestMethodBodyAssert(body); + method.Act = RenderAct(method); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAct(TestMethodBody body) + private static IEnumerable RenderAct(TestMethod method) { const string template = @"var result = {{MethodInvocation}};"; var templateParameters = new { - MethodInvocation = body.TestedMethodInvocation + MethodInvocation = method.TestedMethodInvocation }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { const string template = @"Assert.Equal({{MovesExpected}}, result.Moves); @@ -42,9 +42,9 @@ private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody bod var templateParameters = new { - MovesExpected = body.Data.Expected["moves"], - OtherBucketExpected = body.Data.Expected["otherBucket"], - GoalBucketExpected = body.Data.Expected["goalBucket"] + MovesExpected = method.Data.Expected["moves"], + OtherBucketExpected = method.Data.Expected["otherBucket"], + GoalBucketExpected = method.Data.Expected["goalBucket"] }; return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 4af70ba977..5bbd9af14a 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -34,20 +34,20 @@ protected override void UpdateTestData(TestData data) } - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Assert = RenderTestMethodBodyAssert(body); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - var expectedDictionary = body.Data.Properties["expected"] as IDictionary; + var expectedDictionary = method.Data.Properties["expected"] as IDictionary; foreach (var kv in expectedDictionary) - yield return RenderTestMethodBodyAssertForSearchWord(kv.Key, kv.Value); + yield return RenderAssertForSearchWord(kv.Key, kv.Value); } - private static string RenderTestMethodBodyAssertForSearchWord(string word, dynamic expected) + private static string RenderAssertForSearchWord(string word, dynamic expected) { return expected == null ? $"Assert.Null(expected[\"{word}\"]);" diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index 543ad90aee..51ea93d680 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -8,25 +8,25 @@ namespace Exercism.CSharp.Exercises.Generators { public class Zipper : GeneratorExercise { - protected override void UpdateTestMethodBody(TestMethodBody body) + protected override void UpdateTestMethod(TestMethod method) { - body.Arrange = RenderTestMethodBodyArrange(body); - body.Assert = RenderTestMethodBodyAssert(body); + method.Arrange = RenderArrange(method); + method.Assert = RenderAssert(method); } - private static IEnumerable RenderTestMethodBodyArrange(TestMethodBody body) + private static IEnumerable RenderArrange(TestMethod method) { - var tree = RenderTree(body.Data.Input["initialTree"]); + var tree = RenderTree(method.Data.Input["initialTree"]); yield return $"var tree = {tree};"; yield return "var sut = Zipper.FromTree(tree);"; - var operations = RenderOperations(body.Data.Input["operations"]); + var operations = RenderOperations(method.Data.Input["operations"]); yield return $"var actual = sut{operations};"; } - private static IEnumerable RenderTestMethodBodyAssert(TestMethodBody body) + private static IEnumerable RenderAssert(TestMethod method) { - var expected = RenderExpected(body.Data.Expected); + var expected = RenderExpected(method.Data.Expected); if (expected == null) { yield return "Assert.Null(actual);"; diff --git a/generators/Input/CanonicalDataCase.cs b/generators/Input/CanonicalDataCase.cs index 6f648e5a47..d9c0dcfb49 100644 --- a/generators/Input/CanonicalDataCase.cs +++ b/generators/Input/CanonicalDataCase.cs @@ -4,12 +4,13 @@ namespace Exercism.CSharp.Input { public class CanonicalDataCase { - public CanonicalDataCase(string property, IReadOnlyDictionary properties, + public CanonicalDataCase(int index, string property, IReadOnlyDictionary properties, IReadOnlyDictionary input, dynamic expected, string description, IReadOnlyCollection descriptionPath) - => (Property, Properties, Input, Expected, Description, DescriptionPath) = - (property, properties, input, expected, description, descriptionPath); + => (Index, Property, Properties, Input, Expected, Description, DescriptionPath) = + (index, property, properties, input, expected, description, descriptionPath); + public int Index { get; } public IReadOnlyDictionary Properties { get; } public IReadOnlyDictionary Input { get; } public dynamic Expected { get; } diff --git a/generators/Input/CanonicalDataCaseParser.cs b/generators/Input/CanonicalDataCaseParser.cs index 41cc4c399f..3845411fce 100644 --- a/generators/Input/CanonicalDataCaseParser.cs +++ b/generators/Input/CanonicalDataCaseParser.cs @@ -15,8 +15,9 @@ public static IReadOnlyCollection Parse(JArray canonicalDataC .Select(Parse) .ToArray(); - private static CanonicalDataCase Parse(JToken canonicalDataCaseJToken) + private static CanonicalDataCase Parse(JToken canonicalDataCaseJToken, int index) => new CanonicalDataCase( + index: index, property: canonicalDataCaseJToken.Value("property"), properties: ToReadOnlyDictionary(canonicalDataCaseJToken), input: ToReadOnlyDictionary(canonicalDataCaseJToken["input"]), diff --git a/generators/Output/Templates/_AssertThrowsException.liquid b/generators/Output/Templates/_AssertException.liquid similarity index 100% rename from generators/Output/Templates/_AssertThrowsException.liquid rename to generators/Output/Templates/_AssertException.liquid diff --git a/generators/Output/Templates/_TestClass.liquid b/generators/Output/Templates/_TestClass.liquid index 6fd4a50e16..e351af4ef0 100644 --- a/generators/Output/Templates/_TestClass.liquid +++ b/generators/Output/Templates/_TestClass.liquid @@ -1,10 +1,10 @@ // This file was auto-generated based on version {{CanonicalDataVersion}} of the canonical data. -{%- for namespace in UsingNamespaces -%} +{%- for namespace in Namespaces -%} using {{ namespace }}; {%- endfor -%} -public class {{ClassName}} +public class {{ClassName}}{% if IsDisposable %} : IDisposable{% endif %} { {%- for method in Methods -%} {{ method | indent }} diff --git a/generators/Output/Templates/_TestClassDisposable.liquid b/generators/Output/Templates/_TestClassDisposable.liquid deleted file mode 100644 index f46dcdec94..0000000000 --- a/generators/Output/Templates/_TestClassDisposable.liquid +++ /dev/null @@ -1,14 +0,0 @@ -// This file was auto-generated based on version {{CanonicalDataVersion}} of the canonical data. - -{%- for namespace in UsingNamespaces -%} -using {{ namespace }}; -{%- endfor -%} - -public class {{ClassName}} : IDisposable -{ -{%- for method in Methods -%} -{{ method | indent }} -{%- if forloop.last == false %} -{% endif -%} -{%- endfor -%} -} \ No newline at end of file diff --git a/generators/Output/Templates/_TestMethod.liquid b/generators/Output/Templates/_TestMethod.liquid index f4960c1a34..5da69bb1bc 100644 --- a/generators/Output/Templates/_TestMethod.liquid +++ b/generators/Output/Templates/_TestMethod.liquid @@ -1,5 +1,7 @@ [Fact{% if Skip %}(Skip = "Remove to run test"){% endif %}] public void {{ Name }}() { -{{ Body | indent }} +{%- for line in Lines -%} +{{ line | indent }} +{%- endfor -%} } \ No newline at end of file diff --git a/generators/Output/Templates/_TestMethodBody.liquid b/generators/Output/Templates/_TestMethodBody.liquid deleted file mode 100644 index 06c3d49ec3..0000000000 --- a/generators/Output/Templates/_TestMethodBody.liquid +++ /dev/null @@ -1,9 +0,0 @@ -{%- for arrange in Arrange -%} -{{ arrange }} -{%- endfor -%} -{%- for act in Act -%} -{{ act }} -{%- endfor -%} -{%- for assert in Assert -%} -{{ assert }} -{%- endfor -%} \ No newline at end of file diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index e04cdede38..503051909a 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -4,14 +4,16 @@ namespace Exercism.CSharp.Output { public class TestClass - { + { + private const string TemplateName = "TestClass"; + public string Exercise { get; set; } public string ClassName { get; set; } public string CanonicalDataVersion { get; set; } - public IList Methods { get; set; } + public ICollection Methods { get; set; } public ISet Namespaces { get; set; } - public string TemplateName { get; set; } = "TestClass"; + public bool IsDisposable { get; set; } - public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { ClassName, CanonicalDataVersion, Methods, UsingNamespaces = Namespaces }); + public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { ClassName, CanonicalDataVersion, Methods, Namespaces, IsDisposable }); } } \ No newline at end of file diff --git a/generators/Output/TestData.cs b/generators/Output/TestData.cs index 20448a5e9e..fce92a47e3 100644 --- a/generators/Output/TestData.cs +++ b/generators/Output/TestData.cs @@ -23,6 +23,8 @@ public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); + Skip = canonicalDataCase.Index > 0; + TestedClass = canonicalData.Exercise.ToTestedClassName(); TestedMethod = canonicalDataCase.Property.ToTestedMethodName(); } @@ -37,6 +39,8 @@ public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase public string Description { get; set; } public IList DescriptionPath { get; set; } + public bool Skip { get; set; } + public bool UseVariablesForInput { get; set; } public bool UseVariableForExpected { get; set; } public bool UseVariablesForConstructorParameters { get; set; } diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index ac08cd4ac9..9aad61ca93 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -1,14 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Exercism.CSharp.Exercises; +using Exercism.CSharp.Helpers; using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Output { - public class TestMethod + public abstract class TestMethod { - public bool Skip { get; set; } - public string Name { get; set; } - public TestMethodBody Body { get; set; } - public string TemplateName { get; set; } = "TestMethod"; + private const string SutVariableName = "sut"; + private const string TestedVariableName = "actual"; + private const string ExpectedVariableName = "expected"; + private const string TemplateName = "TestMethod"; - public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { Name, Body = Body.Render(), Skip }); + protected TestMethod(TestData data) => Data = data; + + public TestData Data { get; } + + public string ArrangeTemplateName { get; set; } = "Arrange"; + public object ArrangeTemplateParameters { get; set; } + + public string ActTemplateName { get; set; } = "Act"; + public object ActTemplateParameters { get; set; } + + public string AssertTemplateName { get; set; } = "AssertEqual"; + public object AssertTemplateParameters { get; set; } + + public IEnumerable Act { get; set; } + public IEnumerable Arrange { get; set; } + public IEnumerable Assert { get; set; } + + private IEnumerable Lines => + Arrange.Concat(Act).Concat(Assert).Where(line => !string.IsNullOrWhiteSpace(line)); + + public string Render() + { + ArrangeTemplateParameters = ArrangeTemplateParameters ?? new { Variables }; + ActTemplateParameters = ActTemplateParameters ?? new { }; + AssertTemplateParameters = AssertTemplateParameters ?? new { ExpectedParameter, TestedValue }; + + Arrange = Arrange ?? RenderArrange(); + Act = Act ?? RenderAct(); + Assert = Assert ?? RenderAssert(); + + return TemplateRenderer.RenderPartial(TemplateName, new { Name = Data.TestMethod, Data.Skip, Lines }); + } + + public string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; + public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Data.Expected); + + private string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); + private string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); + + private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); + private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); + + private IEnumerable InputVariablesDeclaration => ValueFormatter.FormatVariables(Input); + private IEnumerable ExpectedVariableDeclaration => ValueFormatter.FormatVariable(Data.Expected, ExpectedVariableName); + private IEnumerable ConstructorVariablesDeclaration => ValueFormatter.FormatVariables(ConstructorInput); + private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {Data.TestedClass}({ConstructorParameters});" }; + private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; + + public IEnumerable Variables + { + get + { + var lines = new List(); + + if (Data.UseVariablesForInput) + lines.AddRange(InputVariablesDeclaration); + + if (Data.UseVariablesForConstructorParameters) + lines.AddRange(ConstructorVariablesDeclaration); + + if (Data.TestedMethodType == TestedMethodType.Instance) + lines.AddRange(SutVariableDeclaration); + + if (Data.UseVariableForTested) + lines.AddRange(ActualVariableDeclaration); + + if (Data.UseVariableForExpected) + lines.AddRange(ExpectedVariableDeclaration); + + return lines; + } + } + + public string TestedMethodInvocation + { + get + { + switch (Data.TestedMethodType) + { + case TestedMethodType.Static: + return $"{Data.TestedClass}.{Data.TestedMethod}({InputParameters})"; + case TestedMethodType.Instance: + return $"{SutVariableName}.{Data.TestedMethod}({InputParameters})"; + case TestedMethodType.Extension: + return $"{InputParameters}.{Data.TestedMethod}()"; + default: + throw new ArgumentOutOfRangeException(); + } + } + } + + private IEnumerable RenderArrange() + => new[] { TemplateRenderer.RenderPartial(ArrangeTemplateName, ArrangeTemplateParameters) }; + + private IEnumerable RenderAct() + => new[] { TemplateRenderer.RenderPartial(ActTemplateName, ActTemplateParameters) }; + + private IEnumerable RenderAssert() + => new[] { TemplateRenderer.RenderPartial(AssertTemplateName, AssertTemplateParameters) }; } } \ No newline at end of file diff --git a/generators/Output/TestMethodBody.cs b/generators/Output/TestMethodBody.cs deleted file mode 100644 index e5f5de3c08..0000000000 --- a/generators/Output/TestMethodBody.cs +++ /dev/null @@ -1,114 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Exercism.CSharp.Exercises; -using Exercism.CSharp.Helpers; -using Exercism.CSharp.Output.Templates; - -namespace Exercism.CSharp.Output -{ - public abstract class TestMethodBody - { - private const string SutVariableName = "sut"; - private const string TestedVariableName = "actual"; - private const string ExpectedVariableName = "expected"; - - protected TestMethodBody(TestData data) => Data = data; - - public string TemplateName { get; } = "TestMethodBody"; - - public TestData Data { get; } - - public string ArrangeTemplateName { get; set; } = "Arrange"; - public object ArrangeTemplateParameters { get; set; } - - public string ActTemplateName { get; set; } = "Act"; - public object ActTemplateParameters { get; set; } - - public string AssertTemplateName { get; set; } = "AssertEqual"; - public object AssertTemplateParameters { get; set; } - - public IEnumerable Act { get; set; } - public IEnumerable Arrange { get; set; } - public IEnumerable Assert { get; set; } - - public virtual string Render() - { - ArrangeTemplateParameters = ArrangeTemplateParameters ?? new { Variables }; - ActTemplateParameters = ActTemplateParameters ?? new { }; - AssertTemplateParameters = AssertTemplateParameters ?? new { ExpectedParameter, TestedValue }; - - Arrange = Arrange ?? RenderTestMethodBodyArrange(); - Act = Act ?? RenderTestMethodBodyAct(); - Assert = Assert ?? RenderTestMethodBodyAssert(); - - return TemplateRenderer.RenderPartial(TemplateName, new { Arrange, Act, Assert }); - } - - public string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; - protected string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); - public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Data.Expected); - protected string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); - - private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); - private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); - - private IEnumerable InputVariablesDeclaration => ValueFormatter.FormatVariables(Input); - private IEnumerable ExpectedVariableDeclaration => ValueFormatter.FormatVariable(Data.Expected, ExpectedVariableName); - private IEnumerable ConstructorVariablesDeclaration => ValueFormatter.FormatVariables(ConstructorInput); - private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {Data.TestedClass}({ConstructorParameters});" }; - private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; - - public IEnumerable Variables - { - get - { - var lines = new List(); - - if (Data.UseVariablesForInput) - lines.AddRange(InputVariablesDeclaration); - - if (Data.UseVariablesForConstructorParameters) - lines.AddRange(ConstructorVariablesDeclaration); - - if (Data.TestedMethodType == TestedMethodType.Instance) - lines.AddRange(SutVariableDeclaration); - - if (Data.UseVariableForTested) - lines.AddRange(ActualVariableDeclaration); - - if (Data.UseVariableForExpected) - lines.AddRange(ExpectedVariableDeclaration); - - return lines; - } - } - - public string TestedMethodInvocation - { - get - { - switch (Data.TestedMethodType) - { - case TestedMethodType.Static: - return $"{Data.TestedClass}.{Data.TestedMethod}({InputParameters})"; - case TestedMethodType.Instance: - return $"{SutVariableName}.{Data.TestedMethod}({InputParameters})"; - case TestedMethodType.Extension: - return $"{InputParameters}.{Data.TestedMethod}()"; - default: - throw new ArgumentOutOfRangeException(); - } - } - } - - private IEnumerable RenderTestMethodBodyArrange() - => new[] { TemplateRenderer.RenderPartial(ArrangeTemplateName, ArrangeTemplateParameters) }; - - private IEnumerable RenderTestMethodBodyAct() - => new[] { TemplateRenderer.RenderPartial(ActTemplateName, ActTemplateParameters) }; - - private IEnumerable RenderTestMethodBodyAssert() - => new[] { TemplateRenderer.RenderPartial(AssertTemplateName, AssertTemplateParameters) }; - } -} \ No newline at end of file diff --git a/generators/Output/TestMethodBodyWithBooleanAssertion.cs b/generators/Output/TestMethodWithBooleanAssertion.cs similarity index 67% rename from generators/Output/TestMethodBodyWithBooleanAssertion.cs rename to generators/Output/TestMethodWithBooleanAssertion.cs index c822fcfa76..e70fb41c17 100644 --- a/generators/Output/TestMethodBodyWithBooleanAssertion.cs +++ b/generators/Output/TestMethodWithBooleanAssertion.cs @@ -2,9 +2,9 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithBooleanAssertion : TestMethodBody + public class TestMethodWithBooleanAssertion : TestMethod { - public TestMethodBodyWithBooleanAssertion(TestData data) : base(data) + public TestMethodWithBooleanAssertion(TestData data) : base(data) { AssertTemplateName = "AssertBoolean"; AssertTemplateParameters = new { BooleanAssertMethod, TestedValue }; diff --git a/generators/Output/TestMethodBodyWithEmptyAssertion.cs b/generators/Output/TestMethodWithEmptyAssertion.cs similarity index 64% rename from generators/Output/TestMethodBodyWithEmptyAssertion.cs rename to generators/Output/TestMethodWithEmptyAssertion.cs index e17f2d4e27..f821d93133 100644 --- a/generators/Output/TestMethodBodyWithEmptyAssertion.cs +++ b/generators/Output/TestMethodWithEmptyAssertion.cs @@ -1,8 +1,8 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithEmptyAssertion : TestMethodBody + public class TestMethodWithEmptyAssertion : TestMethod { - public TestMethodBodyWithEmptyAssertion(TestData data) : base(data) + public TestMethodWithEmptyAssertion(TestData data): base(data) { Data.UseVariableForExpected = false; diff --git a/generators/Output/TestMethodBodyWithEqualityAssertion.cs b/generators/Output/TestMethodWithEqualityAssertion.cs similarity index 56% rename from generators/Output/TestMethodBodyWithEqualityAssertion.cs rename to generators/Output/TestMethodWithEqualityAssertion.cs index d41408ab46..930a07e2ba 100644 --- a/generators/Output/TestMethodBodyWithEqualityAssertion.cs +++ b/generators/Output/TestMethodWithEqualityAssertion.cs @@ -1,8 +1,8 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithEqualityAssertion : TestMethodBody + public class TestMethodWithEqualityAssertion : TestMethod { - public TestMethodBodyWithEqualityAssertion(TestData data) : base(data) + public TestMethodWithEqualityAssertion(TestData data) : base(data) { AssertTemplateName = "AssertEqual"; AssertTemplateParameters = new { ExpectedParameter, TestedValue }; diff --git a/generators/Output/TestMethodBodyWithExceptionAssertion.cs b/generators/Output/TestMethodWithExceptionAssertion.cs similarity index 59% rename from generators/Output/TestMethodBodyWithExceptionAssertion.cs rename to generators/Output/TestMethodWithExceptionAssertion.cs index 02998f2c4c..68a07d6e19 100644 --- a/generators/Output/TestMethodBodyWithExceptionAssertion.cs +++ b/generators/Output/TestMethodWithExceptionAssertion.cs @@ -1,13 +1,13 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithExceptionAssertion : TestMethodBody + public class TestMethodWithExceptionAssertion : TestMethod { - public TestMethodBodyWithExceptionAssertion(TestData data) : base(data) + public TestMethodWithExceptionAssertion(TestData data) : base(data) { Data.UseVariableForExpected = false; Data.UseVariableForTested = false; - AssertTemplateName = "AssertThrowsException"; + AssertTemplateName = "AssertException"; AssertTemplateParameters = new { ExceptionType, TestedValue }; } diff --git a/generators/Output/TestMethodBodyWithNullAssertion.cs b/generators/Output/TestMethodWithNullAssertion.cs similarity index 55% rename from generators/Output/TestMethodBodyWithNullAssertion.cs rename to generators/Output/TestMethodWithNullAssertion.cs index 34a05854e8..0efd279975 100644 --- a/generators/Output/TestMethodBodyWithNullAssertion.cs +++ b/generators/Output/TestMethodWithNullAssertion.cs @@ -1,8 +1,8 @@ namespace Exercism.CSharp.Output { - public class TestMethodBodyWithNullAssertion : TestMethodBody + public class TestMethodWithNullAssertion : TestMethod { - public TestMethodBodyWithNullAssertion(TestData data) : base(data) + public TestMethodWithNullAssertion(TestData data) : base(data) { AssertTemplateName = "AssertNull"; AssertTemplateParameters = new { TestedValue }; From a423ec159fe57f43b1a291bb1e8f26d493727956 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 25 Jun 2018 16:44:07 +0200 Subject: [PATCH 35/97] generators: Make lifecycle of update methods be more sane --- .../rational-numbers/RationalNumbersTest.cs | 2 +- generators/Exercises/GeneratorExercise.cs | 44 ++++++++----------- .../Exercises/Generators/BinarySearchTree.cs | 6 +-- generators/Exercises/Generators/Matrix.cs | 2 - .../Exercises/Generators/RationalNumbers.cs | 18 ++++---- generators/Exercises/Generators/WordSearch.cs | 20 ++++----- generators/Input/CanonicalDataCase.cs | 10 ++--- generators/Input/CanonicalDataCaseParser.cs | 1 - generators/Output/TestData.cs | 6 +-- 9 files changed, 47 insertions(+), 62 deletions(-) diff --git a/exercises/rational-numbers/RationalNumbersTest.cs b/exercises/rational-numbers/RationalNumbersTest.cs index 0db57b440e..94ec6118f0 100644 --- a/exercises/rational-numbers/RationalNumbersTest.cs +++ b/exercises/rational-numbers/RationalNumbersTest.cs @@ -175,7 +175,7 @@ public void Raise_a_real_number_to_a_positive_rational_number() [Fact(Skip = "Remove to run test")] public void Raise_a_real_number_to_a_negative_rational_number() { - Assert.Equal(0.333333333333333, 9.Expreal(new RationalNumber(-1, 2)), 15); + Assert.Equal(0.3333333, 9.Expreal(new RationalNumber(-1, 2)), 7); } [Fact(Skip = "Remove to run test")] diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index 85d1b1dce5..9bfa910314 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -31,8 +31,8 @@ private TestClass CreateTestClass() Exercise = _canonicalData.Exercise, CanonicalDataVersion = _canonicalData.Version, ClassName = _canonicalData.Exercise.ToTestClassName(), - Namespaces = GetNamespaces(), - Methods = RenderTestMethods() + Methods = GetMethods(), + Namespaces = GetNamespaces() }; UpdateTestClass(testClass); @@ -61,19 +61,21 @@ protected virtual void UpdateNamespaces(ISet namespaces) { } - private IList RenderTestMethods() - => CreateTestMethods() - .Select(testMethod => testMethod.Render()) - .ToList(); - - private IEnumerable CreateTestMethods() + private IList GetMethods() { - var testMethods = _testData - .Select(CreateTestMethod) - .ToArray(); - - Array.ForEach(testMethods, UpdateTestMethod); - return testMethods; + var renderedMethods = new List(); + + foreach (var data in _testData) + { + UpdateTestData(data); + + var method = CreateTestMethod(data); + UpdateTestMethod(method); + + renderedMethods.Add(method.Render()); + } + + return renderedMethods; } private static TestMethod CreateTestMethod(TestData data) @@ -99,18 +101,10 @@ protected virtual void UpdateTestMethod(TestMethod method) { } - private TestData[] CreateTestData() - { - var testData = _canonicalData.Cases - .Select(CreateTestData) + private TestData[] CreateTestData() => + _canonicalData.Cases + .Select(canonicalDataCase => new TestData(_canonicalData, canonicalDataCase)) .ToArray(); - - Array.ForEach(testData, UpdateTestData); - return testData; - } - - private TestData CreateTestData(CanonicalDataCase canonicalDataCase) - => new TestData(_canonicalData, canonicalDataCase); protected virtual void UpdateTestData(TestData data) { diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index f1d60fd032..2384e109d3 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -46,7 +46,7 @@ private IEnumerable RenderAssert(TestMethod method) { _testFactCodeLines = new StringBuilder(); var canonicalDataCase = method.Data; - var input = canonicalDataCase.Properties["input"] as Dictionary; + var input = canonicalDataCase.Input as Dictionary; var constructorData = input["treeData"] as string[]; if (constructorData.Length == 1) AddCodeLine($"var tree = new BinarySearchTree({constructorData[0]});"); @@ -56,7 +56,7 @@ private IEnumerable RenderAssert(TestMethod method) AddCodeLine($"var tree = new BinarySearchTree(new[] {{ {constructorDataString} }});"); } - if (canonicalDataCase.Properties["expected"] is Dictionary expected) + if (canonicalDataCase.Expected is Dictionary expected) { var tree = new ExpectedDataBinaryTree(expected); foreach (var assert in tree.TestAsserts()) @@ -64,7 +64,7 @@ private IEnumerable RenderAssert(TestMethod method) } else { - var expectedArrayString = string.Join(", ", canonicalDataCase.Properties["expected"] as string[]); + var expectedArrayString = string.Join(", ", canonicalDataCase.Expected as string[]); AddCodeLine($"Assert.Equal(new[] {{ {expectedArrayString} }}, tree.AsEnumerable());"); } diff --git a/generators/Exercises/Generators/Matrix.cs b/generators/Exercises/Generators/Matrix.cs index f837da89a4..dcc89b57b3 100644 --- a/generators/Exercises/Generators/Matrix.cs +++ b/generators/Exercises/Generators/Matrix.cs @@ -6,9 +6,7 @@ public class Matrix : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Properties["string"] = data.Properties["input"]["string"]; data.SetConstructorInputParameters("string"); - data.Properties["index"] = data.Properties["input"]["index"]; data.SetInputParameters("index"); } } diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index bd7caa9735..d97396489d 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -25,15 +25,13 @@ protected override void UpdateTestMethod(TestMethod method) private static IEnumerable RenderAssert(TestMethod method) { - var input = method.Data.Properties["input"] as Dictionary; - var operation = method.Data.Properties["property"].ToString(); - var expected = method.Data.Properties["expected"]; - var operationName = char.ToUpper(operation[0]) + operation.Substring(1); + var input = (Dictionary)method.Data.Input; + var operationName = char.ToUpper(method.Data.Property[0]) + method.Data.Property.Substring(1); var assertCodeLine = ""; const string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; - string operationCode = operationsWithOverloading.Substring(operationsWithOverloading.IndexOf(operation.ToLower()) + 4, 1); + var operationCode = operationsWithOverloading.Substring(operationsWithOverloading.IndexOf(method.Data.Property.ToLower()) + 4, 1); - switch (operation.ToLower()) + switch (method.Data.Property.ToLower()) { case "add": case "sub": @@ -42,7 +40,7 @@ private static IEnumerable RenderAssert(TestMethod method) { var r1 = new RationalNumber((int[])input["r1"]); var r2 = new RationalNumber((int[])input["r2"]); - var e = new RationalNumber((int[])expected); + var e = new RationalNumber((int[])method.Data.Expected); assertCodeLine = "Assert.Equal(" + $"new RationalNumber ({e.Numerator}, {e.Denominator}), new RationalNumber({r1.Numerator}, {r1.Denominator}) {operationCode} (new RationalNumber({r2.Numerator}, {r2.Denominator})));"; } break; @@ -50,7 +48,7 @@ private static IEnumerable RenderAssert(TestMethod method) case "reduce": { var r = new RationalNumber((int[])input["r"]); - var e = new RationalNumber((int[])expected); + var e = new RationalNumber((int[])method.Data.Expected); assertCodeLine = "Assert.Equal(" + $"new RationalNumber ({e.Numerator}, {e.Denominator}), new RationalNumber({r.Numerator}, {r.Denominator}).{operationName}());"; } break; @@ -58,7 +56,7 @@ private static IEnumerable RenderAssert(TestMethod method) { var r = new RationalNumber((int[])input["r"]); var n = input["n"]; - var e = new RationalNumber((int[])expected); + var e = new RationalNumber((int[])method.Data.Expected); assertCodeLine = "Assert.Equal(" + $"new RationalNumber ({e.Numerator}, {e.Denominator}), new RationalNumber({r.Numerator}, {r.Denominator}).{operationName}({n}));"; } break; @@ -66,7 +64,7 @@ private static IEnumerable RenderAssert(TestMethod method) { var x = input["x"].ToString(); var r = new RationalNumber((int[])input["r"]); - var e = ValueFormatter.Format(expected); + var e = ValueFormatter.Format(method.Data.Expected); var p = Precision(e); assertCodeLine = "Assert.Equal(" + $"{e}, {x}.{operationName}(new RationalNumber({r.Numerator}, {r.Denominator})), {p});"; } diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 5bbd9af14a..7602f6f0a5 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Helpers; @@ -8,6 +9,8 @@ namespace Exercism.CSharp.Exercises.Generators { public class WordSearch : GeneratorExercise { + private IDictionary _expectedDictionary; + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; @@ -19,7 +22,7 @@ protected override void UpdateTestData(TestData data) data.Input["grid"] = ConvertHelper.ToMultiLineString(data.Input["grid"]); - var expectedDictionary = data.Expected as IDictionary; + _expectedDictionary = (IDictionary)data.Expected; var expected = new List { @@ -27,7 +30,7 @@ protected override void UpdateTestData(TestData data) "{" }; - expected.AddRange(expectedDictionary.Select((kv, i) => $" [\"{kv.Key}\"] = {FormatPosition(kv.Value)}{(i < expectedDictionary.Count - 1 ? "," : "")}")); + expected.AddRange(_expectedDictionary.Select((kv, i) => $" [\"{kv.Key}\"] = {FormatPosition(kv.Value)}{(i < _expectedDictionary.Count - 1 ? "," : "")}")); expected.Add("}"); data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); @@ -36,16 +39,13 @@ protected override void UpdateTestData(TestData data) protected override void UpdateTestMethod(TestMethod method) { - method.Assert = RenderAssert(method); + method.Assert = RenderAssert(); } - private static IEnumerable RenderAssert(TestMethod method) - { - var expectedDictionary = method.Data.Properties["expected"] as IDictionary; - - foreach (var kv in expectedDictionary) - yield return RenderAssertForSearchWord(kv.Key, kv.Value); - } + private IEnumerable RenderAssert() + => _expectedDictionary + .Select(kv => RenderAssertForSearchWord(kv.Key, kv.Value)) + .Cast(); private static string RenderAssertForSearchWord(string word, dynamic expected) { diff --git a/generators/Input/CanonicalDataCase.cs b/generators/Input/CanonicalDataCase.cs index d9c0dcfb49..c832eb378a 100644 --- a/generators/Input/CanonicalDataCase.cs +++ b/generators/Input/CanonicalDataCase.cs @@ -4,14 +4,12 @@ namespace Exercism.CSharp.Input { public class CanonicalDataCase { - public CanonicalDataCase(int index, string property, IReadOnlyDictionary properties, - IReadOnlyDictionary input, dynamic expected, - string description, IReadOnlyCollection descriptionPath) - => (Index, Property, Properties, Input, Expected, Description, DescriptionPath) = - (index, property, properties, input, expected, description, descriptionPath); + public CanonicalDataCase(int index, string property, IReadOnlyDictionary input, + dynamic expected, string description, IReadOnlyCollection descriptionPath) + => (Index, Property, Input, Expected, Description, DescriptionPath) = + (index, property, input, expected, description, descriptionPath); public int Index { get; } - public IReadOnlyDictionary Properties { get; } public IReadOnlyDictionary Input { get; } public dynamic Expected { get; } public string Property { get; } diff --git a/generators/Input/CanonicalDataCaseParser.cs b/generators/Input/CanonicalDataCaseParser.cs index 3845411fce..82f6ccc240 100644 --- a/generators/Input/CanonicalDataCaseParser.cs +++ b/generators/Input/CanonicalDataCaseParser.cs @@ -19,7 +19,6 @@ private static CanonicalDataCase Parse(JToken canonicalDataCaseJToken, int index => new CanonicalDataCase( index: index, property: canonicalDataCaseJToken.Value("property"), - properties: ToReadOnlyDictionary(canonicalDataCaseJToken), input: ToReadOnlyDictionary(canonicalDataCaseJToken["input"]), expected: ConvertJToken(canonicalDataCaseJToken["expected"]), description: canonicalDataCaseJToken.Value("description"), diff --git a/generators/Output/TestData.cs b/generators/Output/TestData.cs index fce92a47e3..1e017b188b 100644 --- a/generators/Output/TestData.cs +++ b/generators/Output/TestData.cs @@ -11,7 +11,6 @@ public class TestData { public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) { - Properties = new Dictionary(canonicalDataCase.Properties); Input = new Dictionary(canonicalDataCase.Input); Expected = canonicalDataCase.Expected; @@ -32,7 +31,6 @@ public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase public string Exercise { get; } public string Property { get; } - public IDictionary Properties { get; set; } public IDictionary Input { get; set; } public dynamic Expected { get; set; } @@ -40,14 +38,14 @@ public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase public IList DescriptionPath { get; set; } public bool Skip { get; set; } - + public bool UseVariablesForInput { get; set; } public bool UseVariableForExpected { get; set; } public bool UseVariablesForConstructorParameters { get; set; } public bool UseVariableForTested { get; set; } public bool UseFullDescriptionPath { get; set; } - public string TestMethod => + public string TestMethod => UseFullDescriptionPath ? string.Join(" - ", DescriptionPath).ToTestMethodName() : Description.ToTestMethodName(); From df1812f4d4bc5447896f1a562f74eeb3a3650304 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 26 Jun 2018 18:11:55 +0200 Subject: [PATCH 36/97] generators: Simplify triangle generator --- generators/Exercises/Generators/Triangle.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/generators/Exercises/Generators/Triangle.cs b/generators/Exercises/Generators/Triangle.cs index e68035cd8f..0ed3d56640 100644 --- a/generators/Exercises/Generators/Triangle.cs +++ b/generators/Exercises/Generators/Triangle.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -6,12 +7,7 @@ public class Triangle : GeneratorExercise { protected override void UpdateTestData(TestData data) { - if (data.Property == "equilateral") - data.TestedMethod = "IsEquilateral"; - else if (data.Property == "isosceles") - data.TestedMethod = "IsIsosceles"; - else if (data.Property == "scalene") - data.TestedMethod = "IsScalene"; + data.TestedMethod = $"Is{data.Property.Humanize()}"; data.Input["x"] = data.Input["sides"][0]; data.Input["y"] = data.Input["sides"][1]; From a09a1ea98dede82781d20e2d4b3bb8d7c58a371b Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 26 Jun 2018 18:46:18 +0200 Subject: [PATCH 37/97] generators: Introduce multiline string type --- generators/Exercises/GeneratorExercise.cs | 3 +-- generators/Exercises/Generators/BeerSong.cs | 5 ++--- .../Exercises/Generators/BinarySearchTree.cs | 1 - generators/Exercises/Generators/FoodChain.cs | 5 ++--- generators/Exercises/Generators/GoCounting.cs | 3 +-- generators/Exercises/Generators/House.cs | 5 ++--- .../Exercises/Generators/RationalNumbers.cs | 1 - generators/Exercises/Generators/Tournament.cs | 5 ++--- generators/Exercises/Generators/Transpose.cs | 5 ++--- generators/Exercises/Generators/TwelveDays.cs | 5 ++--- generators/Exercises/Generators/WordSearch.cs | 8 +++----- generators/Helpers/ConvertHelper.cs | 11 ----------- generators/Output/MultiLineString.cs | 17 +++++++++++++++++ generators/Output/ValueFormatter.cs | 3 +++ 14 files changed, 37 insertions(+), 40 deletions(-) create mode 100644 generators/Output/MultiLineString.cs diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index 9bfa910314..d3e65f70b5 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Helpers; using Exercism.CSharp.Input; diff --git a/generators/Exercises/Generators/BeerSong.cs b/generators/Exercises/Generators/BeerSong.cs index a9340be08c..ee6bf0ce1d 100644 --- a/generators/Exercises/Generators/BeerSong.cs +++ b/generators/Exercises/Generators/BeerSong.cs @@ -1,5 +1,4 @@ -using Exercism.CSharp.Helpers; -using Exercism.CSharp.Output; +using Exercism.CSharp.Output; namespace Exercism.CSharp.Exercises.Generators { @@ -8,7 +7,7 @@ public class BeerSong : GeneratorExercise protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; - data.Expected = ConvertHelper.ToMultiLineString(data.Expected); + data.Expected = new MultiLineString(data.Expected); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 2384e109d3..d42623bf27 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/FoodChain.cs b/generators/Exercises/Generators/FoodChain.cs index ff2b4c4c59..1c39331e7a 100644 --- a/generators/Exercises/Generators/FoodChain.cs +++ b/generators/Exercises/Generators/FoodChain.cs @@ -1,5 +1,4 @@ -using Exercism.CSharp.Helpers; -using Exercism.CSharp.Output; +using Exercism.CSharp.Output; namespace Exercism.CSharp.Exercises.Generators { @@ -7,7 +6,7 @@ public class FoodChain : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Expected = ConvertHelper.ToMultiLineString(data.Expected); + data.Expected = new MultiLineString(data.Expected); data.UseVariableForExpected = true; if (data.Input["startVerse"] == data.Input["endVerse"]) diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index 5fc0a55105..6d4febe4f5 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; using Humanizer; using Newtonsoft.Json.Linq; @@ -17,7 +16,7 @@ protected override void UpdateTestData(TestData data) data.UseVariablesForConstructorParameters = true; data.UseVariableForTested = true; - data.Input["board"] = ConvertHelper.ToMultiLineString(data.Input["board"]); + data.Input["board"] = new MultiLineString(data.Input["board"]); data.SetConstructorInputParameters("board"); if (data.Property == "territory") diff --git a/generators/Exercises/Generators/House.cs b/generators/Exercises/Generators/House.cs index 101938a37f..bc446d532b 100644 --- a/generators/Exercises/Generators/House.cs +++ b/generators/Exercises/Generators/House.cs @@ -1,5 +1,4 @@ -using Exercism.CSharp.Helpers; -using Exercism.CSharp.Output; +using Exercism.CSharp.Output; namespace Exercism.CSharp.Exercises.Generators { @@ -8,7 +7,7 @@ public class House : GeneratorExercise protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; - data.Expected = ConvertHelper.ToMultiLineString(data.Expected); + data.Expected = new MultiLineString(data.Expected); if (data.Input["startVerse"] == data.Input["endVerse"]) { diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index d97396489d..4849e09716 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/Tournament.cs b/generators/Exercises/Generators/Tournament.cs index cbf9076d50..dad4d12d55 100644 --- a/generators/Exercises/Generators/Tournament.cs +++ b/generators/Exercises/Generators/Tournament.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Text; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Templates; @@ -16,8 +15,8 @@ protected override void UpdateTestData(TestData data) data.TestedMethodType = TestedMethodType.Static; data.UseVariablesForInput = true; data.UseVariableForExpected = true; - data.Input["rows"] = ConvertHelper.ToMultiLineString(data.Input["rows"], ""); - data.Expected = ConvertHelper.ToMultiLineString(data.Expected); + data.Input["rows"] = new MultiLineString(data.Input["rows"]); + data.Expected = new MultiLineString(data.Expected); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/Transpose.cs b/generators/Exercises/Generators/Transpose.cs index cdea765ab6..0e8134dabd 100644 --- a/generators/Exercises/Generators/Transpose.cs +++ b/generators/Exercises/Generators/Transpose.cs @@ -1,4 +1,3 @@ -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; namespace Exercism.CSharp.Exercises.Generators @@ -8,8 +7,8 @@ public class Transpose : GeneratorExercise protected override void UpdateTestData(TestData data) { data.TestedMethod = "String"; - data.Input["lines"] = ConvertHelper.ToMultiLineString(data.Input["lines"], ""); - data.Expected = ConvertHelper.ToMultiLineString(data.Expected, ""); + data.Input["lines"] = new MultiLineString(data.Input["lines"]); + data.Expected = new MultiLineString(data.Expected); data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/Generators/TwelveDays.cs b/generators/Exercises/Generators/TwelveDays.cs index 7c688f9b53..3ff814755c 100644 --- a/generators/Exercises/Generators/TwelveDays.cs +++ b/generators/Exercises/Generators/TwelveDays.cs @@ -1,5 +1,4 @@ -using Exercism.CSharp.Helpers; -using Exercism.CSharp.Output; +using Exercism.CSharp.Output; namespace Exercism.CSharp.Exercises.Generators { @@ -8,7 +7,7 @@ public class TwelveDays : GeneratorExercise protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; - data.Expected = ConvertHelper.ToMultiLineString(data.Expected); + data.Expected = new MultiLineString(data.Expected); if (data.Input["startVerse"] == data.Input["endVerse"]) { diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 7602f6f0a5..29c7e8348b 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -1,8 +1,6 @@ using System; -using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; namespace Exercism.CSharp.Exercises.Generators @@ -10,7 +8,7 @@ namespace Exercism.CSharp.Exercises.Generators public class WordSearch : GeneratorExercise { private IDictionary _expectedDictionary; - + protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; @@ -20,7 +18,7 @@ protected override void UpdateTestData(TestData data) data.SetConstructorInputParameters("grid"); - data.Input["grid"] = ConvertHelper.ToMultiLineString(data.Input["grid"]); + data.Input["grid"] = new MultiLineString(data.Input["grid"]); _expectedDictionary = (IDictionary)data.Expected; @@ -36,7 +34,7 @@ protected override void UpdateTestData(TestData data) data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } - + protected override void UpdateTestMethod(TestMethod method) { method.Assert = RenderAssert(); diff --git a/generators/Helpers/ConvertHelper.cs b/generators/Helpers/ConvertHelper.cs index 69f3e51943..46ccf7b1b4 100644 --- a/generators/Helpers/ConvertHelper.cs +++ b/generators/Helpers/ConvertHelper.cs @@ -2,17 +2,6 @@ { public static class ConvertHelper { - public static string ToMultiLineString(this object obj) => string.Join("\n", obj as object[]); - - public static string ToMultiLineString(this object obj, string empty) - { - if (obj is object[] arr && arr.Length != 0) - return string.Join("\n", arr); - - return empty; - - } - public static T[] ToArray(this object obj) { if (obj is T[] arr && arr.Length != 0) diff --git a/generators/Output/MultiLineString.cs b/generators/Output/MultiLineString.cs new file mode 100644 index 0000000000..a0addb5260 --- /dev/null +++ b/generators/Output/MultiLineString.cs @@ -0,0 +1,17 @@ +using System; +using DotLiquid; + +namespace Exercism.CSharp.Output +{ + public class MultiLineString : ILiquidizable + { + private readonly string _value; + + public MultiLineString(object obj) + => _value = string.Join("\n", obj as object[] ?? Array.Empty()); + + public override string ToString() => _value; + + public object ToLiquid() => _value; + } +} diff --git a/generators/Output/ValueFormatter.cs b/generators/Output/ValueFormatter.cs index c488aa22b0..07e3a35371 100644 --- a/generators/Output/ValueFormatter.cs +++ b/generators/Output/ValueFormatter.cs @@ -14,6 +14,7 @@ public static string Format(object val) switch (val) { case string str: return str.Format(); + case MultiLineString multiLineString: return multiLineString.ToString().Format(); case double dbl: return dbl.Format(); case float flt: return flt.Format(); case ulong ulng: return ulng.Format(); @@ -47,6 +48,8 @@ public static IEnumerable FormatVariable(object val, string name) { case string str when str.Contains("\n"): return FormatMultiLineString(name, str); + case MultiLineString multiLineValue when multiLineValue.ToString().Contains("\n"): + return FormatMultiLineString(name, multiLineValue.ToString()); case IEnumerable strings: if (!strings.Any()) { From 86a91c23fd39f1e6f17644009eba201cc5fc5c2a Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 26 Jun 2018 18:54:12 +0200 Subject: [PATCH 38/97] generators: Remove dynamic extensions --- generators/Exercises/GeneratorExercise.cs | 13 +++++++++++-- generators/Helpers/DynamicExtensions.cs | 15 --------------- 2 files changed, 11 insertions(+), 17 deletions(-) delete mode 100644 generators/Helpers/DynamicExtensions.cs diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index d3e65f70b5..7f8eab7304 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System.Collections; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Helpers; using Exercism.CSharp.Input; @@ -89,7 +90,7 @@ private static TestMethod CreateTestMethod(TestData data) case null: return new TestMethodWithNullAssertion(data); default: - if ((data.Expected as object).IsEmptyEnumerable()) + if (UseEmptyAssertion(data)) return new TestMethodWithEmptyAssertion(data); return new TestMethodWithEqualityAssertion(data); @@ -108,5 +109,13 @@ private TestData[] CreateTestData() => protected virtual void UpdateTestData(TestData data) { } + + private static bool UseEmptyAssertion(TestData data) + { + if (data.Expected is string) + return false; + + return data.Expected is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; + } } } diff --git a/generators/Helpers/DynamicExtensions.cs b/generators/Helpers/DynamicExtensions.cs deleted file mode 100644 index bf7f9b68bc..0000000000 --- a/generators/Helpers/DynamicExtensions.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections; - -namespace Exercism.CSharp.Helpers -{ - public static class DynamicExtensions - { - public static bool IsEmptyEnumerable(this object value) - { - if (value is string) - return false; - - return value is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; - } - } -} \ No newline at end of file From 7aa7f29dc87278fd0021489e5c8a53c66aa49253 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Wed, 27 Jun 2018 16:48:30 +0200 Subject: [PATCH 39/97] generators: Remove type extensions --- generators/Helpers/TypesExtensions.cs | 15 --------------- generators/Output/ValueFormatter.cs | 10 +++++++++- 2 files changed, 9 insertions(+), 16 deletions(-) delete mode 100644 generators/Helpers/TypesExtensions.cs diff --git a/generators/Helpers/TypesExtensions.cs b/generators/Helpers/TypesExtensions.cs deleted file mode 100644 index 01ba6a96bf..0000000000 --- a/generators/Helpers/TypesExtensions.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections.Generic; - -namespace Exercism.CSharp.Helpers -{ - public static class TypesExtensions - { - public static IEnumerable SliceRow(this T[,] array, int row) - { - for (var i = array.GetLowerBound(1); i <= array.GetUpperBound(1); i++) - { - yield return array[row, i]; - } - } - } -} \ No newline at end of file diff --git a/generators/Output/ValueFormatter.cs b/generators/Output/ValueFormatter.cs index 07e3a35371..24934de1eb 100644 --- a/generators/Output/ValueFormatter.cs +++ b/generators/Output/ValueFormatter.cs @@ -126,8 +126,16 @@ private static string Format(this JArray jArray) => private static string Format(this int[,] multidimensionalArray) { + IEnumerable SliceRow(T[,] array, int row) + { + for (var i = array.GetLowerBound(1); i <= array.GetUpperBound(1); i++) + { + yield return array[row, i]; + } + } + return multidimensionalArray.GetLength(0) > 0 - ? $"new[,]\r\n{{\r\n {string.Join(",\r\n ", Enumerable.Range(0, multidimensionalArray.GetUpperBound(0) + 1).Select(x => multidimensionalArray.SliceRow(x).ToNestedArray()))}\r\n}}" + ? $"new[,]\r\n{{\r\n {string.Join(",\r\n ", Enumerable.Range(0, multidimensionalArray.GetUpperBound(0) + 1).Select(x => SliceRow(multidimensionalArray, x).ToNestedArray()))}\r\n}}" : "new int[,] { }"; } From 795dcc2712be25dfe03a2b4585a928b7e56e3972 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Wed, 27 Jun 2018 17:27:19 +0200 Subject: [PATCH 40/97] generators: Simplify description path logic --- generators/Helpers/JTokenExtensions.cs | 17 ++++++++++++ generators/Input/CanonicalDataCaseParser.cs | 29 ++++++--------------- 2 files changed, 25 insertions(+), 21 deletions(-) create mode 100644 generators/Helpers/JTokenExtensions.cs diff --git a/generators/Helpers/JTokenExtensions.cs b/generators/Helpers/JTokenExtensions.cs new file mode 100644 index 0000000000..3287abf30d --- /dev/null +++ b/generators/Helpers/JTokenExtensions.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; +using Newtonsoft.Json.Linq; + +namespace Exercism.CSharp.Helpers +{ + public static class JTokenExtensions + { + public static IEnumerable ParentsAndSelf(this JToken jToken) + { + while (jToken != null) + { + yield return jToken; + jToken = jToken.Parent; + } + } + } +} \ No newline at end of file diff --git a/generators/Input/CanonicalDataCaseParser.cs b/generators/Input/CanonicalDataCaseParser.cs index 82f6ccc240..3fe170b5a1 100644 --- a/generators/Input/CanonicalDataCaseParser.cs +++ b/generators/Input/CanonicalDataCaseParser.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using Exercism.CSharp.Helpers; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Input @@ -24,27 +25,13 @@ private static CanonicalDataCase Parse(JToken canonicalDataCaseJToken, int index description: canonicalDataCaseJToken.Value("description"), descriptionPath: GetDescriptionPath(canonicalDataCaseJToken)); - private static string[] GetDescriptionPath(JToken canonicalDataCaseToken) - { - var descriptionPath = new Stack(); - var currentToken = canonicalDataCaseToken; - - while (currentToken != null) - { - if (currentToken.Type == JTokenType.Object) - { - var description = currentToken.SelectToken("description"); - if (description == null) - break; - - descriptionPath.Push(description.ToObject()); - } - - currentToken = currentToken.Parent; - } - - return descriptionPath.Where(x => !string.IsNullOrEmpty(x)).ToArray(); - } + private static string[] GetDescriptionPath(JToken canonicalDataCaseToken) + => canonicalDataCaseToken.ParentsAndSelf() + .Where(token => token.Type == JTokenType.Object) + .Select(token => token.Value("description")) + .Where(description => description != null) + .Reverse() + .ToArray(); private static IReadOnlyDictionary ToReadOnlyDictionary(JToken jToken) => ConvertJToken(jToken); From ecf032e30ad0554c110525122cf3d4bfbe192c96 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Wed, 27 Jun 2018 17:35:21 +0200 Subject: [PATCH 41/97] generators: Move JToken conversion helpers to separate class --- generators/Helpers/JTokenExtensions.cs | 17 --- generators/Input/CanonicalDataCaseParser.cs | 126 +------------------ generators/Input/JTokenHelper.cs | 131 ++++++++++++++++++++ 3 files changed, 136 insertions(+), 138 deletions(-) delete mode 100644 generators/Helpers/JTokenExtensions.cs create mode 100644 generators/Input/JTokenHelper.cs diff --git a/generators/Helpers/JTokenExtensions.cs b/generators/Helpers/JTokenExtensions.cs deleted file mode 100644 index 3287abf30d..0000000000 --- a/generators/Helpers/JTokenExtensions.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Collections.Generic; -using Newtonsoft.Json.Linq; - -namespace Exercism.CSharp.Helpers -{ - public static class JTokenExtensions - { - public static IEnumerable ParentsAndSelf(this JToken jToken) - { - while (jToken != null) - { - yield return jToken; - jToken = jToken.Parent; - } - } - } -} \ No newline at end of file diff --git a/generators/Input/CanonicalDataCaseParser.cs b/generators/Input/CanonicalDataCaseParser.cs index 3fe170b5a1..606206ff8b 100644 --- a/generators/Input/CanonicalDataCaseParser.cs +++ b/generators/Input/CanonicalDataCaseParser.cs @@ -1,7 +1,5 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using Exercism.CSharp.Helpers; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Input @@ -20,131 +18,17 @@ private static CanonicalDataCase Parse(JToken canonicalDataCaseJToken, int index => new CanonicalDataCase( index: index, property: canonicalDataCaseJToken.Value("property"), - input: ToReadOnlyDictionary(canonicalDataCaseJToken["input"]), - expected: ConvertJToken(canonicalDataCaseJToken["expected"]), + input: JTokenHelper.ConvertJToken(canonicalDataCaseJToken["input"]), + expected: JTokenHelper.ConvertJToken(canonicalDataCaseJToken["expected"]), description: canonicalDataCaseJToken.Value("description"), descriptionPath: GetDescriptionPath(canonicalDataCaseJToken)); - private static string[] GetDescriptionPath(JToken canonicalDataCaseToken) - => canonicalDataCaseToken.ParentsAndSelf() + private static string[] GetDescriptionPath(JToken canonicalDataCaseJToken) + => canonicalDataCaseJToken.ParentsAndSelf() .Where(token => token.Type == JTokenType.Object) .Select(token => token.Value("description")) .Where(description => description != null) .Reverse() .ToArray(); - - private static IReadOnlyDictionary ToReadOnlyDictionary(JToken jToken) => ConvertJToken(jToken); - - private static dynamic ConvertJToken(JToken jToken) - { - switch (jToken?.Type) - { - case JTokenType.Object: - return ConvertJObject((JObject)jToken); - case JTokenType.Array: - return ConvertJArray((JArray)jToken); - case JTokenType.Property: - return jToken.ToObject>(); - case JTokenType.Integer: - return ConvertIntegerJToken(jToken); - case JTokenType.Float: - return jToken.ToObject(); - case JTokenType.String: - return jToken.ToObject(); - case JTokenType.Boolean: - return jToken.ToObject(); - case JTokenType.Date: - return jToken.ToObject(); - case JTokenType.Raw: - return jToken.ToObject(); - case JTokenType.Bytes: - return jToken.ToObject(); - case JTokenType.Guid: - return jToken.ToObject(); - case JTokenType.Uri: - return jToken.ToObject(); - case JTokenType.TimeSpan: - return jToken.ToObject(); - default: - return null; - } - } - - private static dynamic ConvertJObject(JObject jObject) - { - var properties = jObject.ToObject>(); - - for (var i = 0; i < properties.Count; i++) - { - var key = properties.Keys.ElementAt(i); - var value = properties[key]; - properties[key] = value is JToken jToken ? ConvertJToken(jToken) : value; - } - - return properties; - } - - private static dynamic ConvertJArray(JArray jArray) - { - // We can't determine the type of the array if the array is empty - if (!jArray.Any()) - return jArray; - - // We can only convert when all values have the same type - if (jArray.Select(x => x.Type).Distinct().Count() != 1) - return jArray; - - switch (jArray[0].Type) - { - case JTokenType.Object: - return jArray.Select(ConvertJToken).ToArray(); - case JTokenType.Integer: - var strings = jArray.ToObject(); - if (strings.All(str => int.TryParse(str, out _))) - return jArray.ToObject(); - - if (strings.All(str => long.TryParse(str, out _))) - return jArray.ToObject(); - - if (strings.All(str => ulong.TryParse(str, out _))) - return jArray.ToObject(); - - return strings; - case JTokenType.Float: - return jArray.ToObject(); - case JTokenType.String: - return jArray.ToObject(); - case JTokenType.Boolean: - return jArray.ToObject(); - case JTokenType.Date: - return jArray.ToObject(); - case JTokenType.Bytes: - return jArray.ToObject(); - case JTokenType.Guid: - return jArray.ToObject(); - case JTokenType.Uri: - return jArray.ToObject(); - case JTokenType.TimeSpan: - return jArray.ToObject(); - default: - return jArray; - } - } - - private static dynamic ConvertIntegerJToken(JToken jToken) - { - var str = jToken.ToObject(); - - if (int.TryParse(str, out var i)) - return i; - - if (long.TryParse(str, out var l)) - return l; - - if (ulong.TryParse(str, out var ul)) - return ul; - - return str; - } } } diff --git a/generators/Input/JTokenHelper.cs b/generators/Input/JTokenHelper.cs new file mode 100644 index 0000000000..dac0008209 --- /dev/null +++ b/generators/Input/JTokenHelper.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json.Linq; + +namespace Exercism.CSharp.Input +{ + public static class JTokenHelper + { + public static IEnumerable ParentsAndSelf(this JToken jToken) + { + while (jToken != null) + { + yield return jToken; + jToken = jToken.Parent; + } + } + + public static dynamic ConvertJToken(JToken jToken) + { + switch (jToken?.Type) + { + case JTokenType.Object: + return ConvertJObject((JObject)jToken); + case JTokenType.Array: + return ConvertJArray((JArray)jToken); + case JTokenType.Property: + return jToken.ToObject>(); + case JTokenType.Integer: + return ConvertIntegerJToken(jToken); + case JTokenType.Float: + return jToken.ToObject(); + case JTokenType.String: + return jToken.ToObject(); + case JTokenType.Boolean: + return jToken.ToObject(); + case JTokenType.Date: + return jToken.ToObject(); + case JTokenType.Raw: + return jToken.ToObject(); + case JTokenType.Bytes: + return jToken.ToObject(); + case JTokenType.Guid: + return jToken.ToObject(); + case JTokenType.Uri: + return jToken.ToObject(); + case JTokenType.TimeSpan: + return jToken.ToObject(); + default: + return null; + } + } + + private static dynamic ConvertJObject(JObject jObject) + { + var properties = jObject.ToObject>(); + + for (var i = 0; i < properties.Count; i++) + { + var key = properties.Keys.ElementAt(i); + var value = properties[key]; + properties[key] = value is JToken jToken ? ConvertJToken(jToken) : value; + } + + return properties; + } + + private static dynamic ConvertJArray(JArray jArray) + { + // We can't determine the type of the array if the array is empty + if (!jArray.Any()) + return jArray; + + // We can only convert when all values have the same type + if (jArray.Select(x => x.Type).Distinct().Count() != 1) + return jArray; + + switch (jArray[0].Type) + { + case JTokenType.Object: + return jArray.Select(ConvertJToken).ToArray(); + case JTokenType.Integer: + var strings = jArray.ToObject(); + if (strings.All(str => int.TryParse(str, out _))) + return jArray.ToObject(); + + if (strings.All(str => long.TryParse(str, out _))) + return jArray.ToObject(); + + if (strings.All(str => ulong.TryParse(str, out _))) + return jArray.ToObject(); + + return strings; + case JTokenType.Float: + return jArray.ToObject(); + case JTokenType.String: + return jArray.ToObject(); + case JTokenType.Boolean: + return jArray.ToObject(); + case JTokenType.Date: + return jArray.ToObject(); + case JTokenType.Bytes: + return jArray.ToObject(); + case JTokenType.Guid: + return jArray.ToObject(); + case JTokenType.Uri: + return jArray.ToObject(); + case JTokenType.TimeSpan: + return jArray.ToObject(); + default: + return jArray; + } + } + + private static dynamic ConvertIntegerJToken(JToken jToken) + { + var str = jToken.ToObject(); + + if (int.TryParse(str, out var i)) + return i; + + if (long.TryParse(str, out var l)) + return l; + + if (ulong.TryParse(str, out var ul)) + return ul; + + return str; + } + } +} \ No newline at end of file From 8ce18d8c880a6b084faaa050966c0e56e4e53987 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 28 Jun 2018 19:30:41 +0200 Subject: [PATCH 42/97] generators: Fix invalid ordering of test case when nesting is used --- .../BinarySearchTreeTest.cs | 26 ++++++++--------- .../complex-numbers/ComplexNumbersTest.cs | 18 ++++++------ exercises/grains/GrainsTest.cs | 12 ++++---- generators/Input/CanonicalDataCaseParser.cs | 29 ++++++++++++++----- 4 files changed, 49 insertions(+), 36 deletions(-) diff --git a/exercises/binary-search-tree/BinarySearchTreeTest.cs b/exercises/binary-search-tree/BinarySearchTreeTest.cs index 9246e9b30c..39acafc3e0 100644 --- a/exercises/binary-search-tree/BinarySearchTreeTest.cs +++ b/exercises/binary-search-tree/BinarySearchTreeTest.cs @@ -12,19 +12,6 @@ public void Data_is_retained() Assert.Equal(4, tree.Value); } - [Fact(Skip = "Remove to run test")] - public void Can_create_complex_tree() - { - var tree = new BinarySearchTree(new[] { 4, 2, 6, 1, 3, 5, 7 }); - Assert.Equal(4, tree.Value); - Assert.Equal(2, tree.Left.Value); - Assert.Equal(1, tree.Left.Left.Value); - Assert.Equal(3, tree.Left.Right.Value); - Assert.Equal(6, tree.Right.Value); - Assert.Equal(5, tree.Right.Left.Value); - Assert.Equal(7, tree.Right.Right.Value); - } - [Fact(Skip = "Remove to run test")] public void Smaller_number_at_left_node() { @@ -49,6 +36,19 @@ public void Greater_number_at_right_node() Assert.Equal(5, tree.Right.Value); } + [Fact(Skip = "Remove to run test")] + public void Can_create_complex_tree() + { + var tree = new BinarySearchTree(new[] { 4, 2, 6, 1, 3, 5, 7 }); + Assert.Equal(4, tree.Value); + Assert.Equal(2, tree.Left.Value); + Assert.Equal(1, tree.Left.Left.Value); + Assert.Equal(3, tree.Left.Right.Value); + Assert.Equal(6, tree.Right.Value); + Assert.Equal(5, tree.Right.Left.Value); + Assert.Equal(7, tree.Right.Right.Value); + } + [Fact(Skip = "Remove to run test")] public void Can_sort_single_number() { diff --git a/exercises/complex-numbers/ComplexNumbersTest.cs b/exercises/complex-numbers/ComplexNumbersTest.cs index 7b5b3e2270..80343bd561 100644 --- a/exercises/complex-numbers/ComplexNumbersTest.cs +++ b/exercises/complex-numbers/ComplexNumbersTest.cs @@ -6,15 +6,6 @@ public class ComplexNumbersTest { [Fact] - public void Imaginary_unit() - { - var sut = new ComplexNumber(0, 1); - var expected = new ComplexNumber(-1, 0); - Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(0, 1)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(0, 1)).Imaginary(), precision: 15); - } - - [Fact(Skip = "Remove to run test")] public void Real_part_of_a_purely_real_number() { var sut = new ComplexNumber(1, 0); @@ -56,6 +47,15 @@ public void Imaginary_part_of_a_number_with_real_and_imaginary_part() Assert.Equal(2, sut.Imaginary()); } + [Fact(Skip = "Remove to run test")] + public void Imaginary_unit() + { + var sut = new ComplexNumber(0, 1); + var expected = new ComplexNumber(-1, 0); + Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(0, 1)).Real(), precision: 15); + Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(0, 1)).Imaginary(), precision: 15); + } + [Fact(Skip = "Remove to run test")] public void Add_purely_real_numbers() { diff --git a/exercises/grains/GrainsTest.cs b/exercises/grains/GrainsTest.cs index e6782ef1e6..5326cb8992 100644 --- a/exercises/grains/GrainsTest.cs +++ b/exercises/grains/GrainsTest.cs @@ -6,12 +6,6 @@ public class GrainsTest { [Fact] - public void Returns_the_total_number_of_grains_on_the_board() - { - Assert.Equal(18446744073709551615UL, Grains.Total()); - } - - [Fact(Skip = "Remove to run test")] public void Number_1() { Assert.Equal(1UL, Grains.Square(1)); @@ -70,4 +64,10 @@ public void Square_greater_than_64_raises_an_exception() { Assert.Throws(() => Grains.Square(65)); } + + [Fact(Skip = "Remove to run test")] + public void Returns_the_total_number_of_grains_on_the_board() + { + Assert.Equal(18446744073709551615UL, Grains.Total()); + } } \ No newline at end of file diff --git a/generators/Input/CanonicalDataCaseParser.cs b/generators/Input/CanonicalDataCaseParser.cs index 606206ff8b..718a270423 100644 --- a/generators/Input/CanonicalDataCaseParser.cs +++ b/generators/Input/CanonicalDataCaseParser.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; @@ -6,15 +7,27 @@ namespace Exercism.CSharp.Input { public static class CanonicalDataCaseParser { - private const string TokensPath = "$..*[?(@.property)]"; - - public static IReadOnlyCollection Parse(JArray canonicalDataCasesJArray) - => canonicalDataCasesJArray - .SelectTokens(TokensPath) - .Select(Parse) + public static IReadOnlyCollection Parse(JToken canonicalDataCaseJToken) + => GetCanonicalDataCaseTokens(canonicalDataCaseJToken) + .Select(ParseWithIndex) .ToArray(); - private static CanonicalDataCase Parse(JToken canonicalDataCaseJToken, int index) + private static IEnumerable GetCanonicalDataCaseTokens(JToken currentJToken) + { + switch (currentJToken) + { + case JArray jArray: + return jArray.SelectMany(GetCanonicalDataCaseTokens); + case JObject jObject when jObject.TryGetValue("cases", out var casesJToken) && casesJToken is JArray childJArray: + return childJArray.SelectMany(GetCanonicalDataCaseTokens); + case JObject jObject when jObject.ContainsKey("property"): + return new[] { jObject }; + default: + return Enumerable.Empty(); + } + } + + private static CanonicalDataCase ParseWithIndex(JToken canonicalDataCaseJToken, int index) => new CanonicalDataCase( index: index, property: canonicalDataCaseJToken.Value("property"), From 28a7d63dde1e328d436b7bada06bd2eac1743b0f Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 28 Jun 2018 19:39:13 +0200 Subject: [PATCH 43/97] generators: Remove unused conversion cases --- generators/Input/CanonicalDataCaseParser.cs | 3 +-- generators/Input/JTokenHelper.cs | 20 -------------------- 2 files changed, 1 insertion(+), 22 deletions(-) diff --git a/generators/Input/CanonicalDataCaseParser.cs b/generators/Input/CanonicalDataCaseParser.cs index 718a270423..89883ea90e 100644 --- a/generators/Input/CanonicalDataCaseParser.cs +++ b/generators/Input/CanonicalDataCaseParser.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; diff --git a/generators/Input/JTokenHelper.cs b/generators/Input/JTokenHelper.cs index dac0008209..db877f5b53 100644 --- a/generators/Input/JTokenHelper.cs +++ b/generators/Input/JTokenHelper.cs @@ -24,8 +24,6 @@ public static dynamic ConvertJToken(JToken jToken) return ConvertJObject((JObject)jToken); case JTokenType.Array: return ConvertJArray((JArray)jToken); - case JTokenType.Property: - return jToken.ToObject>(); case JTokenType.Integer: return ConvertIntegerJToken(jToken); case JTokenType.Float: @@ -36,16 +34,6 @@ public static dynamic ConvertJToken(JToken jToken) return jToken.ToObject(); case JTokenType.Date: return jToken.ToObject(); - case JTokenType.Raw: - return jToken.ToObject(); - case JTokenType.Bytes: - return jToken.ToObject(); - case JTokenType.Guid: - return jToken.ToObject(); - case JTokenType.Uri: - return jToken.ToObject(); - case JTokenType.TimeSpan: - return jToken.ToObject(); default: return null; } @@ -99,14 +87,6 @@ private static dynamic ConvertJArray(JArray jArray) return jArray.ToObject(); case JTokenType.Date: return jArray.ToObject(); - case JTokenType.Bytes: - return jArray.ToObject(); - case JTokenType.Guid: - return jArray.ToObject(); - case JTokenType.Uri: - return jArray.ToObject(); - case JTokenType.TimeSpan: - return jArray.ToObject(); default: return jArray; } From daa3e06837f788830cb95ddf35af65c8c0cd927d Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 28 Jun 2018 21:28:28 +0200 Subject: [PATCH 44/97] generators: Remove convert helper --- generators/Exercises/Generators/AllYourBase.cs | 6 ++++-- generators/Exercises/Generators/BinarySearch.cs | 6 ++++-- generators/Exercises/Generators/BookStore.cs | 6 ++++-- generators/Exercises/Generators/Proverb.cs | 10 +++++++--- .../Exercises/Generators/SumOfMultiples.cs | 5 +++-- generators/Helpers/ConvertHelper.cs | 13 ------------- generators/Input/JTokenHelper.cs | 16 +++++++++------- 7 files changed, 31 insertions(+), 31 deletions(-) delete mode 100644 generators/Helpers/ConvertHelper.cs diff --git a/generators/Exercises/Generators/AllYourBase.cs b/generators/Exercises/Generators/AllYourBase.cs index 90df667c66..5289f102e3 100644 --- a/generators/Exercises/Generators/AllYourBase.cs +++ b/generators/Exercises/Generators/AllYourBase.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; +using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { @@ -9,7 +9,9 @@ public class AllYourBase : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Input["digits"] = ConvertHelper.ToArray(data.Input["digits"]); + if (data.Input["digits"] is JArray) + data.Input["digits"] = Array.Empty(); + data.ExceptionThrown = data.Expected is Dictionary ? typeof(ArgumentException) : null; data.UseVariablesForInput = true; data.UseVariableForExpected = true; diff --git a/generators/Exercises/Generators/BinarySearch.cs b/generators/Exercises/Generators/BinarySearch.cs index 471e625596..ca40582920 100644 --- a/generators/Exercises/Generators/BinarySearch.cs +++ b/generators/Exercises/Generators/BinarySearch.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; +using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { @@ -9,7 +9,9 @@ public class BinarySearch : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Input["array"] = ConvertHelper.ToArray(data.Input["array"]); + if (data.Input["array"] is JArray) + data.Input["array"] = Array.Empty(); + data.UseVariablesForConstructorParameters = true; data.SetConstructorInputParameters("array"); } diff --git a/generators/Exercises/Generators/BookStore.cs b/generators/Exercises/Generators/BookStore.cs index 7aa4febd74..df91f37f97 100644 --- a/generators/Exercises/Generators/BookStore.cs +++ b/generators/Exercises/Generators/BookStore.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; +using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { @@ -9,8 +9,10 @@ public class BookStore : GeneratorExercise { protected override void UpdateTestData(TestData data) { + if (data.Input["basket"] is JArray) + data.Input["basket"] = Array.Empty(); + data.Expected = data.Expected / 100.0f; - data.Input["basket"] = ConvertHelper.ToArray(data.Input["basket"]); data.SetInputParameters("basket"); data.UseVariablesForInput = true; } diff --git a/generators/Exercises/Generators/Proverb.cs b/generators/Exercises/Generators/Proverb.cs index 90ceecae52..25f70629fa 100644 --- a/generators/Exercises/Generators/Proverb.cs +++ b/generators/Exercises/Generators/Proverb.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; +using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { @@ -10,8 +10,12 @@ public class Proverb : GeneratorExercise protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; - data.Input["strings"] = ConvertHelper.ToArray(data.Input["strings"]); - data.Expected = ConvertHelper.ToArray(data.Expected); + + if (data.Input["strings"] is JArray) + data.Input["strings"] = Array.Empty(); + + if (data.Expected is JArray) + data.Expected = Array.Empty(); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/SumOfMultiples.cs b/generators/Exercises/Generators/SumOfMultiples.cs index 87bb195105..4fcce14dd3 100644 --- a/generators/Exercises/Generators/SumOfMultiples.cs +++ b/generators/Exercises/Generators/SumOfMultiples.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; +using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { @@ -9,7 +9,8 @@ public class SumOfMultiples : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Input["factors"] = ConvertHelper.ToArray(data.Input["factors"]); + if (data.Input["factors"] is JArray) + data.Input["factors"] = Array.Empty(); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Helpers/ConvertHelper.cs b/generators/Helpers/ConvertHelper.cs deleted file mode 100644 index 46ccf7b1b4..0000000000 --- a/generators/Helpers/ConvertHelper.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Exercism.CSharp.Helpers -{ - public static class ConvertHelper - { - public static T[] ToArray(this object obj) - { - if (obj is T[] arr && arr.Length != 0) - return arr; - - return new T[0]; - } - } -} \ No newline at end of file diff --git a/generators/Input/JTokenHelper.cs b/generators/Input/JTokenHelper.cs index db877f5b53..73a7c1c4b7 100644 --- a/generators/Input/JTokenHelper.cs +++ b/generators/Input/JTokenHelper.cs @@ -18,14 +18,16 @@ public static IEnumerable ParentsAndSelf(this JToken jToken) public static dynamic ConvertJToken(JToken jToken) { - switch (jToken?.Type) + if (jToken is JObject jObject) + return ConvertJObject(jObject); + + if (jToken is JArray jArray) + return ConvertJArray(jArray); + + switch (jToken.Type) { - case JTokenType.Object: - return ConvertJObject((JObject)jToken); - case JTokenType.Array: - return ConvertJArray((JArray)jToken); case JTokenType.Integer: - return ConvertIntegerJToken(jToken); + return ConvertJTokenToInteger(jToken); case JTokenType.Float: return jToken.ToObject(); case JTokenType.String: @@ -92,7 +94,7 @@ private static dynamic ConvertJArray(JArray jArray) } } - private static dynamic ConvertIntegerJToken(JToken jToken) + private static dynamic ConvertJTokenToInteger(JToken jToken) { var str = jToken.ToObject(); From 091b9a61f0258d2e81fdfe74b842e32d26d5bd6a Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 29 Jun 2018 17:42:05 +0200 Subject: [PATCH 45/97] generators: Introduce assertion rendering helper --- generators/Output/Assertion.cs | 27 +++++++++++++++++++ generators/Output/TestMethod.cs | 11 ++++---- .../Output/TestMethodWithBooleanAssertion.cs | 7 +++-- .../Output/TestMethodWithEmptyAssertion.cs | 7 ++--- .../Output/TestMethodWithEqualityAssertion.cs | 6 +++-- .../TestMethodWithExceptionAssertion.cs | 11 ++++---- .../Output/TestMethodWithNullAssertion.cs | 8 +++--- 7 files changed, 53 insertions(+), 24 deletions(-) create mode 100644 generators/Output/Assertion.cs diff --git a/generators/Output/Assertion.cs b/generators/Output/Assertion.cs new file mode 100644 index 0000000000..c8375b51f7 --- /dev/null +++ b/generators/Output/Assertion.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using Exercism.CSharp.Output.Templates; + +namespace Exercism.CSharp.Output +{ + public static class Assertion + { + public static IEnumerable Null(string testedValue) + => Render("AssertNull", new { TestedValue = testedValue }); + + public static IEnumerable Empty(string testedValue, string expectedParameter) + => Render("AssertEmpty", new { TestedValue = testedValue, ExpectedParameter = expectedParameter }); + + public static IEnumerable Equal(string testedValue, string expectedParameter) + => Render("AssertEqual", new { TestedValue = testedValue, ExpectedParameter = expectedParameter }); + + public static IEnumerable Exception(string testedValue, Type exceptionType) + => Render("AssertException", new { TestedValue = testedValue, ExceptionType = exceptionType.Name }); + + public static IEnumerable Boolean(string testedValue, bool expected) + => Render("AssertBoolean", new { TestedValue = testedValue, BooleanAssertMethod = expected.ToString() }); + + private static IEnumerable Render(string template, object parameters) + => new[] { TemplateRenderer.RenderPartial(template, parameters) }; + } +} \ No newline at end of file diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index 9aad61ca93..b4ac08e896 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -13,15 +13,15 @@ public abstract class TestMethod private const string TestedVariableName = "actual"; private const string ExpectedVariableName = "expected"; private const string TemplateName = "TestMethod"; + + private const string ArrangeTemplateName = "Arrange"; + private const string ActTemplateName = "Act"; protected TestMethod(TestData data) => Data = data; public TestData Data { get; } - - public string ArrangeTemplateName { get; set; } = "Arrange"; + public object ArrangeTemplateParameters { get; set; } - - public string ActTemplateName { get; set; } = "Act"; public object ActTemplateParameters { get; set; } public string AssertTemplateName { get; set; } = "AssertEqual"; @@ -111,7 +111,6 @@ private IEnumerable RenderArrange() private IEnumerable RenderAct() => new[] { TemplateRenderer.RenderPartial(ActTemplateName, ActTemplateParameters) }; - private IEnumerable RenderAssert() - => new[] { TemplateRenderer.RenderPartial(AssertTemplateName, AssertTemplateParameters) }; + protected abstract IEnumerable RenderAssert(); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithBooleanAssertion.cs b/generators/Output/TestMethodWithBooleanAssertion.cs index e70fb41c17..ffaac95d5d 100644 --- a/generators/Output/TestMethodWithBooleanAssertion.cs +++ b/generators/Output/TestMethodWithBooleanAssertion.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; namespace Exercism.CSharp.Output { @@ -6,10 +7,8 @@ public class TestMethodWithBooleanAssertion : TestMethod { public TestMethodWithBooleanAssertion(TestData data) : base(data) { - AssertTemplateName = "AssertBoolean"; - AssertTemplateParameters = new { BooleanAssertMethod, TestedValue }; } - - private string BooleanAssertMethod => Convert.ToBoolean(Data.Expected).ToString(); + + protected override IEnumerable RenderAssert() => Assertion.Boolean(TestedValue, Convert.ToBoolean(Data.Expected)); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEmptyAssertion.cs b/generators/Output/TestMethodWithEmptyAssertion.cs index f821d93133..603e518e48 100644 --- a/generators/Output/TestMethodWithEmptyAssertion.cs +++ b/generators/Output/TestMethodWithEmptyAssertion.cs @@ -1,3 +1,5 @@ +using System.Collections.Generic; + namespace Exercism.CSharp.Output { public class TestMethodWithEmptyAssertion : TestMethod @@ -5,9 +7,8 @@ public class TestMethodWithEmptyAssertion : TestMethod public TestMethodWithEmptyAssertion(TestData data): base(data) { Data.UseVariableForExpected = false; - - AssertTemplateName = "AssertEmpty"; - AssertTemplateParameters = new { ExpectedParameter, TestedValue }; } + + protected override IEnumerable RenderAssert() => Assertion.Empty(TestedValue, ExpectedParameter); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEqualityAssertion.cs b/generators/Output/TestMethodWithEqualityAssertion.cs index 930a07e2ba..d5c5a2ce7e 100644 --- a/generators/Output/TestMethodWithEqualityAssertion.cs +++ b/generators/Output/TestMethodWithEqualityAssertion.cs @@ -1,11 +1,13 @@ +using System.Collections.Generic; + namespace Exercism.CSharp.Output { public class TestMethodWithEqualityAssertion : TestMethod { public TestMethodWithEqualityAssertion(TestData data) : base(data) { - AssertTemplateName = "AssertEqual"; - AssertTemplateParameters = new { ExpectedParameter, TestedValue }; } + + protected override IEnumerable RenderAssert() => Assertion.Equal(TestedValue, ExpectedParameter); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithExceptionAssertion.cs b/generators/Output/TestMethodWithExceptionAssertion.cs index 68a07d6e19..4c883e4ac1 100644 --- a/generators/Output/TestMethodWithExceptionAssertion.cs +++ b/generators/Output/TestMethodWithExceptionAssertion.cs @@ -1,4 +1,6 @@ -namespace Exercism.CSharp.Output +using System.Collections.Generic; + +namespace Exercism.CSharp.Output { public class TestMethodWithExceptionAssertion : TestMethod { @@ -6,11 +8,8 @@ public TestMethodWithExceptionAssertion(TestData data) : base(data) { Data.UseVariableForExpected = false; Data.UseVariableForTested = false; - - AssertTemplateName = "AssertException"; - AssertTemplateParameters = new { ExceptionType, TestedValue }; } - - private string ExceptionType => Data.ExceptionThrown.Name; + + protected override IEnumerable RenderAssert() => Assertion.Exception(TestedValue, Data.ExceptionThrown); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithNullAssertion.cs b/generators/Output/TestMethodWithNullAssertion.cs index 0efd279975..bd67bc2517 100644 --- a/generators/Output/TestMethodWithNullAssertion.cs +++ b/generators/Output/TestMethodWithNullAssertion.cs @@ -1,11 +1,13 @@ -namespace Exercism.CSharp.Output +using System.Collections.Generic; + +namespace Exercism.CSharp.Output { public class TestMethodWithNullAssertion : TestMethod { public TestMethodWithNullAssertion(TestData data) : base(data) { - AssertTemplateName = "AssertNull"; - AssertTemplateParameters = new { TestedValue }; } + + protected override IEnumerable RenderAssert() => Assertion.Null(TestedValue); } } \ No newline at end of file From b925e46f27c5d11a12810bdd28693830c122bc88 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 29 Jun 2018 17:59:42 +0200 Subject: [PATCH 46/97] generators: Revert to using string as render output --- generators/Exercises/Generators/Allergies.cs | 9 +++---- .../Exercises/Generators/BinarySearchTree.cs | 4 +-- generators/Exercises/Generators/Bowling.cs | 20 +++++++------- .../Exercises/Generators/CircularBuffer.cs | 10 ++++--- generators/Exercises/Generators/Clock.cs | 10 +++---- .../Exercises/Generators/ComplexNumbers.cs | 6 ++--- generators/Exercises/Generators/GoCounting.cs | 25 +++++++++--------- generators/Exercises/Generators/Meetup.cs | 4 +-- .../Exercises/Generators/NucleotideCount.cs | 10 +++---- .../Generators/PalindromeProducts.cs | 13 +++++----- .../Exercises/Generators/QueenAttack.cs | 7 +++-- .../Exercises/Generators/RationalNumbers.cs | 4 +-- generators/Exercises/Generators/React.cs | 7 +++-- .../Exercises/Generators/RobotSimulator.cs | 16 ++++++------ .../Exercises/Generators/RunLengthEncoding.cs | 9 +++---- .../Exercises/Generators/SimpleCipher.cs | 6 ++--- generators/Exercises/Generators/Tournament.cs | 8 ++---- generators/Exercises/Generators/TwoBucket.cs | 9 +++---- generators/Exercises/Generators/WordSearch.cs | 6 ++--- generators/Exercises/Generators/Zipper.cs | 26 ++++++++++--------- generators/Output/Assertion.cs | 15 +++++------ .../Output/Templates/_TestMethod.liquid | 6 ++--- generators/Output/TestMethod.cs | 23 +++++++--------- .../Output/TestMethodWithBooleanAssertion.cs | 3 +-- .../Output/TestMethodWithEmptyAssertion.cs | 4 +-- .../Output/TestMethodWithEqualityAssertion.cs | 4 +-- .../TestMethodWithExceptionAssertion.cs | 6 ++--- .../Output/TestMethodWithNullAssertion.cs | 6 ++--- 28 files changed, 128 insertions(+), 148 deletions(-) diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index e3398f8363..bebed93b7d 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using Exercism.CSharp.Output; +using Exercism.CSharp.Output; using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators @@ -21,14 +20,14 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { return method.Data.Property == "allergicTo" ? RenderIsAllergicToAssert(method) : method.Assert; } - private static IEnumerable RenderIsAllergicToAssert(TestMethod method) + private static string RenderIsAllergicToAssert(TestMethod method) { const string template = @"{%- for allergy in Allergies -%} @@ -36,7 +35,7 @@ private static IEnumerable RenderIsAllergicToAssert(TestMethod method) {%- endfor -%}"; var templateParameters = new { Allergies = method.Data.Expected }; - return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; + return TemplateRenderer.RenderInline(template, templateParameters); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index d42623bf27..20f629485f 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -41,7 +41,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private IEnumerable RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { _testFactCodeLines = new StringBuilder(); var canonicalDataCase = method.Data; @@ -67,7 +67,7 @@ private IEnumerable RenderAssert(TestMethod method) AddCodeLine($"Assert.Equal(new[] {{ {expectedArrayString} }}, tree.AsEnumerable());"); } - return new[] { _testFactCodeLines.ToString() }; + return _testFactCodeLines.ToString(); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index ab1d8d4a46..f40fdf5e8e 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -31,13 +31,13 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderArrange(TestMethod method) + private static string RenderArrange(TestMethod method) { var builder = new StringBuilder(); builder.AppendLine("var sut = new BowlingGame();"); if (!method.Data.Input.ContainsKey(PreviousRolls)) - return new[] { builder.ToString() }; + return builder.ToString(); if (method.Data.Input[PreviousRolls] is int[] array) { @@ -50,10 +50,10 @@ private static IEnumerable RenderArrange(TestMethod method) builder.Append("var previousRolls = Array.Empty();"); } - return new[] { builder.ToString() }; + return builder.ToString(); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { if (method.Data.ExceptionThrown != null && method.Data.Input.ContainsKey("roll")) { @@ -62,7 +62,7 @@ private static IEnumerable RenderAssert(TestMethod method) { RollVal = method.Data.Input["roll"] }; - return new[] { TemplateRenderer.RenderInline(template, templateParams) }; + return TemplateRenderer.RenderInline(template, templateParams); } if (method.Data.ExceptionThrown == null || @@ -70,11 +70,11 @@ private static IEnumerable RenderAssert(TestMethod method) return method.Assert; const string throwTemplate = "Assert.Throws(() => sut.Score());"; - return new[] { throwTemplate }; + return throwTemplate; } - private static IEnumerable RenderAct(TestMethod method) + private static string RenderAct(TestMethod method) { var template = @"DoRoll(previousRolls, sut); @@ -82,7 +82,7 @@ private static IEnumerable RenderAct(TestMethod method) if (method.Data.ExceptionThrown != null) { - return new[] { template }; + return template; } if (method.Data.Input.ContainsKey("roll")) @@ -95,11 +95,11 @@ private static IEnumerable RenderAct(TestMethod method) { RolVal = method.Data.Input["roll"] }; - return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; + return TemplateRenderer.RenderInline(template, templateParameters); } template += "var actual = sut.Score();"; - return new[] { template }; + return template; } protected override void UpdateTestClass(TestClass @class) diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index 5adb4ccbc6..4e793621ce 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Text; using Exercism.CSharp.Output; namespace Exercism.CSharp.Exercises.Generators @@ -11,12 +12,15 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { - yield return RenderSut(method.Data); + var assert = new StringBuilder(); + assert.AppendLine(RenderSut(method.Data)); foreach (var operation in method.Data.Input["operations"]) - yield return RenderOperation(operation); + assert.AppendLine(RenderOperation(operation)); + + return assert.ToString(); } private static string RenderSut(TestData canonicalDataCase) diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index b748f2fc8a..818a8a6e33 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -43,7 +43,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { if (method.Data.Property == PropertyEqual) { @@ -55,13 +55,13 @@ private static IEnumerable RenderAssert(TestMethod method) : method.Assert; } - private static IEnumerable RenderConsistencyToAssert(TestMethod method) + private static string RenderConsistencyToAssert(TestMethod method) { const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString());"; - return new[] { TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }) }; + return TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }); } - private static IEnumerable RenderEqualToAssert(TestMethod method) + private static string RenderEqualToAssert(TestMethod method) { var expectedParameter = method.Data.Input[ParamClock1]; const string testedValue = "sut"; @@ -73,7 +73,7 @@ private static IEnumerable RenderEqualToAssert(TestMethod method) ? "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}); " : "Assert.NotEqual({{ ExpectedParameter }}, {{ TestedValue }});"; - return new[] { TemplateRenderer.RenderInline(template, assertTemplateParameters) }; + return TemplateRenderer.RenderInline(template, assertTemplateParameters); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index 946c68cb5a..f24190ea22 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -36,18 +36,18 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { return method.Data.UseVariableForExpected ? RenderComplexNumberAssert(method) : method.Assert; } - private static IEnumerable RenderComplexNumberAssert(TestMethod method) + private static string RenderComplexNumberAssert(TestMethod method) { const string template = "Assert.Equal({{ ExpectedParameter }}.Real(), {{ TestedValue }}.Real(), precision: 15);\r\nAssert.Equal({{ ExpectedParameter }}.Imaginary(), {{ TestedValue }}.Imaginary(), precision: 15);"; - return new[] { TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }) }; + return TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index 6d4febe4f5..e908edfdfa 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using Exercism.CSharp.Output; using Humanizer; using Newtonsoft.Json.Linq; @@ -56,7 +57,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { if (method.Data.ExceptionThrown != null) { @@ -65,20 +66,18 @@ private static IEnumerable RenderAssert(TestMethod method) if (method.Data.Property == "territories") { - return new[] - { - "Assert.Equal(expected.Keys, actual.Keys);", - "Assert.Equal(expected[Owner.Black], actual[Owner.Black]);", - "Assert.Equal(expected[Owner.White], actual[Owner.White]);", - "Assert.Equal(expected[Owner.None], actual[Owner.None]);" - }; + var territoriesAssert = new StringBuilder(); + territoriesAssert.AppendLine("Assert.Equal(expected.Keys, actual.Keys);"); + territoriesAssert.AppendLine("Assert.Equal(expected[Owner.Black], actual[Owner.Black]);"); + territoriesAssert.AppendLine("Assert.Equal(expected[Owner.White], actual[Owner.White]);"); + territoriesAssert.AppendLine("Assert.Equal(expected[Owner.None], actual[Owner.None]);"); + return territoriesAssert.ToString(); } - return new[] - { - "Assert.Equal(expected.Item1, actual.Item1);", - "Assert.Equal(expected.Item2, actual.Item2);" - }; + var assert = new StringBuilder(); + assert.AppendLine("Assert.Equal(expected.Item1, actual.Item1);"); + assert.AppendLine("Assert.Equal(expected.Item2, actual.Item2);"); + return assert.ToString(); } private static string FormatOwner(dynamic owner) diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index e885df4482..dc18df54f8 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -35,11 +35,11 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString(\"yyyy-MM-dd\"));"; - return new[] { TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }) }; + return TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index fdc7423e9d..e5f83f2419 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -31,14 +31,14 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { return method.Data.UseVariableForExpected ? RenderEqualAssert(method) : RenderThrowsAssert(method); } - private static IEnumerable RenderEqualAssert(TestMethod method) + private static string RenderEqualAssert(TestMethod method) { const string template = @"Assert.Equal(expected, sut.{{ TestedMethodName }});"; @@ -47,10 +47,10 @@ private static IEnumerable RenderEqualAssert(TestMethod method) TestedMethodName = method.Data.Property.ToTestedMethodName() }; - return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; + return TemplateRenderer.RenderInline(template, templateParameters); } - private static IEnumerable RenderThrowsAssert(TestMethod method) + private static string RenderThrowsAssert(TestMethod method) { const string template = @"Assert.Throws(() => new NucleotideCount(""{{ Input }}""));"; @@ -59,7 +59,7 @@ private static IEnumerable RenderThrowsAssert(TestMethod method) Input = method.Data.Input["strand"] }; - return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; + return TemplateRenderer.RenderInline(template, templateParameters); } } } diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index 7e9fa0324c..045751d4ff 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Linq; +using System.Text; using Exercism.CSharp.Output; using Newtonsoft.Json.Linq; @@ -27,18 +27,17 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { if (method.Data.ExceptionThrown != null) { return method.Assert; } - return new[] - { - "Assert.Equal(expected.Item1, actual.Item1);", - "Assert.Equal(expected.Item2, actual.Item2);" - }; + var assert = new StringBuilder(); + assert.AppendLine("Assert.Equal(expected.Item1, actual.Item1);"); + assert.AppendLine("Assert.Equal(expected.Item2, actual.Item2);"); + return assert.ToString(); } private static string FormatCoordinates(dynamic coordinates) diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index cfe095e5bb..bf2c18a07c 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Templates; @@ -18,13 +17,13 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { if (method.Data.Property == "canAttack") - return new[] { RenderCanAttackAssert(method) }; + return RenderCanAttackAssert(method); return method.Data.UseVariableForTested - ? Array.Empty() + ? string.Empty : method.Assert; } diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index 4849e09716..eabd46048f 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -22,7 +22,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { var input = (Dictionary)method.Data.Input; var operationName = char.ToUpper(method.Data.Property[0]) + method.Data.Property.Substring(1); @@ -70,7 +70,7 @@ private static IEnumerable RenderAssert(TestMethod method) break; } - return new[] { assertCodeLine }; + return assertCodeLine; } private static int Precision(object rawValue) diff --git a/generators/Exercises/Generators/React.cs b/generators/Exercises/Generators/React.cs index 02c3d7d68f..4c733452db 100644 --- a/generators/Exercises/Generators/React.cs +++ b/generators/Exercises/Generators/React.cs @@ -16,7 +16,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(); } - private static IEnumerable RenderArrange(TestMethod method) + private static string RenderArrange(TestMethod method) { var arrange = new StringBuilder(); arrange.AppendLine("var sut = new Reactor();"); @@ -27,7 +27,7 @@ private static IEnumerable RenderArrange(TestMethod method) var operations = RenderOperations(method.Data.Input["operations"]); arrange.AppendLine(operations); - return new[] { arrange.ToString() }; + return arrange.ToString(); } private static string RenderCells(dynamic cells) @@ -125,8 +125,7 @@ private static string RenderOperation(dynamic operation) } } - private static IEnumerable RenderAssert() - => new[] { "" }; + private static string RenderAssert() => string.Empty; protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs index eac2b4c4f3..5c63477804 100644 --- a/generators/Exercises/Generators/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -32,17 +32,17 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAct(TestMethod method) + private static string RenderAct(TestMethod method) { switch (method.Data.Property) { - case "create": return Array.Empty(); + case "create": return null; case "instructions": return RenderInstructionsAct(method); default: return RenderDefaultAct(method); } } - private static IEnumerable RenderDefaultAct(TestMethod method) + private static string RenderDefaultAct(TestMethod method) { const string template = @"sut.{{MethodInvocation}}();"; @@ -51,10 +51,10 @@ private static IEnumerable RenderDefaultAct(TestMethod method) MethodInvocation = method.Data.Property.ToTestedMethodName() }; - return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; + return TemplateRenderer.RenderInline(template, templateParameters); } - private static IEnumerable RenderInstructionsAct(TestMethod method) + private static string RenderInstructionsAct(TestMethod method) { const string template = @"sut.{{MethodInvocation}}(""{{Instructions}}"");"; @@ -64,10 +64,10 @@ private static IEnumerable RenderInstructionsAct(TestMethod method) Instructions = method.Data.Input["instructions"] }; - return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; + return TemplateRenderer.RenderInline(template, templateParameters); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { var expected = method.Data.Expected as Dictionary; expected.TryGetValue("position", out var position); @@ -91,7 +91,7 @@ private static IEnumerable RenderAssert(TestMethod method) Y = position?["y"] }; - return new[] { TemplateRenderer.RenderInline(template.ToString(), templateParameters) }; + return TemplateRenderer.RenderInline(template.ToString(), templateParameters); } private static string GetDirectionEnum(string direction) diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index b0ce819a58..237049e196 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using Exercism.CSharp.Output; +using Exercism.CSharp.Output; using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators @@ -16,14 +15,14 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { return method.Data.Property == "consistency" ? RenderConsistencyToAssert(method) : method.Assert; } - private static IEnumerable RenderConsistencyToAssert(TestMethod method) + private static string RenderConsistencyToAssert(TestMethod method) { const string template = @"Assert.Equal(""{{Expected}}"", {{TestedClassName}}.Decode({{TestedClassName}}.Encode(""{{Expected}}"")));"; @@ -33,7 +32,7 @@ private static IEnumerable RenderConsistencyToAssert(TestMethod method) TestedClassName = method.Data.TestedClass }; - return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; + return TemplateRenderer.RenderInline(template, templateParameters); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index 80739aa9b9..4b96214caf 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -48,16 +48,16 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { switch (method.Data.Property) { case "new": var key = ValueFormatter.Format(method.Data.Input["key"]); - return new[] { $"Assert.Throws(() => new SimpleCipher({key}));" }; + return $"Assert.Throws(() => new SimpleCipher({key}));"; case "key": var pattern = ValueFormatter.Format(method.Data.Expected["match"]); - return new[] { $"Assert.Matches({pattern}, sut.Key);" }; + return $"Assert.Matches({pattern}, sut.Key);"; default: return method.Assert; } diff --git a/generators/Exercises/Generators/Tournament.cs b/generators/Exercises/Generators/Tournament.cs index dad4d12d55..cf1685b97b 100644 --- a/generators/Exercises/Generators/Tournament.cs +++ b/generators/Exercises/Generators/Tournament.cs @@ -26,17 +26,13 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(UTF8Encoding).Namespace); } - protected override void UpdateTestMethod(TestMethod method) { method.Assert = RenderAssert(); } - private static IEnumerable RenderAssert() - { - const string template = @"Assert.Equal(expected, RunTally(rows));"; - return new[] { TemplateRenderer.RenderInline(template, new { }) }; - } + private static string RenderAssert() + => TemplateRenderer.RenderInline(@"Assert.Equal(expected, RunTally(rows));", new { }); protected override void UpdateTestClass(TestClass @class) { diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index 6dac9cc2c0..0e3138f028 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Templates; @@ -21,7 +20,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderAct(TestMethod method) + private static string RenderAct(TestMethod method) { const string template = @"var result = {{MethodInvocation}};"; @@ -30,10 +29,10 @@ private static IEnumerable RenderAct(TestMethod method) MethodInvocation = method.TestedMethodInvocation }; - return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; + return TemplateRenderer.RenderInline(template, templateParameters); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { const string template = @"Assert.Equal({{MovesExpected}}, result.Moves); @@ -47,7 +46,7 @@ private static IEnumerable RenderAssert(TestMethod method) GoalBucketExpected = method.Data.Expected["goalBucket"] }; - return new[] { TemplateRenderer.RenderInline(template, templateParameters) }; + return TemplateRenderer.RenderInline(template, templateParameters); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 29c7e8348b..663d85ebb0 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -40,10 +40,10 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(); } - private IEnumerable RenderAssert() - => _expectedDictionary + private string RenderAssert() + => string.Join(Environment.NewLine, _expectedDictionary .Select(kv => RenderAssertForSearchWord(kv.Key, kv.Value)) - .Cast(); + .Cast()); private static string RenderAssertForSearchWord(string word, dynamic expected) { diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index 51ea93d680..3ee5137d38 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -1,6 +1,6 @@ using System; -using System.Collections.Generic; using System.Linq; +using System.Text; using Exercism.CSharp.Output; using Humanizer; @@ -14,28 +14,30 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static IEnumerable RenderArrange(TestMethod method) + private static string RenderArrange(TestMethod method) { + var arrange = new StringBuilder(); var tree = RenderTree(method.Data.Input["initialTree"]); - yield return $"var tree = {tree};"; - yield return "var sut = Zipper.FromTree(tree);"; + arrange.AppendLine($"var tree = {tree};"); + arrange.AppendLine("var sut = Zipper.FromTree(tree);"); var operations = RenderOperations(method.Data.Input["operations"]); - yield return $"var actual = sut{operations};"; + arrange.AppendLine($"var actual = sut{operations};"); + return arrange.ToString(); } - private static IEnumerable RenderAssert(TestMethod method) + private static string RenderAssert(TestMethod method) { var expected = RenderExpected(method.Data.Expected); if (expected == null) { - yield return "Assert.Null(actual);"; - } - else - { - yield return $"var expected = {expected};"; - yield return "Assert.Equal(expected, actual);"; + return "Assert.Null(actual);"; } + + var assert = new StringBuilder(); + assert.AppendLine($"var expected = {expected};"); + assert.AppendLine("Assert.Equal(expected, actual);"); + return assert.ToString(); } private static string RenderTree(dynamic tree) diff --git a/generators/Output/Assertion.cs b/generators/Output/Assertion.cs index c8375b51f7..01ed2cb3e0 100644 --- a/generators/Output/Assertion.cs +++ b/generators/Output/Assertion.cs @@ -1,27 +1,26 @@ using System; -using System.Collections.Generic; using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Output { public static class Assertion { - public static IEnumerable Null(string testedValue) + public static string Null(string testedValue) => Render("AssertNull", new { TestedValue = testedValue }); - public static IEnumerable Empty(string testedValue, string expectedParameter) + public static string Empty(string testedValue, string expectedParameter) => Render("AssertEmpty", new { TestedValue = testedValue, ExpectedParameter = expectedParameter }); - public static IEnumerable Equal(string testedValue, string expectedParameter) + public static string Equal(string testedValue, string expectedParameter) => Render("AssertEqual", new { TestedValue = testedValue, ExpectedParameter = expectedParameter }); - public static IEnumerable Exception(string testedValue, Type exceptionType) + public static string Exception(string testedValue, Type exceptionType) => Render("AssertException", new { TestedValue = testedValue, ExceptionType = exceptionType.Name }); - public static IEnumerable Boolean(string testedValue, bool expected) + public static string Boolean(string testedValue, bool expected) => Render("AssertBoolean", new { TestedValue = testedValue, BooleanAssertMethod = expected.ToString() }); - private static IEnumerable Render(string template, object parameters) - => new[] { TemplateRenderer.RenderPartial(template, parameters) }; + private static string Render(string template, object parameters) + => TemplateRenderer.RenderPartial(template, parameters); } } \ No newline at end of file diff --git a/generators/Output/Templates/_TestMethod.liquid b/generators/Output/Templates/_TestMethod.liquid index 5da69bb1bc..8182578a8b 100644 --- a/generators/Output/Templates/_TestMethod.liquid +++ b/generators/Output/Templates/_TestMethod.liquid @@ -1,7 +1,7 @@ [Fact{% if Skip %}(Skip = "Remove to run test"){% endif %}] public void {{ Name }}() { -{%- for line in Lines -%} -{{ line | indent }} -{%- endfor -%} +{{ Arrange | indent }} +{{ Act | indent }} +{{ Assert | indent }} } \ No newline at end of file diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index b4ac08e896..b079723d7f 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -23,16 +23,11 @@ public abstract class TestMethod public object ArrangeTemplateParameters { get; set; } public object ActTemplateParameters { get; set; } - - public string AssertTemplateName { get; set; } = "AssertEqual"; public object AssertTemplateParameters { get; set; } - public IEnumerable Act { get; set; } - public IEnumerable Arrange { get; set; } - public IEnumerable Assert { get; set; } - - private IEnumerable Lines => - Arrange.Concat(Act).Concat(Assert).Where(line => !string.IsNullOrWhiteSpace(line)); + public string Act { get; set; } + public string Arrange { get; set; } + public string Assert { get; set; } public string Render() { @@ -44,7 +39,7 @@ public string Render() Act = Act ?? RenderAct(); Assert = Assert ?? RenderAssert(); - return TemplateRenderer.RenderPartial(TemplateName, new { Name = Data.TestMethod, Data.Skip, Lines }); + return TemplateRenderer.RenderPartial(TemplateName, new { Name = Data.TestMethod, Data.Skip, Arrange, Act, Assert }); } public string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; @@ -105,12 +100,12 @@ public string TestedMethodInvocation } } - private IEnumerable RenderArrange() - => new[] { TemplateRenderer.RenderPartial(ArrangeTemplateName, ArrangeTemplateParameters) }; + private string RenderArrange() + => TemplateRenderer.RenderPartial(ArrangeTemplateName, ArrangeTemplateParameters); - private IEnumerable RenderAct() - => new[] { TemplateRenderer.RenderPartial(ActTemplateName, ActTemplateParameters) }; + private string RenderAct() + => TemplateRenderer.RenderPartial(ActTemplateName, ActTemplateParameters); - protected abstract IEnumerable RenderAssert(); + protected abstract string RenderAssert(); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithBooleanAssertion.cs b/generators/Output/TestMethodWithBooleanAssertion.cs index ffaac95d5d..b41cc21053 100644 --- a/generators/Output/TestMethodWithBooleanAssertion.cs +++ b/generators/Output/TestMethodWithBooleanAssertion.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; namespace Exercism.CSharp.Output { @@ -9,6 +8,6 @@ public TestMethodWithBooleanAssertion(TestData data) : base(data) { } - protected override IEnumerable RenderAssert() => Assertion.Boolean(TestedValue, Convert.ToBoolean(Data.Expected)); + protected override string RenderAssert() => Assertion.Boolean(TestedValue, Convert.ToBoolean(Data.Expected)); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEmptyAssertion.cs b/generators/Output/TestMethodWithEmptyAssertion.cs index 603e518e48..2cbde1fcdf 100644 --- a/generators/Output/TestMethodWithEmptyAssertion.cs +++ b/generators/Output/TestMethodWithEmptyAssertion.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Exercism.CSharp.Output { public class TestMethodWithEmptyAssertion : TestMethod @@ -9,6 +7,6 @@ public TestMethodWithEmptyAssertion(TestData data): base(data) Data.UseVariableForExpected = false; } - protected override IEnumerable RenderAssert() => Assertion.Empty(TestedValue, ExpectedParameter); + protected override string RenderAssert() => Assertion.Empty(TestedValue, ExpectedParameter); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEqualityAssertion.cs b/generators/Output/TestMethodWithEqualityAssertion.cs index d5c5a2ce7e..9c93c54007 100644 --- a/generators/Output/TestMethodWithEqualityAssertion.cs +++ b/generators/Output/TestMethodWithEqualityAssertion.cs @@ -1,5 +1,3 @@ -using System.Collections.Generic; - namespace Exercism.CSharp.Output { public class TestMethodWithEqualityAssertion : TestMethod @@ -8,6 +6,6 @@ public TestMethodWithEqualityAssertion(TestData data) : base(data) { } - protected override IEnumerable RenderAssert() => Assertion.Equal(TestedValue, ExpectedParameter); + protected override string RenderAssert() => Assertion.Equal(TestedValue, ExpectedParameter); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithExceptionAssertion.cs b/generators/Output/TestMethodWithExceptionAssertion.cs index 4c883e4ac1..2f5188344b 100644 --- a/generators/Output/TestMethodWithExceptionAssertion.cs +++ b/generators/Output/TestMethodWithExceptionAssertion.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; - -namespace Exercism.CSharp.Output +namespace Exercism.CSharp.Output { public class TestMethodWithExceptionAssertion : TestMethod { @@ -10,6 +8,6 @@ public TestMethodWithExceptionAssertion(TestData data) : base(data) Data.UseVariableForTested = false; } - protected override IEnumerable RenderAssert() => Assertion.Exception(TestedValue, Data.ExceptionThrown); + protected override string RenderAssert() => Assertion.Exception(TestedValue, Data.ExceptionThrown); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithNullAssertion.cs b/generators/Output/TestMethodWithNullAssertion.cs index bd67bc2517..37cbcdeec7 100644 --- a/generators/Output/TestMethodWithNullAssertion.cs +++ b/generators/Output/TestMethodWithNullAssertion.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; - -namespace Exercism.CSharp.Output +namespace Exercism.CSharp.Output { public class TestMethodWithNullAssertion : TestMethod { @@ -8,6 +6,6 @@ public TestMethodWithNullAssertion(TestData data) : base(data) { } - protected override IEnumerable RenderAssert() => Assertion.Null(TestedValue); + protected override string RenderAssert() => Assertion.Null(TestedValue); } } \ No newline at end of file From 88984f85106283e19c0e8bf330aeeb825e2f2e36 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 29 Jun 2018 21:23:37 +0200 Subject: [PATCH 47/97] generators: Use assertion helpers --- exercises/clock/ClockTest.cs | 26 +-- exercises/minesweeper/MinesweeperTest.cs | 119 ++++++------- exercises/ocr-numbers/OcrNumbersTest.cs | 167 ++++++++++-------- generators/Exercises/Generators/Allergies.cs | 14 +- .../Exercises/Generators/BinarySearchTree.cs | 4 +- generators/Exercises/Generators/Bowling.cs | 14 +- .../Exercises/Generators/CircularBuffer.cs | 6 +- generators/Exercises/Generators/Clock.cs | 22 +-- .../Exercises/Generators/ComplexNumbers.cs | 13 +- generators/Exercises/Generators/GoCounting.cs | 12 +- generators/Exercises/Generators/Meetup.cs | 8 +- .../Exercises/Generators/Minesweeper.cs | 20 +-- .../Exercises/Generators/NucleotideCount.cs | 25 +-- generators/Exercises/Generators/OcrNumbers.cs | 19 +- .../Generators/PalindromeProducts.cs | 4 +- .../Exercises/Generators/QueenAttack.cs | 31 ++-- .../Exercises/Generators/RobotSimulator.cs | 48 ++--- .../Exercises/Generators/RunLengthEncoding.cs | 13 +- .../Exercises/Generators/SimpleCipher.cs | 4 +- generators/Exercises/Generators/Tournament.cs | 4 +- generators/Exercises/Generators/TwoBucket.cs | 36 ++-- generators/Exercises/Generators/WordSearch.cs | 4 +- generators/Exercises/Generators/Zipper.cs | 4 +- generators/Output/Assertion.cs | 32 ++-- .../Output/Templates/_AssertBoolean.liquid | 2 +- .../Output/Templates/_AssertEmpty.liquid | 2 +- .../Output/Templates/_AssertEqual.liquid | 2 +- .../Templates/_AssertEqualWithin.liquid | 1 + .../Output/Templates/_AssertException.liquid | 1 - .../Output/Templates/_AssertMatches.liquid | 1 + .../Output/Templates/_AssertNotEqual.liquid | 1 + .../Output/Templates/_AssertNull.liquid | 2 +- .../Output/Templates/_AssertThrows.liquid | 1 + .../Output/TestMethodWithBooleanAssertion.cs | 2 +- .../Output/TestMethodWithEmptyAssertion.cs | 2 +- .../Output/TestMethodWithEqualityAssertion.cs | 2 +- .../TestMethodWithExceptionAssertion.cs | 2 +- 37 files changed, 296 insertions(+), 374 deletions(-) create mode 100644 generators/Output/Templates/_AssertEqualWithin.liquid delete mode 100644 generators/Output/Templates/_AssertException.liquid create mode 100644 generators/Output/Templates/_AssertMatches.liquid create mode 100644 generators/Output/Templates/_AssertNotEqual.liquid create mode 100644 generators/Output/Templates/_AssertThrows.liquid diff --git a/exercises/clock/ClockTest.cs b/exercises/clock/ClockTest.cs index 94fd421c72..8bd8768f08 100644 --- a/exercises/clock/ClockTest.cs +++ b/exercises/clock/ClockTest.cs @@ -253,7 +253,7 @@ public void Subtract_more_than_two_days() public void Clocks_with_same_time() { var sut = new Clock(15, 37); - Assert.Equal(new Clock(15, 37), sut); + Assert.Equal(new Clock(15, 37), sut); } [Fact(Skip = "Remove to run test")] @@ -274,83 +274,83 @@ public void Clocks_an_hour_apart() public void Clocks_with_hour_overflow() { var sut = new Clock(34, 37); - Assert.Equal(new Clock(10, 37), sut); + Assert.Equal(new Clock(10, 37), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_hour_overflow_by_several_days() { var sut = new Clock(99, 11); - Assert.Equal(new Clock(3, 11), sut); + Assert.Equal(new Clock(3, 11), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_negative_hour() { var sut = new Clock(-2, 40); - Assert.Equal(new Clock(22, 40), sut); + Assert.Equal(new Clock(22, 40), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_negative_hour_that_wraps() { var sut = new Clock(-31, 3); - Assert.Equal(new Clock(17, 3), sut); + Assert.Equal(new Clock(17, 3), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_negative_hour_that_wraps_multiple_times() { var sut = new Clock(-83, 49); - Assert.Equal(new Clock(13, 49), sut); + Assert.Equal(new Clock(13, 49), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_minute_overflow() { var sut = new Clock(0, 1441); - Assert.Equal(new Clock(0, 1), sut); + Assert.Equal(new Clock(0, 1), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_minute_overflow_by_several_days() { var sut = new Clock(2, 4322); - Assert.Equal(new Clock(2, 2), sut); + Assert.Equal(new Clock(2, 2), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_negative_minute() { var sut = new Clock(3, -20); - Assert.Equal(new Clock(2, 40), sut); + Assert.Equal(new Clock(2, 40), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_negative_minute_that_wraps() { var sut = new Clock(5, -1490); - Assert.Equal(new Clock(4, 10), sut); + Assert.Equal(new Clock(4, 10), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_negative_minute_that_wraps_multiple_times() { var sut = new Clock(6, -4305); - Assert.Equal(new Clock(6, 15), sut); + Assert.Equal(new Clock(6, 15), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_negative_hours_and_minutes() { var sut = new Clock(-12, -268); - Assert.Equal(new Clock(7, 32), sut); + Assert.Equal(new Clock(7, 32), sut); } [Fact(Skip = "Remove to run test")] public void Clocks_with_negative_hours_and_minutes_that_wrap() { var sut = new Clock(-54, -11513); - Assert.Equal(new Clock(18, 7), sut); + Assert.Equal(new Clock(18, 7), sut); } } \ No newline at end of file diff --git a/exercises/minesweeper/MinesweeperTest.cs b/exercises/minesweeper/MinesweeperTest.cs index e2e8dbbc61..422b386b76 100644 --- a/exercises/minesweeper/MinesweeperTest.cs +++ b/exercises/minesweeper/MinesweeperTest.cs @@ -9,20 +9,19 @@ public class MinesweeperTest public void No_rows() { var minefield = Array.Empty(); - var expected = Array.Empty(); - Assert.Equal(expected, Minesweeper.Annotate(minefield)); + Assert.Empty(Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void No_columns() { - var minefield = new string[] - { - "" + var minefield = new[] + { + "" }; - var expected = new string[] - { - "" + var expected = new[] + { + "" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -30,19 +29,17 @@ public void No_columns() [Fact(Skip = "Remove to run test")] public void No_mines() { - var minefield = new string[] - { + var minefield = new[] + { " ", " ", " " - }; - var expected = new string[] - { + var expected = new[] + { " ", " ", " " - }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -50,19 +47,17 @@ public void No_mines() [Fact(Skip = "Remove to run test")] public void Minefield_with_only_mines() { - var minefield = new string[] - { + var minefield = new[] + { "***", "***", "***" - }; - var expected = new string[] - { + var expected = new[] + { "***", "***", "***" - }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -70,19 +65,17 @@ public void Minefield_with_only_mines() [Fact(Skip = "Remove to run test")] public void Mine_surrounded_by_spaces() { - var minefield = new string[] - { + var minefield = new[] + { " ", " * ", " " - }; - var expected = new string[] - { + var expected = new[] + { "111", "1*1", "111" - }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -90,19 +83,17 @@ public void Mine_surrounded_by_spaces() [Fact(Skip = "Remove to run test")] public void Space_surrounded_by_mines() { - var minefield = new string[] - { + var minefield = new[] + { "***", "* *", "***" - }; - var expected = new string[] - { + var expected = new[] + { "***", "*8*", "***" - }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -110,13 +101,13 @@ public void Space_surrounded_by_mines() [Fact(Skip = "Remove to run test")] public void Horizontal_line() { - var minefield = new string[] - { - " * * " + var minefield = new[] + { + " * * " }; - var expected = new string[] - { - "1*2*1" + var expected = new[] + { + "1*2*1" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -124,13 +115,13 @@ public void Horizontal_line() [Fact(Skip = "Remove to run test")] public void Horizontal_line_mines_at_edges() { - var minefield = new string[] - { - "* *" + var minefield = new[] + { + "* *" }; - var expected = new string[] - { - "*1 1*" + var expected = new[] + { + "*1 1*" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -138,23 +129,21 @@ public void Horizontal_line_mines_at_edges() [Fact(Skip = "Remove to run test")] public void Vertical_line() { - var minefield = new string[] - { + var minefield = new[] + { " ", "*", " ", "*", " " - }; - var expected = new string[] - { + var expected = new[] + { "1", "*", "2", "*", "1" - }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -162,23 +151,21 @@ public void Vertical_line() [Fact(Skip = "Remove to run test")] public void Vertical_line_mines_at_edges() { - var minefield = new string[] - { + var minefield = new[] + { "*", " ", " ", " ", "*" - }; - var expected = new string[] - { + var expected = new[] + { "*", "1", " ", "1", "*" - }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -186,23 +173,21 @@ public void Vertical_line_mines_at_edges() [Fact(Skip = "Remove to run test")] public void Cross() { - var minefield = new string[] - { + var minefield = new[] + { " * ", " * ", "*****", " * ", " * " - }; - var expected = new string[] - { + var expected = new[] + { " 2*2 ", "25*52", "*****", "25*52", " 2*2 " - }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -210,25 +195,23 @@ public void Cross() [Fact(Skip = "Remove to run test")] public void Large_minefield() { - var minefield = new string[] - { + var minefield = new[] + { " * * ", " * ", " * ", " * *", " * * ", " " - }; - var expected = new string[] - { + var expected = new[] + { "1*22*1", "12*322", " 123*2", "112*4*", "1*22*2", "111111" - }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } diff --git a/exercises/ocr-numbers/OcrNumbersTest.cs b/exercises/ocr-numbers/OcrNumbersTest.cs index 9043f2d538..16da4b0dc8 100644 --- a/exercises/ocr-numbers/OcrNumbersTest.cs +++ b/exercises/ocr-numbers/OcrNumbersTest.cs @@ -8,10 +8,11 @@ public class OcrNumbersTest [Fact] public void Recognizes_0() { - var rows = " _ " + "\n" + - "| |" + "\n" + - "|_|" + "\n" + - " "; + var rows = + " _ " + "\n" + + "| |" + "\n" + + "|_|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("0", actual); } @@ -19,10 +20,11 @@ public void Recognizes_0() [Fact(Skip = "Remove to run test")] public void Recognizes_1() { - var rows = " " + "\n" + - " |" + "\n" + - " |" + "\n" + - " "; + var rows = + " " + "\n" + + " |" + "\n" + + " |" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("1", actual); } @@ -30,10 +32,11 @@ public void Recognizes_1() [Fact(Skip = "Remove to run test")] public void Unreadable_but_correctly_sized_inputs_return_() { - var rows = " " + "\n" + - " _" + "\n" + - " |" + "\n" + - " "; + var rows = + " " + "\n" + + " _" + "\n" + + " |" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("?", actual); } @@ -41,29 +44,32 @@ public void Unreadable_but_correctly_sized_inputs_return_() [Fact(Skip = "Remove to run test")] public void Input_with_a_number_of_lines_that_is_not_a_multiple_of_four_raises_an_error() { - var rows = " _ " + "\n" + - "| |" + "\n" + - " "; + var rows = + " _ " + "\n" + + "| |" + "\n" + + " "; Assert.Throws(() => OcrNumbers.Convert(rows)); } [Fact(Skip = "Remove to run test")] public void Input_with_a_number_of_columns_that_is_not_a_multiple_of_three_raises_an_error() { - var rows = " " + "\n" + - " |" + "\n" + - " |" + "\n" + - " "; + var rows = + " " + "\n" + + " |" + "\n" + + " |" + "\n" + + " "; Assert.Throws(() => OcrNumbers.Convert(rows)); } [Fact(Skip = "Remove to run test")] public void Recognizes_110101100() { - var rows = " _ _ _ _ " + "\n" + - " | || | || | | || || |" + "\n" + - " | ||_| ||_| | ||_||_|" + "\n" + - " "; + var rows = + " _ _ _ _ " + "\n" + + " | || | || | | || || |" + "\n" + + " | ||_| ||_| | ||_||_|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("110101100", actual); } @@ -71,10 +77,11 @@ public void Recognizes_110101100() [Fact(Skip = "Remove to run test")] public void Garbled_numbers_in_a_string_are_replaced_with_() { - var rows = " _ _ _ " + "\n" + - " | || | || | || || |" + "\n" + - " | | _| ||_| | ||_||_|" + "\n" + - " "; + var rows = + " _ _ _ " + "\n" + + " | || | || | || || |" + "\n" + + " | | _| ||_| | ||_||_|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("11?10?1?0", actual); } @@ -82,10 +89,11 @@ public void Garbled_numbers_in_a_string_are_replaced_with_() [Fact(Skip = "Remove to run test")] public void Recognizes_2() { - var rows = " _ " + "\n" + - " _|" + "\n" + - "|_ " + "\n" + - " "; + var rows = + " _ " + "\n" + + " _|" + "\n" + + "|_ " + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("2", actual); } @@ -93,10 +101,11 @@ public void Recognizes_2() [Fact(Skip = "Remove to run test")] public void Recognizes_3() { - var rows = " _ " + "\n" + - " _|" + "\n" + - " _|" + "\n" + - " "; + var rows = + " _ " + "\n" + + " _|" + "\n" + + " _|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("3", actual); } @@ -104,10 +113,11 @@ public void Recognizes_3() [Fact(Skip = "Remove to run test")] public void Recognizes_4() { - var rows = " " + "\n" + - "|_|" + "\n" + - " |" + "\n" + - " "; + var rows = + " " + "\n" + + "|_|" + "\n" + + " |" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("4", actual); } @@ -115,10 +125,11 @@ public void Recognizes_4() [Fact(Skip = "Remove to run test")] public void Recognizes_5() { - var rows = " _ " + "\n" + - "|_ " + "\n" + - " _|" + "\n" + - " "; + var rows = + " _ " + "\n" + + "|_ " + "\n" + + " _|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("5", actual); } @@ -126,10 +137,11 @@ public void Recognizes_5() [Fact(Skip = "Remove to run test")] public void Recognizes_6() { - var rows = " _ " + "\n" + - "|_ " + "\n" + - "|_|" + "\n" + - " "; + var rows = + " _ " + "\n" + + "|_ " + "\n" + + "|_|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("6", actual); } @@ -137,10 +149,11 @@ public void Recognizes_6() [Fact(Skip = "Remove to run test")] public void Recognizes_7() { - var rows = " _ " + "\n" + - " |" + "\n" + - " |" + "\n" + - " "; + var rows = + " _ " + "\n" + + " |" + "\n" + + " |" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("7", actual); } @@ -148,10 +161,11 @@ public void Recognizes_7() [Fact(Skip = "Remove to run test")] public void Recognizes_8() { - var rows = " _ " + "\n" + - "|_|" + "\n" + - "|_|" + "\n" + - " "; + var rows = + " _ " + "\n" + + "|_|" + "\n" + + "|_|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("8", actual); } @@ -159,10 +173,11 @@ public void Recognizes_8() [Fact(Skip = "Remove to run test")] public void Recognizes_9() { - var rows = " _ " + "\n" + - "|_|" + "\n" + - " _|" + "\n" + - " "; + var rows = + " _ " + "\n" + + "|_|" + "\n" + + " _|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("9", actual); } @@ -170,10 +185,11 @@ public void Recognizes_9() [Fact(Skip = "Remove to run test")] public void Recognizes_string_of_decimal_numbers() { - var rows = " _ _ _ _ _ _ _ _ " + "\n" + - " | _| _||_||_ |_ ||_||_|| |" + "\n" + - " ||_ _| | _||_| ||_| _||_|" + "\n" + - " "; + var rows = + " _ _ _ _ _ _ _ _ " + "\n" + + " | _| _||_||_ |_ ||_||_|| |" + "\n" + + " ||_ _| | _||_| ||_| _||_|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("1234567890", actual); } @@ -181,18 +197,19 @@ public void Recognizes_string_of_decimal_numbers() [Fact(Skip = "Remove to run test")] public void Numbers_separated_by_empty_lines_are_recognized_lines_are_joined_by_commas_() { - var rows = " _ _ " + "\n" + - " | _| _|" + "\n" + - " ||_ _|" + "\n" + - " " + "\n" + - " _ _ " + "\n" + - "|_||_ |_ " + "\n" + - " | _||_|" + "\n" + - " " + "\n" + - " _ _ _ " + "\n" + - " ||_||_|" + "\n" + - " ||_| _|" + "\n" + - " "; + var rows = + " _ _ " + "\n" + + " | _| _|" + "\n" + + " ||_ _|" + "\n" + + " " + "\n" + + " _ _ " + "\n" + + "|_||_ |_ " + "\n" + + " | _||_|" + "\n" + + " " + "\n" + + " _ _ _ " + "\n" + + " ||_||_|" + "\n" + + " ||_| _|" + "\n" + + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("123,456,789", actual); } diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index bebed93b7d..d08727833c 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -1,4 +1,5 @@ -using Exercism.CSharp.Output; +using System.Text; +using Exercism.CSharp.Output; using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators @@ -29,13 +30,12 @@ private static string RenderAssert(TestMethod method) private static string RenderIsAllergicToAssert(TestMethod method) { - const string template = - @"{%- for allergy in Allergies -%} -Assert.{% if allergy.result %}True{% else %}False{% endif %}(sut.IsAllergicTo(""{{ allergy.substance }}"")); -{%- endfor -%}"; + var assert = new StringBuilder(); - var templateParameters = new { Allergies = method.Data.Expected }; - return TemplateRenderer.RenderInline(template, templateParameters); + foreach (var allergy in method.Data.Expected) + assert.AppendLine(Assertion.Boolean(allergy["result"], $"sut.IsAllergicTo({ValueFormatter.Format(allergy["substance"])})")); + + return assert.ToString(); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 20f629485f..fd6e5e2d47 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -20,7 +20,7 @@ public ExpectedDataBinaryTree(IReadOnlyDictionary treeNode) public IEnumerable TestAsserts(string traverse = "") { - yield return $"Assert.Equal({Value}, tree{traverse}.Value);"; + yield return Assertion.Equal(Value, $"tree{traverse}.Value"); if (Left != null) foreach (var assert in Left.TestAsserts(traverse + ".Left")) yield return assert; if (Right != null) foreach (var assert in Right.TestAsserts(traverse + ".Right")) yield return assert; } @@ -64,7 +64,7 @@ private string RenderAssert(TestMethod method) else { var expectedArrayString = string.Join(", ", canonicalDataCase.Expected as string[]); - AddCodeLine($"Assert.Equal(new[] {{ {expectedArrayString} }}, tree.AsEnumerable());"); + AddCodeLine(Assertion.Equal($"new[] {{ {expectedArrayString} }}", "tree.AsEnumerable()")); } return _testFactCodeLines.ToString(); diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index f40fdf5e8e..b447b4fd8c 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -57,21 +57,15 @@ private static string RenderAssert(TestMethod method) { if (method.Data.ExceptionThrown != null && method.Data.Input.ContainsKey("roll")) { - const string template = "Assert.Throws(() => sut.Roll({{RollVal}}));"; - var templateParams = new - { - RollVal = method.Data.Input["roll"] - }; - return TemplateRenderer.RenderInline(template, templateParams); + var actual = ValueFormatter.Format(method.Data.Input["roll"]); + return Assertion.Throws(method.Data.ExceptionThrown.Name, $"sut.Roll({actual})"); } if (method.Data.ExceptionThrown == null || method.Data.Property != "score") return method.Assert; - - const string throwTemplate = "Assert.Throws(() => sut.Score());"; - return throwTemplate; - + + return Assertion.Throws(method.Data.ExceptionThrown.Name, $"sut.Score()"); } private static string RenderAct(TestMethod method) diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index 4e793621ce..aa37067e45 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -49,15 +49,15 @@ private static string RenderOperation(dynamic operation) private static string RenderReadOperation(dynamic operation) { return operation["should_succeed"] - ? $"Assert.Equal({operation["expected"]}, buffer.Read());" - : "Assert.Throws(() => buffer.Read());"; + ? Assertion.Equal(operation["expected"].ToString(), "buffer.Read()") + : Assertion.Throws("InvalidOperationException", "buffer.Read()"); } private static string RenderWriteOperation(dynamic operation) { return operation["should_succeed"] ? $"buffer.Write({operation["item"]});" - : $"Assert.Throws(() => buffer.Write({operation["item"]}));"; + : Assertion.Throws("InvalidOperationException", $"buffer.Write({operation["item"]})"); } private static string RenderOverwriteOperation(dynamic operation) diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 818a8a6e33..29fe45ccf1 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators { @@ -55,25 +54,16 @@ private static string RenderAssert(TestMethod method) : method.Assert; } - private static string RenderConsistencyToAssert(TestMethod method) - { - const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString());"; - return TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }); - } + private static string RenderConsistencyToAssert(TestMethod method) + => Assertion.Equal(method.ExpectedParameter, $"{method.TestedValue}.ToString()"); private static string RenderEqualToAssert(TestMethod method) { - var expectedParameter = method.Data.Input[ParamClock1]; - const string testedValue = "sut"; - var expectedEqual = method.Data.Expected; - - var assertTemplateParameters = new { expectedParameter, testedValue }; - - var template = expectedEqual - ? "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}); " - : "Assert.NotEqual({{ ExpectedParameter }}, {{ TestedValue }});"; + var expected = method.Data.Input[ParamClock1].ToString(); - return TemplateRenderer.RenderInline(template, assertTemplateParameters); + return method.Data.Expected + ? Assertion.Equal(expected, "sut") + : Assertion.NotEqual(expected, "sut"); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index f24190ea22..975e127fea 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Templates; using Newtonsoft.Json.Linq; @@ -45,9 +46,11 @@ private static string RenderAssert(TestMethod method) private static string RenderComplexNumberAssert(TestMethod method) { - const string template = "Assert.Equal({{ ExpectedParameter }}.Real(), {{ TestedValue }}.Real(), precision: 15);\r\nAssert.Equal({{ ExpectedParameter }}.Imaginary(), {{ TestedValue }}.Imaginary(), precision: 15);"; + var assert = new StringBuilder(); + assert.AppendLine(Assertion.EqualWithin($"{method.ExpectedParameter}.Real()", $"{method.TestedValue}.Real()", 15)); + assert.AppendLine(Assertion.EqualWithin($"{method.ExpectedParameter}.Imaginary()", $"{method.TestedValue}.Imaginary()", 15)); - return TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }); + return assert.ToString(); } protected override void UpdateNamespaces(ISet namespaces) @@ -55,12 +58,10 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(Math).Namespace); } - private static object ConvertToType(dynamic rawValue) - { - return IsComplexNumber(rawValue) + private static object ConvertToType(dynamic rawValue) + => IsComplexNumber(rawValue) ? new UnescapedValue($"new ComplexNumber({ValueFormatter.Format(ConvertMathDouble(rawValue[0]))}, {ValueFormatter.Format(ConvertMathDouble(rawValue[1]))})") : rawValue; - } private static bool IsComplexNumber(object rawValue) => rawValue is int[] || rawValue is double[] || rawValue is float[] || rawValue is JArray; diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index e908edfdfa..c1e973c402 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -67,16 +67,16 @@ private static string RenderAssert(TestMethod method) if (method.Data.Property == "territories") { var territoriesAssert = new StringBuilder(); - territoriesAssert.AppendLine("Assert.Equal(expected.Keys, actual.Keys);"); - territoriesAssert.AppendLine("Assert.Equal(expected[Owner.Black], actual[Owner.Black]);"); - territoriesAssert.AppendLine("Assert.Equal(expected[Owner.White], actual[Owner.White]);"); - territoriesAssert.AppendLine("Assert.Equal(expected[Owner.None], actual[Owner.None]);"); + territoriesAssert.AppendLine(Assertion.Equal("expected.Keys", "actual.Keys")); + territoriesAssert.AppendLine(Assertion.Equal("expected[Owner.Black]", "actual[Owner.Black]")); + territoriesAssert.AppendLine(Assertion.Equal("expected[Owner.White]", "actual[Owner.White]")); + territoriesAssert.AppendLine(Assertion.Equal("expected[Owner.None]", "actual[Owner.None]")); return territoriesAssert.ToString(); } var assert = new StringBuilder(); - assert.AppendLine("Assert.Equal(expected.Item1, actual.Item1);"); - assert.AppendLine("Assert.Equal(expected.Item2, actual.Item2);"); + assert.AppendLine(Assertion.Equal("expected.Item1", "actual.Item1")); + assert.AppendLine(Assertion.Equal("expected.Item2", "actual.Item2")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index dc18df54f8..8463ae223b 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -35,12 +35,8 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) - { - const string template = "Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}.ToString(\"yyyy-MM-dd\"));"; - - return TemplateRenderer.RenderInline(template, new { method.ExpectedParameter, method.TestedValue }); - } + private static string RenderAssert(TestMethod method) + => Assertion.Equal(method.ExpectedParameter, $"{method.TestedValue}.ToString(\"yyyy-MM-dd\")"); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/Minesweeper.cs b/generators/Exercises/Generators/Minesweeper.cs index 5e5ed6ccc7..1aa2f88fea 100644 --- a/generators/Exercises/Generators/Minesweeper.cs +++ b/generators/Exercises/Generators/Minesweeper.cs @@ -12,23 +12,9 @@ protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; - - data.Input["minefield"] = ToMultiLineString(data.Input["minefield"]); - data.Expected = ToMultiLineString(data.Expected); - } - - private static UnescapedValue ToMultiLineString(JArray input) => new UnescapedValue("Array.Empty()"); - - private static UnescapedValue ToMultiLineString(IEnumerable input) - { - const string template = -@"new string[] -{ - {% if input.size > 0 %}{% for item in {{input}} %}{% if forloop.length == 1 %}""{{item}}""{% break %}{% endif %}""{{item}}""{% if forloop.last == false %},{% else %}{{string.Empty}}{% endif %} - {% endfor %}{% endif %} -}"; - - return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); + + if (data.Input["minefield"] is JArray) + data.Input["minefield"] = Array.Empty(); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index e5f83f2419..79aa506b83 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -1,8 +1,6 @@ using System.Collections.Generic; using System.Linq; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators { @@ -38,28 +36,13 @@ private static string RenderAssert(TestMethod method) : RenderThrowsAssert(method); } - private static string RenderEqualAssert(TestMethod method) - { - const string template = @"Assert.Equal(expected, sut.{{ TestedMethodName }});"; - - var templateParameters = new - { - TestedMethodName = method.Data.Property.ToTestedMethodName() - }; - - return TemplateRenderer.RenderInline(template, templateParameters); - } + private static string RenderEqualAssert(TestMethod method) + => Assertion.Equal("expected", $"sut.{method.Data.TestedMethod}"); private static string RenderThrowsAssert(TestMethod method) { - const string template = @"Assert.Throws(() => new NucleotideCount(""{{ Input }}""));"; - - var templateParameters = new - { - Input = method.Data.Input["strand"] - }; - - return TemplateRenderer.RenderInline(template, templateParameters); + var strand = ValueFormatter.Format(method.Data.Input["strand"]); + return Assertion.Throws("InvalidNucleotideException", $"new NucleotideCount({strand})"); } } } diff --git a/generators/Exercises/Generators/OcrNumbers.cs b/generators/Exercises/Generators/OcrNumbers.cs index d28f2c59b1..8654fc911a 100644 --- a/generators/Exercises/Generators/OcrNumbers.cs +++ b/generators/Exercises/Generators/OcrNumbers.cs @@ -1,8 +1,7 @@ using System; -using System.Collections; using System.Collections.Generic; +using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators { @@ -17,12 +16,20 @@ protected override void UpdateTestData(TestData data) data.UseVariablesForInput = true; } - private static UnescapedValue ToDigitStringRepresentation(IEnumerable input) + private static UnescapedValue ToDigitStringRepresentation(string[] input) { - const string template = @" {% for item in {{input}} %}{% if forloop.first == true %}""{{item}}"" + ""\n"" +{% continue %}{% endif %} - ""{{item}}""{% if forloop.last == false %} + ""\n"" +{% endif %}{% endfor %}"; + var lines = new StringBuilder(); + lines.AppendLine(); - return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); + for (var i = 0; i < input.Length; i++) + { + lines.Append(ValueFormatter.Format(input[i]).Indent()); + + if (i < input.Length - 1) + lines.Append(" + \"\\n\" +\n"); + } + + return new UnescapedValue(lines.ToString()); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index 045751d4ff..c5b88b2f4b 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -35,8 +35,8 @@ private static string RenderAssert(TestMethod method) } var assert = new StringBuilder(); - assert.AppendLine("Assert.Equal(expected.Item1, actual.Item1);"); - assert.AppendLine("Assert.Equal(expected.Item2, actual.Item2);"); + assert.AppendLine(Assertion.Equal("expected.Item1", "actual.Item1")); + assert.AppendLine(Assertion.Equal("expected.Item2", "actual.Item2")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index bf2c18a07c..2c4628f913 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Templates; @@ -29,34 +31,25 @@ private static string RenderAssert(TestMethod method) private static string RenderCanAttackAssert(TestMethod method) { - const string template = -@"var whiteQueen = QueenAttack.Create({{whiteQueenX}},{{whiteQueenY}}); -var blackQueen = QueenAttack.Create({{blackQueenX}},{{blackQueenY}}); -Assert.{% if Expected %}True{% else %}False{% endif %}(QueenAttack.CanAttack(whiteQueen, blackQueen));"; + var assert = new StringBuilder(); + + var (whiteQueenX, whiteQueenY) = GetCoordinatesFromPosition((IDictionary)method.Data.Input["white_queen"]); + var (blackQueenX, blackQueenY) = GetCoordinatesFromPosition((IDictionary)method.Data.Input["black_queen"]); - var whiteQueenPositions = GetCoordinatesFromPosition(method.Data.Input["white_queen"]); - var blackQueenPositions = GetCoordinatesFromPosition(method.Data.Input["black_queen"]); + assert.AppendLine($"var whiteQueen = QueenAttack.Create({whiteQueenX},{whiteQueenY});"); + assert.AppendLine($"var blackQueen = QueenAttack.Create({blackQueenX},{blackQueenY});"); + assert.AppendLine(Assertion.Boolean((bool)method.Data.Expected, "QueenAttack.CanAttack(whiteQueen, blackQueen)")); - var templateParameters = new - { - whiteQueenX = whiteQueenPositions.Item1, - whiteQueenY = whiteQueenPositions.Item2, - blackQueenX = blackQueenPositions.Item1, - blackQueenY = blackQueenPositions.Item2, - method.Data.Expected - }; - - return TemplateRenderer.RenderInline(template, templateParameters); + return assert.ToString(); } - private static Tuple GetCoordinatesFromPosition(dynamic expected) + private static ValueTuple GetCoordinatesFromPosition(IDictionary expected) { var coordinates = expected["position"]; - var positionX = (int)coordinates["row"]; var positionY = (int)coordinates["column"]; - return Tuple.Create(positionX, positionY); + return (positionX, positionY); } private static void SetCreatePropertyData(TestData canonicalDataCase) diff --git a/generators/Exercises/Generators/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs index 5c63477804..bc9667740b 100644 --- a/generators/Exercises/Generators/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -42,29 +42,12 @@ private static string RenderAct(TestMethod method) } } - private static string RenderDefaultAct(TestMethod method) - { - const string template = @"sut.{{MethodInvocation}}();"; - - var templateParameters = new - { - MethodInvocation = method.Data.Property.ToTestedMethodName() - }; - - return TemplateRenderer.RenderInline(template, templateParameters); - } + private static string RenderDefaultAct(TestMethod method) => $"sut.{method.Data.TestedMethod}();"; private static string RenderInstructionsAct(TestMethod method) { - const string template = @"sut.{{MethodInvocation}}(""{{Instructions}}"");"; - - var templateParameters = new - { - MethodInvocation = "Simulate", - Instructions = method.Data.Input["instructions"] - }; - - return TemplateRenderer.RenderInline(template, templateParameters); + var actual = ValueFormatter.Format(method.Data.Input["instructions"]); + return $"sut.Simulate({actual});"; } private static string RenderAssert(TestMethod method) @@ -73,25 +56,24 @@ private static string RenderAssert(TestMethod method) expected.TryGetValue("position", out var position); expected.TryGetValue("direction", out var direction); - var template = new StringBuilder(); + var assert = new StringBuilder(); if (direction != null) - template.AppendLine("Assert.Equal({{Direction}}, sut.Direction);"); + { + var expectedDirection = GetDirectionEnum(direction); + assert.AppendLine(Assertion.Equal(expectedDirection, "sut.Direction")); + } if (position != null) { - template.AppendLine("Assert.Equal({{X}}, sut.Coordinate.X);"); - template.AppendLine("Assert.Equal({{Y}}, sut.Coordinate.Y);"); + var x = ValueFormatter.Format(position["x"]); + var y = ValueFormatter.Format(position["y"]); + + assert.AppendLine(Assertion.Equal(x, "sut.Coordinate.X")); + assert.AppendLine(Assertion.Equal(y, "sut.Coordinate.Y")); } - - var templateParameters = new - { - Direction = !string.IsNullOrEmpty(direction) ? GetDirectionEnum(direction) : null, - X = position?["x"], - Y = position?["y"] - }; - - return TemplateRenderer.RenderInline(template.ToString(), templateParameters); + + return assert.ToString(); } private static string GetDirectionEnum(string direction) diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index 237049e196..668aa9cb17 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -1,5 +1,4 @@ using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators { @@ -24,15 +23,9 @@ private static string RenderAssert(TestMethod method) private static string RenderConsistencyToAssert(TestMethod method) { - const string template = @"Assert.Equal(""{{Expected}}"", {{TestedClassName}}.Decode({{TestedClassName}}.Encode(""{{Expected}}"")));"; - - var templateParameters = new - { - method.Data.Expected, - TestedClassName = method.Data.TestedClass - }; - - return TemplateRenderer.RenderInline(template, templateParameters); + var expected = ValueFormatter.Format(method.Data.Expected); + var actual = $"{method.Data.TestedClass}.Decode({method.Data.TestedClass}.Encode({expected}))"; + return Assertion.Equal(expected, actual); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index 4b96214caf..9b513da34a 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -54,10 +54,10 @@ private static string RenderAssert(TestMethod method) { case "new": var key = ValueFormatter.Format(method.Data.Input["key"]); - return $"Assert.Throws(() => new SimpleCipher({key}));"; + return Assertion.Throws("ArgumentException", $"new SimpleCipher({key})"); case "key": var pattern = ValueFormatter.Format(method.Data.Expected["match"]); - return $"Assert.Matches({pattern}, sut.Key);"; + return Assertion.Matches(pattern, "sut.Key"); default: return method.Assert; } diff --git a/generators/Exercises/Generators/Tournament.cs b/generators/Exercises/Generators/Tournament.cs index cf1685b97b..d54c672cfe 100644 --- a/generators/Exercises/Generators/Tournament.cs +++ b/generators/Exercises/Generators/Tournament.cs @@ -3,7 +3,6 @@ using System.IO; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Exercises.Generators { @@ -31,8 +30,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(); } - private static string RenderAssert() - => TemplateRenderer.RenderInline(@"Assert.Equal(expected, RunTally(rows));", new { }); + private static string RenderAssert() => Assertion.Equal("expected", "RunTally(rows)"); protected override void UpdateTestClass(TestClass @class) { diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index 0e3138f028..bf417af41e 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -1,5 +1,7 @@ +using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Templates; +using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -20,33 +22,19 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAct(TestMethod method) - { - const string template = @"var result = {{MethodInvocation}};"; - - var templateParameters = new - { - MethodInvocation = method.TestedMethodInvocation - }; - - return TemplateRenderer.RenderInline(template, templateParameters); - } + private static string RenderAct(TestMethod method) => $"var result = {method.TestedMethodInvocation};"; private static string RenderAssert(TestMethod method) { - const string template = -@"Assert.Equal({{MovesExpected}}, result.Moves); -Assert.Equal({{OtherBucketExpected}}, result.OtherBucket); -Assert.Equal({% if GoalBucketExpected == 'two' %}Bucket.Two{% else %}Bucket.One{% endif %}, result.GoalBucket);"; - - var templateParameters = new - { - MovesExpected = method.Data.Expected["moves"], - OtherBucketExpected = method.Data.Expected["otherBucket"], - GoalBucketExpected = method.Data.Expected["goalBucket"] - }; - - return TemplateRenderer.RenderInline(template, templateParameters); + var assert = new StringBuilder(); + assert.AppendLine(Assertion.Equal(method.Data.Expected["moves"].ToString(), "result.Moves")); + assert.AppendLine(Assertion.Equal(method.Data.Expected["otherBucket"].ToString(), "result.OtherBucket")); + + var goalBucket = (string) method.Data.Expected["goalBucket"]; + var expected = $"Bucket.{goalBucket.Humanize()}"; + assert.AppendLine(Assertion.Equal(expected, "result.GoalBucket")); + + return assert.ToString(); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 663d85ebb0..02c86e2e99 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -48,8 +48,8 @@ private string RenderAssert() private static string RenderAssertForSearchWord(string word, dynamic expected) { return expected == null - ? $"Assert.Null(expected[\"{word}\"]);" - : $"Assert.Equal(expected[\"{word}\"], actual[\"{word}\"]);"; + ? Assertion.Null($"expected[\"{word}\"]") + : Assertion.Equal($"expected[\"{word}\"]", $"actual[\"{word}\"]"); } private static string FormatPosition(dynamic position) diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index 3ee5137d38..83eb9887c7 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -31,12 +31,12 @@ private static string RenderAssert(TestMethod method) var expected = RenderExpected(method.Data.Expected); if (expected == null) { - return "Assert.Null(actual);"; + return Assertion.Null("actual"); } var assert = new StringBuilder(); assert.AppendLine($"var expected = {expected};"); - assert.AppendLine("Assert.Equal(expected, actual);"); + assert.AppendLine(Assertion.Equal("expected", "actual")); return assert.ToString(); } diff --git a/generators/Output/Assertion.cs b/generators/Output/Assertion.cs index 01ed2cb3e0..0ab5900e4d 100644 --- a/generators/Output/Assertion.cs +++ b/generators/Output/Assertion.cs @@ -1,24 +1,32 @@ -using System; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Output { public static class Assertion { - public static string Null(string testedValue) - => Render("AssertNull", new { TestedValue = testedValue }); + public static string Null(string actual) + => Render("AssertNull", new { actual }); - public static string Empty(string testedValue, string expectedParameter) - => Render("AssertEmpty", new { TestedValue = testedValue, ExpectedParameter = expectedParameter }); + public static string Empty(string expected, string actual) + => Render("AssertEmpty", new { expected, actual }); - public static string Equal(string testedValue, string expectedParameter) - => Render("AssertEqual", new { TestedValue = testedValue, ExpectedParameter = expectedParameter }); + public static string Equal(string expected, string actual) + => Render("AssertEqual", new { expected, actual }); - public static string Exception(string testedValue, Type exceptionType) - => Render("AssertException", new { TestedValue = testedValue, ExceptionType = exceptionType.Name }); + public static string EqualWithin(string expected, string actual, int precision) + => Render("AssertEqualWithin", new { expected, actual, precision }); - public static string Boolean(string testedValue, bool expected) - => Render("AssertBoolean", new { TestedValue = testedValue, BooleanAssertMethod = expected.ToString() }); + public static string NotEqual(string expected, string actual) + => Render("AssertNotEqual", new { expected, actual }); + + public static string Throws(string expectedException, string actual) + => Render("AssertThrows", new { expected = expectedException, actual }); + + public static string Boolean(bool expected, string actual) + => Render("AssertBoolean", new { expected = expected.ToString(), actual }); + + public static string Matches(string expected, string actual) + => Render("AssertMatches", new { expected, actual }); private static string Render(string template, object parameters) => TemplateRenderer.RenderPartial(template, parameters); diff --git a/generators/Output/Templates/_AssertBoolean.liquid b/generators/Output/Templates/_AssertBoolean.liquid index 1b1e21bf36..09377ab8b1 100644 --- a/generators/Output/Templates/_AssertBoolean.liquid +++ b/generators/Output/Templates/_AssertBoolean.liquid @@ -1 +1 @@ -Assert.{{ BooleanAssertMethod}}({{ TestedValue }}); \ No newline at end of file +Assert.{{ expected }}({{ actual }}); \ No newline at end of file diff --git a/generators/Output/Templates/_AssertEmpty.liquid b/generators/Output/Templates/_AssertEmpty.liquid index 609e5c97fa..e9c3bd6d5d 100644 --- a/generators/Output/Templates/_AssertEmpty.liquid +++ b/generators/Output/Templates/_AssertEmpty.liquid @@ -1 +1 @@ -Assert.Empty({{ TestedValue }}); \ No newline at end of file +Assert.Empty({{ actual }}); \ No newline at end of file diff --git a/generators/Output/Templates/_AssertEqual.liquid b/generators/Output/Templates/_AssertEqual.liquid index 1103752cdb..2333a5bfea 100644 --- a/generators/Output/Templates/_AssertEqual.liquid +++ b/generators/Output/Templates/_AssertEqual.liquid @@ -1 +1 @@ -Assert.Equal({{ ExpectedParameter }}, {{ TestedValue }}); \ No newline at end of file +Assert.Equal({{ expected }}, {{ actual }}); \ No newline at end of file diff --git a/generators/Output/Templates/_AssertEqualWithin.liquid b/generators/Output/Templates/_AssertEqualWithin.liquid new file mode 100644 index 0000000000..3bb7756cf2 --- /dev/null +++ b/generators/Output/Templates/_AssertEqualWithin.liquid @@ -0,0 +1 @@ +Assert.Equal({{ expected }}, {{ actual }}, precision: {{ precision }}); \ No newline at end of file diff --git a/generators/Output/Templates/_AssertException.liquid b/generators/Output/Templates/_AssertException.liquid deleted file mode 100644 index 04efd3ca5a..0000000000 --- a/generators/Output/Templates/_AssertException.liquid +++ /dev/null @@ -1 +0,0 @@ -Assert.Throws<{{ ExceptionType }}>(() => {{ TestedValue }}); \ No newline at end of file diff --git a/generators/Output/Templates/_AssertMatches.liquid b/generators/Output/Templates/_AssertMatches.liquid new file mode 100644 index 0000000000..d84f82b6e2 --- /dev/null +++ b/generators/Output/Templates/_AssertMatches.liquid @@ -0,0 +1 @@ +Assert.Matches({{ expected }}, {{ actual }}); \ No newline at end of file diff --git a/generators/Output/Templates/_AssertNotEqual.liquid b/generators/Output/Templates/_AssertNotEqual.liquid new file mode 100644 index 0000000000..b3af0ab819 --- /dev/null +++ b/generators/Output/Templates/_AssertNotEqual.liquid @@ -0,0 +1 @@ +Assert.NotEqual({{ expected }}, {{ actual }}); \ No newline at end of file diff --git a/generators/Output/Templates/_AssertNull.liquid b/generators/Output/Templates/_AssertNull.liquid index 93d9af2a94..3b88555e7b 100644 --- a/generators/Output/Templates/_AssertNull.liquid +++ b/generators/Output/Templates/_AssertNull.liquid @@ -1 +1 @@ -Assert.Null({{ TestedValue }}); \ No newline at end of file +Assert.Null({{ actual }}); \ No newline at end of file diff --git a/generators/Output/Templates/_AssertThrows.liquid b/generators/Output/Templates/_AssertThrows.liquid new file mode 100644 index 0000000000..5c700c93e6 --- /dev/null +++ b/generators/Output/Templates/_AssertThrows.liquid @@ -0,0 +1 @@ +Assert.Throws<{{ expected }}>(() => {{ actual }}); \ No newline at end of file diff --git a/generators/Output/TestMethodWithBooleanAssertion.cs b/generators/Output/TestMethodWithBooleanAssertion.cs index b41cc21053..b2d77f6c1e 100644 --- a/generators/Output/TestMethodWithBooleanAssertion.cs +++ b/generators/Output/TestMethodWithBooleanAssertion.cs @@ -8,6 +8,6 @@ public TestMethodWithBooleanAssertion(TestData data) : base(data) { } - protected override string RenderAssert() => Assertion.Boolean(TestedValue, Convert.ToBoolean(Data.Expected)); + protected override string RenderAssert() => Assertion.Boolean(Convert.ToBoolean(Data.Expected), TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEmptyAssertion.cs b/generators/Output/TestMethodWithEmptyAssertion.cs index 2cbde1fcdf..da5ae57a52 100644 --- a/generators/Output/TestMethodWithEmptyAssertion.cs +++ b/generators/Output/TestMethodWithEmptyAssertion.cs @@ -7,6 +7,6 @@ public TestMethodWithEmptyAssertion(TestData data): base(data) Data.UseVariableForExpected = false; } - protected override string RenderAssert() => Assertion.Empty(TestedValue, ExpectedParameter); + protected override string RenderAssert() => Assertion.Empty(ExpectedParameter, TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEqualityAssertion.cs b/generators/Output/TestMethodWithEqualityAssertion.cs index 9c93c54007..9f348fd173 100644 --- a/generators/Output/TestMethodWithEqualityAssertion.cs +++ b/generators/Output/TestMethodWithEqualityAssertion.cs @@ -6,6 +6,6 @@ public TestMethodWithEqualityAssertion(TestData data) : base(data) { } - protected override string RenderAssert() => Assertion.Equal(TestedValue, ExpectedParameter); + protected override string RenderAssert() => Assertion.Equal(ExpectedParameter, TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithExceptionAssertion.cs b/generators/Output/TestMethodWithExceptionAssertion.cs index 2f5188344b..9671ec60e8 100644 --- a/generators/Output/TestMethodWithExceptionAssertion.cs +++ b/generators/Output/TestMethodWithExceptionAssertion.cs @@ -8,6 +8,6 @@ public TestMethodWithExceptionAssertion(TestData data) : base(data) Data.UseVariableForTested = false; } - protected override string RenderAssert() => Assertion.Exception(TestedValue, Data.ExceptionThrown); + protected override string RenderAssert() => Assertion.Throws(Data.ExceptionThrown.Name, TestedValue); } } \ No newline at end of file From 31627be7e9da701095d485e4706bb015020df859 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 29 Jun 2018 22:28:23 +0200 Subject: [PATCH 48/97] generators: Add throws assertion generic overload --- exercises/nucleotide-count/Example.cs | 4 +--- exercises/nucleotide-count/NucleotideCount.cs | 4 +--- exercises/nucleotide-count/NucleotideCountTest.cs | 2 +- generators/Exercises/Generators/Bowling.cs | 4 ++-- generators/Exercises/Generators/CircularBuffer.cs | 4 ++-- generators/Exercises/Generators/NucleotideCount.cs | 5 +++-- generators/Exercises/Generators/SimpleCipher.cs | 2 +- generators/Output/Assertion.cs | 12 ++++++++---- .../Output/TestMethodWithExceptionAssertion.cs | 2 +- 9 files changed, 20 insertions(+), 19 deletions(-) diff --git a/exercises/nucleotide-count/Example.cs b/exercises/nucleotide-count/Example.cs index 6fb509a90d..b25845a936 100644 --- a/exercises/nucleotide-count/Example.cs +++ b/exercises/nucleotide-count/Example.cs @@ -20,9 +20,7 @@ private void InitializeNucleotideCounts(string sequence) } catch (KeyNotFoundException) { - throw new InvalidNucleotideException(); + throw new ArgumentException(); } } } - -public class InvalidNucleotideException : Exception { } diff --git a/exercises/nucleotide-count/NucleotideCount.cs b/exercises/nucleotide-count/NucleotideCount.cs index 4f71c41d2e..310a058299 100644 --- a/exercises/nucleotide-count/NucleotideCount.cs +++ b/exercises/nucleotide-count/NucleotideCount.cs @@ -14,6 +14,4 @@ public IDictionary NucleotideCounts throw new NotImplementedException("You need to implement this function."); } } -} - -public class InvalidNucleotideException : Exception { } +} \ No newline at end of file diff --git a/exercises/nucleotide-count/NucleotideCountTest.cs b/exercises/nucleotide-count/NucleotideCountTest.cs index 22646544d3..bf3bdac204 100644 --- a/exercises/nucleotide-count/NucleotideCountTest.cs +++ b/exercises/nucleotide-count/NucleotideCountTest.cs @@ -64,6 +64,6 @@ public void Strand_with_multiple_nucleotides() [Fact(Skip = "Remove to run test")] public void Strand_with_invalid_nucleotides() { - Assert.Throws(() => new NucleotideCount("AGXXACT")); + Assert.Throws(() => new NucleotideCount("AGXXACT")); } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index b447b4fd8c..af4b61ae98 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -58,14 +58,14 @@ private static string RenderAssert(TestMethod method) if (method.Data.ExceptionThrown != null && method.Data.Input.ContainsKey("roll")) { var actual = ValueFormatter.Format(method.Data.Input["roll"]); - return Assertion.Throws(method.Data.ExceptionThrown.Name, $"sut.Roll({actual})"); + return Assertion.Throws(method.Data.ExceptionThrown, $"sut.Roll({actual})"); } if (method.Data.ExceptionThrown == null || method.Data.Property != "score") return method.Assert; - return Assertion.Throws(method.Data.ExceptionThrown.Name, $"sut.Score()"); + return Assertion.Throws(method.Data.ExceptionThrown, "sut.Score()"); } private static string RenderAct(TestMethod method) diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index aa37067e45..56c5055298 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -50,14 +50,14 @@ private static string RenderReadOperation(dynamic operation) { return operation["should_succeed"] ? Assertion.Equal(operation["expected"].ToString(), "buffer.Read()") - : Assertion.Throws("InvalidOperationException", "buffer.Read()"); + : Assertion.Throws("buffer.Read()"); } private static string RenderWriteOperation(dynamic operation) { return operation["should_succeed"] ? $"buffer.Write({operation["item"]});" - : Assertion.Throws("InvalidOperationException", $"buffer.Write({operation["item"]})"); + : Assertion.Throws($"buffer.Write({operation["item"]})"); } private static string RenderOverwriteOperation(dynamic operation) diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index 79aa506b83..88a9be9b50 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; @@ -42,7 +43,7 @@ private static string RenderEqualAssert(TestMethod method) private static string RenderThrowsAssert(TestMethod method) { var strand = ValueFormatter.Format(method.Data.Input["strand"]); - return Assertion.Throws("InvalidNucleotideException", $"new NucleotideCount({strand})"); + return Assertion.Throws($"new NucleotideCount({strand})"); } } } diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index 9b513da34a..8f850721b1 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -54,7 +54,7 @@ private static string RenderAssert(TestMethod method) { case "new": var key = ValueFormatter.Format(method.Data.Input["key"]); - return Assertion.Throws("ArgumentException", $"new SimpleCipher({key})"); + return Assertion.Throws($"new SimpleCipher({key})"); case "key": var pattern = ValueFormatter.Format(method.Data.Expected["match"]); return Assertion.Matches(pattern, "sut.Key"); diff --git a/generators/Output/Assertion.cs b/generators/Output/Assertion.cs index 0ab5900e4d..69a63fdf61 100644 --- a/generators/Output/Assertion.cs +++ b/generators/Output/Assertion.cs @@ -1,4 +1,5 @@ -using Exercism.CSharp.Output.Templates; +using System; +using Exercism.CSharp.Output.Templates; namespace Exercism.CSharp.Output { @@ -19,15 +20,18 @@ public static string EqualWithin(string expected, string actual, int precision) public static string NotEqual(string expected, string actual) => Render("AssertNotEqual", new { expected, actual }); - public static string Throws(string expectedException, string actual) - => Render("AssertThrows", new { expected = expectedException, actual }); - public static string Boolean(bool expected, string actual) => Render("AssertBoolean", new { expected = expected.ToString(), actual }); public static string Matches(string expected, string actual) => Render("AssertMatches", new { expected, actual }); + public static string Throws(Type expectedException, string actual) + => Render("AssertThrows", new { expected = expectedException.Name, actual }); + + public static string Throws(string actual) + => Throws(typeof(T), actual); + private static string Render(string template, object parameters) => TemplateRenderer.RenderPartial(template, parameters); } diff --git a/generators/Output/TestMethodWithExceptionAssertion.cs b/generators/Output/TestMethodWithExceptionAssertion.cs index 9671ec60e8..4923ad6d4e 100644 --- a/generators/Output/TestMethodWithExceptionAssertion.cs +++ b/generators/Output/TestMethodWithExceptionAssertion.cs @@ -8,6 +8,6 @@ public TestMethodWithExceptionAssertion(TestData data) : base(data) Data.UseVariableForTested = false; } - protected override string RenderAssert() => Assertion.Throws(Data.ExceptionThrown.Name, TestedValue); + protected override string RenderAssert() => Assertion.Throws(Data.ExceptionThrown, TestedValue); } } \ No newline at end of file From bbfa24ba396b5e736e1f98ba3c51b0835900a62f Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 29 Jun 2018 22:33:42 +0200 Subject: [PATCH 49/97] generators: Use standard value formatter in binary search tree generator --- generators/Exercises/Generators/BinarySearchTree.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index fd6e5e2d47..65efdcdd6f 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -63,8 +63,9 @@ private string RenderAssert(TestMethod method) } else { - var expectedArrayString = string.Join(", ", canonicalDataCase.Expected as string[]); - AddCodeLine(Assertion.Equal($"new[] {{ {expectedArrayString} }}", "tree.AsEnumerable()")); + var expectedNumbers = ((string[]) canonicalDataCase.Expected).Select(int.Parse).ToArray(); + var expectedFormatted = ValueFormatter.Format(expectedNumbers); + AddCodeLine(Assertion.Equal(expectedFormatted, "tree.AsEnumerable()")); } return _testFactCodeLines.ToString(); From 52d22334cd6959a26878531c69a87cf69041d6be Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 30 Jun 2018 10:18:02 +0200 Subject: [PATCH 50/97] generators: Introduce rendering namespace --- exercises/bowling/BowlingTest.cs | 2 +- exercises/connect/ConnectTest.cs | 52 +++---- generators/Exercises/Generators/Allergies.cs | 4 +- generators/Exercises/Generators/BeerSong.cs | 1 + .../Exercises/Generators/BinarySearchTree.cs | 7 +- generators/Exercises/Generators/Bowling.cs | 35 ++--- .../Exercises/Generators/CircularBuffer.cs | 7 +- generators/Exercises/Generators/Clock.cs | 7 +- .../Exercises/Generators/ComplexNumbers.cs | 8 +- generators/Exercises/Generators/Connect.cs | 18 +-- generators/Exercises/Generators/CustomSet.cs | 3 +- generators/Exercises/Generators/Dominoes.cs | 1 + .../Exercises/Generators/FlattenArray.cs | 1 + generators/Exercises/Generators/FoodChain.cs | 1 + generators/Exercises/Generators/Gigasecond.cs | 1 + generators/Exercises/Generators/GoCounting.cs | 15 +- generators/Exercises/Generators/Grep.cs | 1 + generators/Exercises/Generators/House.cs | 1 + .../Generators/KindergartenGarden.cs | 1 + generators/Exercises/Generators/ListOps.cs | 7 +- generators/Exercises/Generators/Meetup.cs | 4 +- .../Exercises/Generators/Minesweeper.cs | 1 - .../Exercises/Generators/NucleotideCount.cs | 7 +- generators/Exercises/Generators/OcrNumbers.cs | 3 +- .../Generators/PalindromeProducts.cs | 7 +- .../Exercises/Generators/PerfectNumbers.cs | 1 + generators/Exercises/Generators/Pov.cs | 3 +- .../Exercises/Generators/QueenAttack.cs | 4 +- .../Exercises/Generators/RationalNumbers.cs | 3 +- .../Exercises/Generators/RobotSimulator.cs | 15 +- .../Exercises/Generators/RunLengthEncoding.cs | 5 +- .../Exercises/Generators/SimpleCipher.cs | 11 +- generators/Exercises/Generators/Sublist.cs | 1 + generators/Exercises/Generators/Tournament.cs | 3 +- generators/Exercises/Generators/Transpose.cs | 1 + generators/Exercises/Generators/TwelveDays.cs | 1 + generators/Exercises/Generators/TwoBucket.cs | 8 +- .../Generators/VariableLengthQuantity.cs | 1 + generators/Exercises/Generators/WordSearch.cs | 9 +- generators/Exercises/Generators/Yacht.cs | 1 + .../Exercises/Generators/ZebraPuzzle.cs | 1 + generators/Exercises/Generators/Zipper.cs | 5 +- generators/Generators.csproj | 2 +- .../{ => Rendering}/FormattingExtensions.cs | 2 +- .../{Templates => Rendering}/IndentFilter.cs | 2 +- .../Output/{ => Rendering}/MultiLineString.cs | 2 +- .../Render.cs} | 136 +++++++++--------- .../RenderAssert.cs} | 25 ++-- generators/Output/Rendering/Template.cs | 20 +++ .../{ => Rendering}/Templates/_Act.liquid | 0 .../{ => Rendering}/Templates/_Arrange.liquid | 0 .../Templates/_AssertBoolean.liquid | 0 .../Templates/_AssertEmpty.liquid | 0 .../Templates/_AssertEqual.liquid | 0 .../Templates/_AssertEqualWithin.liquid | 0 .../Templates/_AssertMatches.liquid | 0 .../Templates/_AssertNotEqual.liquid | 0 .../Templates/_AssertNull.liquid | 0 .../Templates/_AssertThrows.liquid | 0 .../Templates/_TestClass.liquid | 0 .../Templates/_TestMethod.liquid | 0 .../Output/{ => Rendering}/UnescapedValue.cs | 2 +- .../Output/Templates/TemplateRenderer.cs | 23 --- generators/Output/TestClass.cs | 4 +- generators/Output/TestMethod.cs | 20 +-- .../Output/TestMethodWithBooleanAssertion.cs | 2 +- .../Output/TestMethodWithEmptyAssertion.cs | 2 +- .../Output/TestMethodWithEqualityAssertion.cs | 2 +- .../TestMethodWithExceptionAssertion.cs | 2 +- .../Output/TestMethodWithNullAssertion.cs | 2 +- 70 files changed, 257 insertions(+), 259 deletions(-) rename generators/Output/{ => Rendering}/FormattingExtensions.cs (94%) rename generators/Output/{Templates => Rendering}/IndentFilter.cs (88%) rename generators/Output/{ => Rendering}/MultiLineString.cs (89%) rename generators/Output/{ValueFormatter.cs => Rendering/Render.cs} (60%) rename generators/Output/{Assertion.cs => Rendering/RenderAssert.cs} (50%) create mode 100644 generators/Output/Rendering/Template.cs rename generators/Output/{ => Rendering}/Templates/_Act.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_Arrange.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_AssertBoolean.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_AssertEmpty.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_AssertEqual.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_AssertEqualWithin.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_AssertMatches.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_AssertNotEqual.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_AssertNull.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_AssertThrows.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_TestClass.liquid (100%) rename generators/Output/{ => Rendering}/Templates/_TestMethod.liquid (100%) rename generators/Output/{ => Rendering}/UnescapedValue.cs (87%) delete mode 100644 generators/Output/Templates/TemplateRenderer.cs diff --git a/exercises/bowling/BowlingTest.cs b/exercises/bowling/BowlingTest.cs index 230ddbfdcf..20f928787f 100644 --- a/exercises/bowling/BowlingTest.cs +++ b/exercises/bowling/BowlingTest.cs @@ -291,7 +291,7 @@ public void Cannot_roll_after_bonus_rolls_for_strike() Assert.Throws(() => sut.Roll(2)); } - public void DoRoll(ICollection rolls, BowlingGame sut) + public void DoRoll(IEnumerable rolls, BowlingGame sut) { foreach (var roll in rolls) { diff --git a/exercises/connect/ConnectTest.cs b/exercises/connect/ConnectTest.cs index 2417d52d6d..6e0da7f075 100644 --- a/exercises/connect/ConnectTest.cs +++ b/exercises/connect/ConnectTest.cs @@ -7,14 +7,13 @@ public class ConnectTest [Fact] public void An_empty_board_has_no_winner() { - var board = new [] - { + var board = new[] + { ". . . . .", " . . . . .", " . . . . .", " . . . . .", " . . . . ." - }; var sut = new Connect(board); Assert.Equal(ConnectWinner.None, sut.Result()); @@ -23,9 +22,9 @@ public void An_empty_board_has_no_winner() [Fact(Skip = "Remove to run test")] public void X_can_win_on_a_1x1_board() { - var board = new [] - { - "X" + var board = new[] + { + "X" }; var sut = new Connect(board); Assert.Equal(ConnectWinner.Black, sut.Result()); @@ -34,9 +33,9 @@ public void X_can_win_on_a_1x1_board() [Fact(Skip = "Remove to run test")] public void O_can_win_on_a_1x1_board() { - var board = new [] - { - "O" + var board = new[] + { + "O" }; var sut = new Connect(board); Assert.Equal(ConnectWinner.White, sut.Result()); @@ -45,13 +44,12 @@ public void O_can_win_on_a_1x1_board() [Fact(Skip = "Remove to run test")] public void Only_edges_does_not_make_a_winner() { - var board = new [] - { + var board = new[] + { "O O O X", " X . . X", " X . . X", " X O O O" - }; var sut = new Connect(board); Assert.Equal(ConnectWinner.None, sut.Result()); @@ -60,14 +58,13 @@ public void Only_edges_does_not_make_a_winner() [Fact(Skip = "Remove to run test")] public void Illegal_diagonal_does_not_make_a_winner() { - var board = new [] - { + var board = new[] + { "X O . .", " O X X X", " O X O .", " . O X .", " X X O O" - }; var sut = new Connect(board); Assert.Equal(ConnectWinner.None, sut.Result()); @@ -76,14 +73,13 @@ public void Illegal_diagonal_does_not_make_a_winner() [Fact(Skip = "Remove to run test")] public void Nobody_wins_crossing_adjacent_angles() { - var board = new [] - { + var board = new[] + { "X . . .", " . X O .", " O . X O", " . O . X", " . . O ." - }; var sut = new Connect(board); Assert.Equal(ConnectWinner.None, sut.Result()); @@ -92,14 +88,13 @@ public void Nobody_wins_crossing_adjacent_angles() [Fact(Skip = "Remove to run test")] public void X_wins_crossing_from_left_to_right() { - var board = new [] - { + var board = new[] + { ". O . .", " O X X X", " O X O .", " X X O X", " . O X ." - }; var sut = new Connect(board); Assert.Equal(ConnectWinner.Black, sut.Result()); @@ -108,14 +103,13 @@ public void X_wins_crossing_from_left_to_right() [Fact(Skip = "Remove to run test")] public void O_wins_crossing_from_top_to_bottom() { - var board = new [] - { + var board = new[] + { ". O . .", " O X X X", " O O O .", " X X O X", " . O X ." - }; var sut = new Connect(board); Assert.Equal(ConnectWinner.White, sut.Result()); @@ -124,14 +118,13 @@ public void O_wins_crossing_from_top_to_bottom() [Fact(Skip = "Remove to run test")] public void X_wins_using_a_convoluted_path() { - var board = new [] - { + var board = new[] + { ". X X . .", " X . X . X", " . X . X .", " . X X . .", " O O O O O" - }; var sut = new Connect(board); Assert.Equal(ConnectWinner.Black, sut.Result()); @@ -140,8 +133,8 @@ public void X_wins_using_a_convoluted_path() [Fact(Skip = "Remove to run test")] public void X_wins_using_a_spiral_path() { - var board = new [] - { + var board = new[] + { "O X X X X X X X X", " O X O O O O O O O", " O X O X X X X X O", @@ -151,7 +144,6 @@ public void X_wins_using_a_spiral_path() " O X X X X X O X O", " O O O O O O O X O", " X X X X X X X X O" - }; var sut = new Connect(board); Assert.Equal(ConnectWinner.Black, sut.Result()); diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index d08727833c..ceff08f034 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -1,6 +1,6 @@ using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -33,7 +33,7 @@ private static string RenderIsAllergicToAssert(TestMethod method) var assert = new StringBuilder(); foreach (var allergy in method.Data.Expected) - assert.AppendLine(Assertion.Boolean(allergy["result"], $"sut.IsAllergicTo({ValueFormatter.Format(allergy["substance"])})")); + assert.AppendLine(Render.Assert.Boolean(allergy["result"], $"sut.IsAllergicTo({Render.Object(allergy["substance"])})")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/BeerSong.cs b/generators/Exercises/Generators/BeerSong.cs index ee6bf0ce1d..d79cab351c 100644 --- a/generators/Exercises/Generators/BeerSong.cs +++ b/generators/Exercises/Generators/BeerSong.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 65efdcdd6f..1da5f670e1 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -20,7 +21,7 @@ public ExpectedDataBinaryTree(IReadOnlyDictionary treeNode) public IEnumerable TestAsserts(string traverse = "") { - yield return Assertion.Equal(Value, $"tree{traverse}.Value"); + yield return Render.Assert.Equal(Value, $"tree{traverse}.Value"); if (Left != null) foreach (var assert in Left.TestAsserts(traverse + ".Left")) yield return assert; if (Right != null) foreach (var assert in Right.TestAsserts(traverse + ".Right")) yield return assert; } @@ -64,8 +65,8 @@ private string RenderAssert(TestMethod method) else { var expectedNumbers = ((string[]) canonicalDataCase.Expected).Select(int.Parse).ToArray(); - var expectedFormatted = ValueFormatter.Format(expectedNumbers); - AddCodeLine(Assertion.Equal(expectedFormatted, "tree.AsEnumerable()")); + var expectedFormatted = Render.Object(expectedNumbers); + AddCodeLine(Render.Assert.Equal(expectedFormatted, "tree.AsEnumerable()")); } return _testFactCodeLines.ToString(); diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index af4b61ae98..78da943c91 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -57,43 +57,36 @@ private static string RenderAssert(TestMethod method) { if (method.Data.ExceptionThrown != null && method.Data.Input.ContainsKey("roll")) { - var actual = ValueFormatter.Format(method.Data.Input["roll"]); - return Assertion.Throws(method.Data.ExceptionThrown, $"sut.Roll({actual})"); + var actual = Render.Object(method.Data.Input["roll"]); + return Render.Assert.Throws(method.Data.ExceptionThrown, $"sut.Roll({actual})"); } if (method.Data.ExceptionThrown == null || method.Data.Property != "score") return method.Assert; - return Assertion.Throws(method.Data.ExceptionThrown, "sut.Score()"); + return Render.Assert.Throws(method.Data.ExceptionThrown, "sut.Score()"); } private static string RenderAct(TestMethod method) { - var template = - @"DoRoll(previousRolls, sut); -"; - + var act = new StringBuilder(); + act.AppendLine("DoRoll(previousRolls, sut);"); + if (method.Data.ExceptionThrown != null) { - return template; + return act.ToString(); } if (method.Data.Input.ContainsKey("roll")) { - template += - @"sut.Roll({{RolVal}}); -var actual = sut.Score(); -"; - var templateParameters = new - { - RolVal = method.Data.Input["roll"] - }; - return TemplateRenderer.RenderInline(template, templateParameters); + act.AppendLine($"sut.Roll({method.Data.Input["roll"]});"); + act.AppendLine("var actual = sut.Score();"); + return act.ToString(); } - template += "var actual = sut.Score();"; - return template; + act.AppendLine("var actual = sut.Score();"); + return act.ToString(); } protected override void UpdateTestClass(TestClass @class) @@ -104,7 +97,7 @@ protected override void UpdateTestClass(TestClass @class) private static void AddDoRollMethod(TestClass @class) { @class.Methods.Add(@" -public void DoRoll(ICollection rolls, BowlingGame sut) +public void DoRoll(IEnumerable rolls, BowlingGame sut) { foreach (var roll in rolls) { diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index 56c5055298..2b5675aeed 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Text; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -49,15 +50,15 @@ private static string RenderOperation(dynamic operation) private static string RenderReadOperation(dynamic operation) { return operation["should_succeed"] - ? Assertion.Equal(operation["expected"].ToString(), "buffer.Read()") - : Assertion.Throws("buffer.Read()"); + ? Render.Assert.Equal(operation["expected"].ToString(), "buffer.Read()") + : Render.Assert.Throws("buffer.Read()"); } private static string RenderWriteOperation(dynamic operation) { return operation["should_succeed"] ? $"buffer.Write({operation["item"]});" - : Assertion.Throws($"buffer.Write({operation["item"]})"); + : Render.Assert.Throws($"buffer.Write({operation["item"]})"); } private static string RenderOverwriteOperation(dynamic operation) diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 29fe45ccf1..0889265225 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -55,15 +56,15 @@ private static string RenderAssert(TestMethod method) } private static string RenderConsistencyToAssert(TestMethod method) - => Assertion.Equal(method.ExpectedParameter, $"{method.TestedValue}.ToString()"); + => Render.Assert.Equal(method.ExpectedParameter, $"{method.TestedValue}.ToString()"); private static string RenderEqualToAssert(TestMethod method) { var expected = method.Data.Input[ParamClock1].ToString(); return method.Data.Expected - ? Assertion.Equal(expected, "sut") - : Assertion.NotEqual(expected, "sut"); + ? Render.Assert.Equal(expected, "sut") + : Render.Assert.NotEqual(expected, "sut"); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index 975e127fea..1be3f12d17 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -3,7 +3,7 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators @@ -47,8 +47,8 @@ private static string RenderAssert(TestMethod method) private static string RenderComplexNumberAssert(TestMethod method) { var assert = new StringBuilder(); - assert.AppendLine(Assertion.EqualWithin($"{method.ExpectedParameter}.Real()", $"{method.TestedValue}.Real()", 15)); - assert.AppendLine(Assertion.EqualWithin($"{method.ExpectedParameter}.Imaginary()", $"{method.TestedValue}.Imaginary()", 15)); + assert.AppendLine(Render.Assert.EqualWithin($"{method.ExpectedParameter}.Real()", $"{method.TestedValue}.Real()", 15)); + assert.AppendLine(Render.Assert.EqualWithin($"{method.ExpectedParameter}.Imaginary()", $"{method.TestedValue}.Imaginary()", 15)); return assert.ToString(); } @@ -60,7 +60,7 @@ protected override void UpdateNamespaces(ISet namespaces) private static object ConvertToType(dynamic rawValue) => IsComplexNumber(rawValue) - ? new UnescapedValue($"new ComplexNumber({ValueFormatter.Format(ConvertMathDouble(rawValue[0]))}, {ValueFormatter.Format(ConvertMathDouble(rawValue[1]))})") + ? new UnescapedValue($"new ComplexNumber({Render.Object(ConvertMathDouble(rawValue[0]))}, {Render.Object(ConvertMathDouble(rawValue[1]))})") : rawValue; private static bool IsComplexNumber(object rawValue) => rawValue is int[] || rawValue is double[] || rawValue is float[] || rawValue is JArray; diff --git a/generators/Exercises/Generators/Connect.cs b/generators/Exercises/Generators/Connect.cs index ad7e63fbaa..ceb3582c23 100644 --- a/generators/Exercises/Generators/Connect.cs +++ b/generators/Exercises/Generators/Connect.cs @@ -1,6 +1,5 @@ -using System.Collections; -using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -11,7 +10,6 @@ protected override void UpdateTestData(TestData data) data.UseVariablesForConstructorParameters = true; data.SetConstructorInputParameters("board"); data.TestedMethod = "Result"; - data.Input["board"] = ToMultiLineString(data.Input["board"]); switch (data.Expected) { @@ -26,17 +24,5 @@ protected override void UpdateTestData(TestData data) break; } } - - private static UnescapedValue ToMultiLineString(IEnumerable input) - { - const string template = - @"new [] -{ - {% if input.size == 0 %}string.Empty{% else %}{% for item in {{input}} %}{% if forloop.length == 1 %}""{{item}}""{% break %}{% endif %}""{{item}}""{% if forloop.last == false %},{% else %}{{string.Empty}}{% endif %} - {% endfor %}{% endif %} -}"; - - return new UnescapedValue(TemplateRenderer.RenderInline(template, new { input })); - } } } diff --git a/generators/Exercises/Generators/CustomSet.cs b/generators/Exercises/Generators/CustomSet.cs index bafa3332d1..f64b172679 100644 --- a/generators/Exercises/Generators/CustomSet.cs +++ b/generators/Exercises/Generators/CustomSet.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -43,7 +44,7 @@ private static dynamic ConvertCustomSet(dynamic value) case bool _: return value; case int[] values when values.Length > 0: - return new UnescapedValue($"new CustomSet({ValueFormatter.Format(values)})"); + return new UnescapedValue($"new CustomSet({Render.Object(values)})"); default: return new UnescapedValue("new CustomSet()"); } diff --git a/generators/Exercises/Generators/Dominoes.cs b/generators/Exercises/Generators/Dominoes.cs index 07896b1a11..4f9a905044 100644 --- a/generators/Exercises/Generators/Dominoes.cs +++ b/generators/Exercises/Generators/Dominoes.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Exercises/Generators/FlattenArray.cs b/generators/Exercises/Generators/FlattenArray.cs index ad264fde29..5fcbdcb3c4 100644 --- a/generators/Exercises/Generators/FlattenArray.cs +++ b/generators/Exercises/Generators/FlattenArray.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/FoodChain.cs b/generators/Exercises/Generators/FoodChain.cs index 1c39331e7a..eb6acb6a0b 100644 --- a/generators/Exercises/Generators/FoodChain.cs +++ b/generators/Exercises/Generators/FoodChain.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/Gigasecond.cs b/generators/Exercises/Generators/Gigasecond.cs index 7ae498cd40..fa76c1953d 100644 --- a/generators/Exercises/Generators/Gigasecond.cs +++ b/generators/Exercises/Generators/Gigasecond.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index c1e973c402..9d856bc042 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Humanizer; using Newtonsoft.Json.Linq; @@ -67,16 +68,16 @@ private static string RenderAssert(TestMethod method) if (method.Data.Property == "territories") { var territoriesAssert = new StringBuilder(); - territoriesAssert.AppendLine(Assertion.Equal("expected.Keys", "actual.Keys")); - territoriesAssert.AppendLine(Assertion.Equal("expected[Owner.Black]", "actual[Owner.Black]")); - territoriesAssert.AppendLine(Assertion.Equal("expected[Owner.White]", "actual[Owner.White]")); - territoriesAssert.AppendLine(Assertion.Equal("expected[Owner.None]", "actual[Owner.None]")); + territoriesAssert.AppendLine(Render.Assert.Equal("expected.Keys", "actual.Keys")); + territoriesAssert.AppendLine(Render.Assert.Equal("expected[Owner.Black]", "actual[Owner.Black]")); + territoriesAssert.AppendLine(Render.Assert.Equal("expected[Owner.White]", "actual[Owner.White]")); + territoriesAssert.AppendLine(Render.Assert.Equal("expected[Owner.None]", "actual[Owner.None]")); return territoriesAssert.ToString(); } var assert = new StringBuilder(); - assert.AppendLine(Assertion.Equal("expected.Item1", "actual.Item1")); - assert.AppendLine(Assertion.Equal("expected.Item2", "actual.Item2")); + assert.AppendLine(Render.Assert.Equal("expected.Item1", "actual.Item1")); + assert.AppendLine(Render.Assert.Equal("expected.Item2", "actual.Item2")); return assert.ToString(); } @@ -84,7 +85,7 @@ private static string FormatOwner(dynamic owner) => $"Owner.{(owner as string).ToLowerInvariant().Humanize()}"; private static string FormatTerritory(dynamic territory) - => ValueFormatter.Format((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); + => Render.Object((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/Grep.cs b/generators/Exercises/Generators/Grep.cs index 7cbf25c9e7..819be02f29 100644 --- a/generators/Exercises/Generators/Grep.cs +++ b/generators/Exercises/Generators/Grep.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/House.cs b/generators/Exercises/Generators/House.cs index bc446d532b..738e1d21bb 100644 --- a/generators/Exercises/Generators/House.cs +++ b/generators/Exercises/Generators/House.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/KindergartenGarden.cs b/generators/Exercises/Generators/KindergartenGarden.cs index b21b260ffe..e414286ed0 100644 --- a/generators/Exercises/Generators/KindergartenGarden.cs +++ b/generators/Exercises/Generators/KindergartenGarden.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Humanizer; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Exercises/Generators/ListOps.cs b/generators/Exercises/Generators/ListOps.cs index 8972d7d31f..0ae0e4ddb6 100644 --- a/generators/Exercises/Generators/ListOps.cs +++ b/generators/Exercises/Generators/ListOps.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators @@ -84,17 +85,17 @@ private static dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) var nestedList = jArray .Children() .Select(ConvertToList) - .Select(ValueFormatter.Format) + .Select(Render.Object) .Select(formattedValue => new UnescapedValue(formattedValue)) .ToList(); - return new UnescapedValue(ValueFormatter.Format(nestedList) + return new UnescapedValue(Render.Object(nestedList) .Replace("", "") .Replace("new List { new List", "new List> { new List") .Replace("new[] { new List>", "new List>> { new List>") .Replace("new[] { new List", "new List> { new List")); case IEnumerable ints: - return new UnescapedValue(ValueFormatter.Format(ints.ToList())); + return new UnescapedValue(Render.Object(ints.ToList())); } return value; diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index 8463ae223b..3d930b7edf 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Rendering; using Humanizer; namespace Exercism.CSharp.Exercises.Generators @@ -36,7 +36,7 @@ protected override void UpdateTestMethod(TestMethod method) } private static string RenderAssert(TestMethod method) - => Assertion.Equal(method.ExpectedParameter, $"{method.TestedValue}.ToString(\"yyyy-MM-dd\")"); + => Render.Assert.Equal(method.ExpectedParameter, $"{method.TestedValue}.ToString(\"yyyy-MM-dd\")"); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/Minesweeper.cs b/generators/Exercises/Generators/Minesweeper.cs index 1aa2f88fea..6ddec63513 100644 --- a/generators/Exercises/Generators/Minesweeper.cs +++ b/generators/Exercises/Generators/Minesweeper.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index 88a9be9b50..13419af8b2 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -38,12 +39,12 @@ private static string RenderAssert(TestMethod method) } private static string RenderEqualAssert(TestMethod method) - => Assertion.Equal("expected", $"sut.{method.Data.TestedMethod}"); + => Render.Assert.Equal("expected", $"sut.{method.Data.TestedMethod}"); private static string RenderThrowsAssert(TestMethod method) { - var strand = ValueFormatter.Format(method.Data.Input["strand"]); - return Assertion.Throws($"new NucleotideCount({strand})"); + var strand = Render.Object(method.Data.Input["strand"]); + return Render.Assert.Throws($"new NucleotideCount({strand})"); } } } diff --git a/generators/Exercises/Generators/OcrNumbers.cs b/generators/Exercises/Generators/OcrNumbers.cs index 8654fc911a..43e7e43ddd 100644 --- a/generators/Exercises/Generators/OcrNumbers.cs +++ b/generators/Exercises/Generators/OcrNumbers.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Text; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -23,7 +24,7 @@ private static UnescapedValue ToDigitStringRepresentation(string[] input) for (var i = 0; i < input.Length; i++) { - lines.Append(ValueFormatter.Format(input[i]).Indent()); + lines.Append(Render.Object(input[i]).Indent()); if (i < input.Length - 1) lines.Append(" + \"\\n\" +\n"); diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index c5b88b2f4b..d3af8917c7 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators @@ -35,12 +36,12 @@ private static string RenderAssert(TestMethod method) } var assert = new StringBuilder(); - assert.AppendLine(Assertion.Equal("expected.Item1", "actual.Item1")); - assert.AppendLine(Assertion.Equal("expected.Item2", "actual.Item2")); + assert.AppendLine(Render.Assert.Equal("expected.Item1", "actual.Item1")); + assert.AppendLine(Render.Assert.Equal("expected.Item2", "actual.Item2")); return assert.ToString(); } private static string FormatCoordinates(dynamic coordinates) - => ValueFormatter.Format((coordinates as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); + => Render.Object((coordinates as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); } } \ No newline at end of file diff --git a/generators/Exercises/Generators/PerfectNumbers.cs b/generators/Exercises/Generators/PerfectNumbers.cs index b884776187..2272d150f4 100644 --- a/generators/Exercises/Generators/PerfectNumbers.cs +++ b/generators/Exercises/Generators/PerfectNumbers.cs @@ -1,5 +1,6 @@ using System; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Humanizer; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Exercises/Generators/Pov.cs b/generators/Exercises/Generators/Pov.cs index bbad024a6f..df214949d5 100644 --- a/generators/Exercises/Generators/Pov.cs +++ b/generators/Exercises/Generators/Pov.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -30,7 +31,7 @@ private static UnescapedValue RenderTree(dynamic tree) var sb = new StringBuilder(); - var label = ValueFormatter.Format(tree["label"]); + var label = Render.Object(tree["label"]); if (tree.ContainsKey("children")) { diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index 2c4628f913..bf8def32d4 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -38,7 +38,7 @@ private static string RenderCanAttackAssert(TestMethod method) assert.AppendLine($"var whiteQueen = QueenAttack.Create({whiteQueenX},{whiteQueenY});"); assert.AppendLine($"var blackQueen = QueenAttack.Create({blackQueenX},{blackQueenY});"); - assert.AppendLine(Assertion.Boolean((bool)method.Data.Expected, "QueenAttack.CanAttack(whiteQueen, blackQueen)")); + assert.AppendLine(Render.Assert.Boolean((bool)method.Data.Expected, "QueenAttack.CanAttack(whiteQueen, blackQueen)")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index eabd46048f..83a0a7616a 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -63,7 +64,7 @@ private static string RenderAssert(TestMethod method) { var x = input["x"].ToString(); var r = new RationalNumber((int[])input["r"]); - var e = ValueFormatter.Format(method.Data.Expected); + var e = Render.Object(method.Data.Expected); var p = Precision(e); assertCodeLine = "Assert.Equal(" + $"{e}, {x}.{operationName}(new RationalNumber({r.Numerator}, {r.Denominator})), {p});"; } diff --git a/generators/Exercises/Generators/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs index bc9667740b..9ae2e1198a 100644 --- a/generators/Exercises/Generators/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using System.Text; -using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -46,7 +45,7 @@ private static string RenderAct(TestMethod method) private static string RenderInstructionsAct(TestMethod method) { - var actual = ValueFormatter.Format(method.Data.Input["instructions"]); + var actual = Render.Object(method.Data.Input["instructions"]); return $"sut.Simulate({actual});"; } @@ -61,16 +60,16 @@ private static string RenderAssert(TestMethod method) if (direction != null) { var expectedDirection = GetDirectionEnum(direction); - assert.AppendLine(Assertion.Equal(expectedDirection, "sut.Direction")); + assert.AppendLine(Render.Assert.Equal(expectedDirection, "sut.Direction")); } if (position != null) { - var x = ValueFormatter.Format(position["x"]); - var y = ValueFormatter.Format(position["y"]); + var x = Render.Object(position["x"]); + var y = Render.Object(position["y"]); - assert.AppendLine(Assertion.Equal(x, "sut.Coordinate.X")); - assert.AppendLine(Assertion.Equal(y, "sut.Coordinate.Y")); + assert.AppendLine(Render.Assert.Equal(x, "sut.Coordinate.X")); + assert.AppendLine(Render.Assert.Equal(y, "sut.Coordinate.Y")); } return assert.ToString(); diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index 668aa9cb17..8430101751 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -23,9 +24,9 @@ private static string RenderAssert(TestMethod method) private static string RenderConsistencyToAssert(TestMethod method) { - var expected = ValueFormatter.Format(method.Data.Expected); + var expected = Render.Object(method.Data.Expected); var actual = $"{method.Data.TestedClass}.Decode({method.Data.TestedClass}.Encode({expected}))"; - return Assertion.Equal(expected, actual); + return Render.Assert.Equal(expected, actual); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index 8f850721b1..a1dfdbc360 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -30,7 +31,7 @@ protected override void UpdateTestData(TestData data) data.Input["ciphertext"] = new UnescapedValue("sut.Key.Substring(0, 10)"); break; case "cipher.encode": - var plaintext = ValueFormatter.Format(data.Input["plaintext"]); + var plaintext = Render.Object(data.Input["plaintext"]); data.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); data.SetInputParameters("ciphertext"); break; @@ -53,11 +54,11 @@ private static string RenderAssert(TestMethod method) switch (method.Data.Property) { case "new": - var key = ValueFormatter.Format(method.Data.Input["key"]); - return Assertion.Throws($"new SimpleCipher({key})"); + var key = Render.Object(method.Data.Input["key"]); + return Render.Assert.Throws($"new SimpleCipher({key})"); case "key": - var pattern = ValueFormatter.Format(method.Data.Expected["match"]); - return Assertion.Matches(pattern, "sut.Key"); + var pattern = Render.Object(method.Data.Expected["match"]); + return Render.Assert.Matches(pattern, "sut.Key"); default: return method.Assert; } diff --git a/generators/Exercises/Generators/Sublist.cs b/generators/Exercises/Generators/Sublist.cs index 88d61ea6df..b73f86fdb6 100644 --- a/generators/Exercises/Generators/Sublist.cs +++ b/generators/Exercises/Generators/Sublist.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Humanizer; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Exercises/Generators/Tournament.cs b/generators/Exercises/Generators/Tournament.cs index d54c672cfe..39cf63b5f6 100644 --- a/generators/Exercises/Generators/Tournament.cs +++ b/generators/Exercises/Generators/Tournament.cs @@ -3,6 +3,7 @@ using System.IO; using System.Text; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -30,7 +31,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(); } - private static string RenderAssert() => Assertion.Equal("expected", "RunTally(rows)"); + private static string RenderAssert() => Render.Assert.Equal("expected", "RunTally(rows)"); protected override void UpdateTestClass(TestClass @class) { diff --git a/generators/Exercises/Generators/Transpose.cs b/generators/Exercises/Generators/Transpose.cs index 0e8134dabd..07b78944bc 100644 --- a/generators/Exercises/Generators/Transpose.cs +++ b/generators/Exercises/Generators/Transpose.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/TwelveDays.cs b/generators/Exercises/Generators/TwelveDays.cs index 3ff814755c..e6be70791d 100644 --- a/generators/Exercises/Generators/TwelveDays.cs +++ b/generators/Exercises/Generators/TwelveDays.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index bf417af41e..71921b4e8b 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -1,6 +1,6 @@ using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Rendering; using Humanizer; namespace Exercism.CSharp.Exercises.Generators @@ -27,12 +27,12 @@ protected override void UpdateTestMethod(TestMethod method) private static string RenderAssert(TestMethod method) { var assert = new StringBuilder(); - assert.AppendLine(Assertion.Equal(method.Data.Expected["moves"].ToString(), "result.Moves")); - assert.AppendLine(Assertion.Equal(method.Data.Expected["otherBucket"].ToString(), "result.OtherBucket")); + assert.AppendLine(Render.Assert.Equal(method.Data.Expected["moves"].ToString(), "result.Moves")); + assert.AppendLine(Render.Assert.Equal(method.Data.Expected["otherBucket"].ToString(), "result.OtherBucket")); var goalBucket = (string) method.Data.Expected["goalBucket"]; var expected = $"Bucket.{goalBucket.Humanize()}"; - assert.AppendLine(Assertion.Equal(expected, "result.GoalBucket")); + assert.AppendLine(Render.Assert.Equal(expected, "result.GoalBucket")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/VariableLengthQuantity.cs b/generators/Exercises/Generators/VariableLengthQuantity.cs index 2c22ec5743..da75e0ad30 100644 --- a/generators/Exercises/Generators/VariableLengthQuantity.cs +++ b/generators/Exercises/Generators/VariableLengthQuantity.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 02c86e2e99..7d0ed7371c 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -48,19 +49,19 @@ private string RenderAssert() private static string RenderAssertForSearchWord(string word, dynamic expected) { return expected == null - ? Assertion.Null($"expected[\"{word}\"]") - : Assertion.Equal($"expected[\"{word}\"]", $"actual[\"{word}\"]"); + ? Render.Assert.Null($"expected[\"{word}\"]") + : Render.Assert.Equal($"expected[\"{word}\"]", $"actual[\"{word}\"]"); } private static string FormatPosition(dynamic position) { return position == null ? "null" : - ValueFormatter.Format((FormatCoordinate(position["start"]), FormatCoordinate(position["end"]))); + Render.Object((FormatCoordinate(position["start"]), FormatCoordinate(position["end"]))); } private static string FormatCoordinate(dynamic coordinate) - => ValueFormatter.Format((coordinate["column"], coordinate["row"])); + => Render.Object((coordinate["column"], coordinate["row"])); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/Yacht.cs b/generators/Exercises/Generators/Yacht.cs index 09e11c75fc..83227d1129 100644 --- a/generators/Exercises/Generators/Yacht.cs +++ b/generators/Exercises/Generators/Yacht.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Humanizer; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Exercises/Generators/ZebraPuzzle.cs b/generators/Exercises/Generators/ZebraPuzzle.cs index f1663a02be..62ddd79ee8 100644 --- a/generators/Exercises/Generators/ZebraPuzzle.cs +++ b/generators/Exercises/Generators/ZebraPuzzle.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Humanizer; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index 83eb9887c7..4719225e2b 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -2,6 +2,7 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Humanizer; namespace Exercism.CSharp.Exercises.Generators @@ -31,12 +32,12 @@ private static string RenderAssert(TestMethod method) var expected = RenderExpected(method.Data.Expected); if (expected == null) { - return Assertion.Null("actual"); + return Render.Assert.Null("actual"); } var assert = new StringBuilder(); assert.AppendLine($"var expected = {expected};"); - assert.AppendLine(Assertion.Equal("expected", "actual")); + assert.AppendLine(Render.Assert.Equal("expected", "actual")); return assert.ToString(); } diff --git a/generators/Generators.csproj b/generators/Generators.csproj index 9dd54a4cf5..a56c06b6bb 100644 --- a/generators/Generators.csproj +++ b/generators/Generators.csproj @@ -14,6 +14,6 @@ - + \ No newline at end of file diff --git a/generators/Output/FormattingExtensions.cs b/generators/Output/Rendering/FormattingExtensions.cs similarity index 94% rename from generators/Output/FormattingExtensions.cs rename to generators/Output/Rendering/FormattingExtensions.cs index 121d71f222..588104fe43 100644 --- a/generators/Output/FormattingExtensions.cs +++ b/generators/Output/Rendering/FormattingExtensions.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -namespace Exercism.CSharp.Output +namespace Exercism.CSharp.Output.Rendering { public static class FormattingExtensions { diff --git a/generators/Output/Templates/IndentFilter.cs b/generators/Output/Rendering/IndentFilter.cs similarity index 88% rename from generators/Output/Templates/IndentFilter.cs rename to generators/Output/Rendering/IndentFilter.cs index f6a601f9df..812006b020 100644 --- a/generators/Output/Templates/IndentFilter.cs +++ b/generators/Output/Rendering/IndentFilter.cs @@ -1,7 +1,7 @@ using System; using System.Linq; -namespace Exercism.CSharp.Output.Templates +namespace Exercism.CSharp.Output.Rendering { public static class IndentFilter { diff --git a/generators/Output/MultiLineString.cs b/generators/Output/Rendering/MultiLineString.cs similarity index 89% rename from generators/Output/MultiLineString.cs rename to generators/Output/Rendering/MultiLineString.cs index a0addb5260..81094a0fd0 100644 --- a/generators/Output/MultiLineString.cs +++ b/generators/Output/Rendering/MultiLineString.cs @@ -1,7 +1,7 @@ using System; using DotLiquid; -namespace Exercism.CSharp.Output +namespace Exercism.CSharp.Output.Rendering { public class MultiLineString : ILiquidizable { diff --git a/generators/Output/ValueFormatter.cs b/generators/Output/Rendering/Render.cs similarity index 60% rename from generators/Output/ValueFormatter.cs rename to generators/Output/Rendering/Render.cs index 24934de1eb..4670d9bf6f 100644 --- a/generators/Output/ValueFormatter.cs +++ b/generators/Output/Rendering/Render.cs @@ -5,36 +5,38 @@ using Exercism.CSharp.Helpers; using Newtonsoft.Json.Linq; -namespace Exercism.CSharp.Output +namespace Exercism.CSharp.Output.Rendering { - public static class ValueFormatter - { - public static string Format(object val) + public static class Render + { + public static readonly RenderAssert Assert = new RenderAssert(); + + public static string Object(object val) { switch (val) { - case string str: return str.Format(); - case MultiLineString multiLineString: return multiLineString.ToString().Format(); - case double dbl: return dbl.Format(); - case float flt: return flt.Format(); - case ulong ulng: return ulng.Format(); - case char c: return c.Format(); - case Enum enumeration: return enumeration.Format(); - case Tuple tuple: return tuple.Format(); - case List ints: return ints.Format(); - case List objects: return objects.Format(); - case IEnumerable ints: return ints.Format(); - case IEnumerable strings: return strings.Format(); - case IEnumerable unescapedValues when unescapedValues.Any(): return unescapedValues.Format(); - case IDictionary dict: return dict.Format(); - case IDictionary dict: return dict.Format(); - case IDictionary dict: return dict.Format(); - case IDictionary dict: return dict.Format(); - case JArray jArray: return jArray.Format(); - case int[,] multidimensionalArray: return multidimensionalArray.Format(); - case IEnumerable> tuples: return tuples.Format(); - case IEnumerable> tuples: return tuples.Format(); - case IEnumerable objects: return objects.Format(); + case string str: return str.Object(); + case MultiLineString multiLineString: return multiLineString.ToString().Object(); + case double dbl: return dbl.Object(); + case float flt: return flt.Object(); + case ulong ulng: return ulng.Object(); + case char c: return c.Object(); + case Enum enumeration: return enumeration.Object(); + case Tuple tuple: return tuple.Object(); + case List ints: return ints.Object(); + case List objects: return objects.Object(); + case IEnumerable ints: return ints.Object(); + case IEnumerable strings: return strings.Object(); + case IEnumerable unescapedValues when unescapedValues.Any(): return unescapedValues.Object(); + case IDictionary dict: return dict.Object(); + case IDictionary dict: return dict.Object(); + case IDictionary dict: return dict.Object(); + case IDictionary dict: return dict.Object(); + case JArray jArray: return jArray.Object(); + case int[,] multidimensionalArray: return multidimensionalArray.Object(); + case IEnumerable> tuples: return tuples.Object(); + case IEnumerable> tuples: return tuples.Object(); + case IEnumerable objects: return objects.Object(); default: return val?.ToString(); } } @@ -56,75 +58,75 @@ public static IEnumerable FormatVariable(object val, string name) return new[] { $"var {name} = Array.Empty();" }; } - return FormatMultiLineEnumerable(strings.Select((str, i) => str.Format() + (i < strings.Count() - 1 ? "," : "")), name, "new[]"); + return FormatMultiLineEnumerable(strings.Select((str, i) => str.Object() + (i < strings.Count() - 1 ? "," : "")), name, "new[]"); case IDictionary dict: - return FormatMultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Format(key)}] = {Format(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); + return FormatMultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Object(key)}] = {Object(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); case IDictionary dict: - return FormatMultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Format(key)}] = {Format(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); + return FormatMultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Object(key)}] = {Object(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); case IDictionary dict: - return FormatMultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Format(key)}] = {Format(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); + return FormatMultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Object(key)}] = {Object(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); case IEnumerable> tuples: - return new[] { tuples.Format() }; + return new[] { tuples.Object() }; default: - return new[] { $"var {name} = {Format(val)};" }; + return new[] { $"var {name} = {Object(val)};" }; } } - private static string Format(this string s) => s.EscapeSpecialCharacters().Quote(); + private static string Object(this string s) => s.EscapeSpecialCharacters().Quote(); - private static string Format(this char c) => $"'{c}'"; + private static string Object(this char c) => $"'{c}'"; - private static string Format(this double dbl) => dbl.ToString(CultureInfo.InvariantCulture); + private static string Object(this double dbl) => dbl.ToString(CultureInfo.InvariantCulture); - private static string Format(this float flt) => flt.ToString(CultureInfo.InvariantCulture); + private static string Object(this float flt) => flt.ToString(CultureInfo.InvariantCulture); - private static string Format(this int i) => i.ToString(CultureInfo.InvariantCulture); + private static string Object(this int i) => i.ToString(CultureInfo.InvariantCulture); - private static string Format(this ulong ulng) => $"{ulng}UL"; + private static string Object(this ulong ulng) => $"{ulng}UL"; - private static string Format(this Enum enumeration) => + private static string Object(this Enum enumeration) => $"{enumeration.GetType().Name}.{enumeration}"; - private static string Format(this Tuple tuple) => + private static string Object(this Tuple tuple) => $"Tuple.Create({tuple.Item1}, {tuple.Item2})"; - private static string Format(this IEnumerable ints) => ints.Any() ? + private static string Object(this IEnumerable ints) => ints.Any() ? $"new[] {{ {string.Join(", ", ints)} }}" : "Array.Empty()"; - private static string Format(this IEnumerable strings) => - strings.Any() ? $"new[] {{ {string.Join(", ", strings.Select(Format))} }}" : "Array.Empty()"; + private static string Object(this IEnumerable strings) => + strings.Any() ? $"new[] {{ {string.Join(", ", strings.Select(Object))} }}" : "Array.Empty()"; - private static string Format(this IEnumerable objects) => - objects.Any() ? $"new[] {{ {string.Join(", ", objects.Select(Format))} }}" : "Array.Empty()"; + private static string Object(this IEnumerable objects) => + objects.Any() ? $"new[] {{ {string.Join(", ", objects.Select(Object))} }}" : "Array.Empty()"; - private static string Format(this List ints) => - ints.Any() ? $"new List {{ {string.Join(", ", ints.Select(Format))} }}" : "new List()"; + private static string Object(this List ints) => + ints.Any() ? $"new List {{ {string.Join(", ", ints.Select(Object))} }}" : "new List()"; - private static string Format(this List objects) => - objects.Any() ? $"new List {{ {string.Join(", ", objects.Select(Format))} }}" : "new List()"; + private static string Object(this List objects) => + objects.Any() ? $"new List {{ {string.Join(", ", objects.Select(Object))} }}" : "new List()"; - private static string Format(this IEnumerable unescapedValues) => - $"new[] {{ {string.Join(", ", unescapedValues.Select(Format))} }}"; + private static string Object(this IEnumerable unescapedValues) => + $"new[] {{ {string.Join(", ", unescapedValues.Select(Object))} }}"; - private static string Format(this IEnumerable> tuples) => tuples.Any() ? + private static string Object(this IEnumerable> tuples) => tuples.Any() ? $"new[] {{ {string.Join(", ", tuples)} }}" : "Array.Empty>()"; - private static string Format(this IDictionary dict) => - string.Join(", ", dict.Values.Select(Format)); + private static string Object(this IDictionary dict) => + string.Join(", ", dict.Values.Select(Object)); - private static string Format(this IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Format(key)}] = {Format(dict[key])}"))} }}"; + private static string Object(this IDictionary dict) => + $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}"; - private static string Format(this IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Format(key)}] = {Format(dict[key])}"))} }}"; + private static string Object(this IDictionary dict) => + $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}"; - private static string Format(this IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Format(key)}] = {Format(dict[key])}"))} }}"; + private static string Object(this IDictionary dict) => + $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}"; - private static string Format(this JArray jArray) => - $"new[] {{ {string.Join(", ", jArray.Select(Format))} }}"; + private static string Object(this JArray jArray) => + $"new[] {{ {string.Join(", ", jArray.Select(Object))} }}"; - private static string Format(this int[,] multidimensionalArray) + private static string Object(this int[,] multidimensionalArray) { IEnumerable SliceRow(T[,] array, int row) { @@ -139,8 +141,8 @@ IEnumerable SliceRow(T[,] array, int row) : "new int[,] { }"; } - private static string Format(this IEnumerable> tuples) => - $"new[] {{ {string.Join(", ", tuples.Select(Format))} }}"; + private static string Object(this IEnumerable> tuples) => + $"new[] {{ {string.Join(", ", tuples.Select(Object))} }}"; private static string ToNestedArray(this IEnumerable enumerable) => enumerable.Any() ? $"{{ {string.Join(", ", enumerable)} }}" : string.Empty; @@ -150,8 +152,8 @@ private static IEnumerable FormatMultiLineString(string name, string str var strings = str.Split('\n'); var formattedStrings = strings .Select((t, i) => i < strings.Length - 1 - ? $"{Format(t + "\n")} +" - : $"{Format(t)}"); + ? $"{Object(t + "\n")} +" + : $"{Object(t)}"); return FormatMultiLineVariable(formattedStrings, name); } diff --git a/generators/Output/Assertion.cs b/generators/Output/Rendering/RenderAssert.cs similarity index 50% rename from generators/Output/Assertion.cs rename to generators/Output/Rendering/RenderAssert.cs index 69a63fdf61..81d18951bb 100644 --- a/generators/Output/Assertion.cs +++ b/generators/Output/Rendering/RenderAssert.cs @@ -1,38 +1,37 @@ using System; -using Exercism.CSharp.Output.Templates; -namespace Exercism.CSharp.Output +namespace Exercism.CSharp.Output.Rendering { - public static class Assertion + public class RenderAssert { - public static string Null(string actual) + public string Null(string actual) => Render("AssertNull", new { actual }); - public static string Empty(string expected, string actual) + public string Empty(string expected, string actual) => Render("AssertEmpty", new { expected, actual }); - public static string Equal(string expected, string actual) + public string Equal(string expected, string actual) => Render("AssertEqual", new { expected, actual }); - public static string EqualWithin(string expected, string actual, int precision) + public string EqualWithin(string expected, string actual, int precision) => Render("AssertEqualWithin", new { expected, actual, precision }); - public static string NotEqual(string expected, string actual) + public string NotEqual(string expected, string actual) => Render("AssertNotEqual", new { expected, actual }); - public static string Boolean(bool expected, string actual) + public string Boolean(bool expected, string actual) => Render("AssertBoolean", new { expected = expected.ToString(), actual }); - public static string Matches(string expected, string actual) + public string Matches(string expected, string actual) => Render("AssertMatches", new { expected, actual }); - public static string Throws(Type expectedException, string actual) + public string Throws(Type expectedException, string actual) => Render("AssertThrows", new { expected = expectedException.Name, actual }); - public static string Throws(string actual) + public string Throws(string actual) => Throws(typeof(T), actual); private static string Render(string template, object parameters) - => TemplateRenderer.RenderPartial(template, parameters); + => Template.Render(template, parameters); } } \ No newline at end of file diff --git a/generators/Output/Rendering/Template.cs b/generators/Output/Rendering/Template.cs new file mode 100644 index 0000000000..b034381b5d --- /dev/null +++ b/generators/Output/Rendering/Template.cs @@ -0,0 +1,20 @@ +using System.Reflection; +using DotLiquid; +using DotLiquid.FileSystems; + +namespace Exercism.CSharp.Output.Rendering +{ + public static class Template + { + private static readonly string EmbeddedTemplatesNamespace = $"{typeof(Template).Namespace}.Templates"; + + static Template() + { + DotLiquid.Template.RegisterFilter(typeof(IndentFilter)); + DotLiquid.Template.FileSystem = new EmbeddedFileSystem(Assembly.GetEntryAssembly(), EmbeddedTemplatesNamespace); + } + + public static string Render(string template, object parameters) + => DotLiquid.Template.Parse($"{{% include \"{template}\" %}}").Render(Hash.FromAnonymousObject(parameters)); + } +} \ No newline at end of file diff --git a/generators/Output/Templates/_Act.liquid b/generators/Output/Rendering/Templates/_Act.liquid similarity index 100% rename from generators/Output/Templates/_Act.liquid rename to generators/Output/Rendering/Templates/_Act.liquid diff --git a/generators/Output/Templates/_Arrange.liquid b/generators/Output/Rendering/Templates/_Arrange.liquid similarity index 100% rename from generators/Output/Templates/_Arrange.liquid rename to generators/Output/Rendering/Templates/_Arrange.liquid diff --git a/generators/Output/Templates/_AssertBoolean.liquid b/generators/Output/Rendering/Templates/_AssertBoolean.liquid similarity index 100% rename from generators/Output/Templates/_AssertBoolean.liquid rename to generators/Output/Rendering/Templates/_AssertBoolean.liquid diff --git a/generators/Output/Templates/_AssertEmpty.liquid b/generators/Output/Rendering/Templates/_AssertEmpty.liquid similarity index 100% rename from generators/Output/Templates/_AssertEmpty.liquid rename to generators/Output/Rendering/Templates/_AssertEmpty.liquid diff --git a/generators/Output/Templates/_AssertEqual.liquid b/generators/Output/Rendering/Templates/_AssertEqual.liquid similarity index 100% rename from generators/Output/Templates/_AssertEqual.liquid rename to generators/Output/Rendering/Templates/_AssertEqual.liquid diff --git a/generators/Output/Templates/_AssertEqualWithin.liquid b/generators/Output/Rendering/Templates/_AssertEqualWithin.liquid similarity index 100% rename from generators/Output/Templates/_AssertEqualWithin.liquid rename to generators/Output/Rendering/Templates/_AssertEqualWithin.liquid diff --git a/generators/Output/Templates/_AssertMatches.liquid b/generators/Output/Rendering/Templates/_AssertMatches.liquid similarity index 100% rename from generators/Output/Templates/_AssertMatches.liquid rename to generators/Output/Rendering/Templates/_AssertMatches.liquid diff --git a/generators/Output/Templates/_AssertNotEqual.liquid b/generators/Output/Rendering/Templates/_AssertNotEqual.liquid similarity index 100% rename from generators/Output/Templates/_AssertNotEqual.liquid rename to generators/Output/Rendering/Templates/_AssertNotEqual.liquid diff --git a/generators/Output/Templates/_AssertNull.liquid b/generators/Output/Rendering/Templates/_AssertNull.liquid similarity index 100% rename from generators/Output/Templates/_AssertNull.liquid rename to generators/Output/Rendering/Templates/_AssertNull.liquid diff --git a/generators/Output/Templates/_AssertThrows.liquid b/generators/Output/Rendering/Templates/_AssertThrows.liquid similarity index 100% rename from generators/Output/Templates/_AssertThrows.liquid rename to generators/Output/Rendering/Templates/_AssertThrows.liquid diff --git a/generators/Output/Templates/_TestClass.liquid b/generators/Output/Rendering/Templates/_TestClass.liquid similarity index 100% rename from generators/Output/Templates/_TestClass.liquid rename to generators/Output/Rendering/Templates/_TestClass.liquid diff --git a/generators/Output/Templates/_TestMethod.liquid b/generators/Output/Rendering/Templates/_TestMethod.liquid similarity index 100% rename from generators/Output/Templates/_TestMethod.liquid rename to generators/Output/Rendering/Templates/_TestMethod.liquid diff --git a/generators/Output/UnescapedValue.cs b/generators/Output/Rendering/UnescapedValue.cs similarity index 87% rename from generators/Output/UnescapedValue.cs rename to generators/Output/Rendering/UnescapedValue.cs index 666b6cfd40..864c491752 100644 --- a/generators/Output/UnescapedValue.cs +++ b/generators/Output/Rendering/UnescapedValue.cs @@ -1,6 +1,6 @@ using DotLiquid; -namespace Exercism.CSharp.Output +namespace Exercism.CSharp.Output.Rendering { public class UnescapedValue : ILiquidizable { diff --git a/generators/Output/Templates/TemplateRenderer.cs b/generators/Output/Templates/TemplateRenderer.cs deleted file mode 100644 index 2742533724..0000000000 --- a/generators/Output/Templates/TemplateRenderer.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.Reflection; -using DotLiquid; -using DotLiquid.FileSystems; - -namespace Exercism.CSharp.Output.Templates -{ - public static class TemplateRenderer - { - private static readonly string EmbeddedTemplatesNamespace = typeof(TemplateRenderer).Namespace; - - static TemplateRenderer() - { - Template.RegisterFilter(typeof(IndentFilter)); - Template.FileSystem = new EmbeddedFileSystem(Assembly.GetEntryAssembly(), EmbeddedTemplatesNamespace); - } - - public static string RenderInline(string template, object parameters) - => Template.Parse(template).Render(Hash.FromAnonymousObject(parameters)); - - public static string RenderPartial(string template, object parameters) - => Template.Parse($"{{% include \"{template}\" %}}").Render(Hash.FromAnonymousObject(parameters)); - } -} \ No newline at end of file diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index 503051909a..1c690d8a94 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -1,5 +1,5 @@ using System.Collections.Generic; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Output { @@ -14,6 +14,6 @@ public class TestClass public ISet Namespaces { get; set; } public bool IsDisposable { get; set; } - public string Render() => TemplateRenderer.RenderPartial(TemplateName, new { ClassName, CanonicalDataVersion, Methods, Namespaces, IsDisposable }); + public string Render() => Template.Render(TemplateName, new { ClassName, CanonicalDataVersion, Methods, Namespaces, IsDisposable }); } } \ No newline at end of file diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index b079723d7f..e7b60dd10a 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -3,7 +3,7 @@ using System.Linq; using Exercism.CSharp.Exercises; using Exercism.CSharp.Helpers; -using Exercism.CSharp.Output.Templates; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Output { @@ -39,21 +39,21 @@ public string Render() Act = Act ?? RenderAct(); Assert = Assert ?? RenderAssert(); - return TemplateRenderer.RenderPartial(TemplateName, new { Name = Data.TestMethod, Data.Skip, Arrange, Act, Assert }); + return Template.Render(TemplateName, new { Name = Data.TestMethod, Data.Skip, Arrange, Act, Assert }); } public string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; - public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : ValueFormatter.Format(Data.Expected); + public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : Rendering.Render.Object(Data.Expected); - private string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(Input); - private string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : ValueFormatter.Format(ConstructorInput); + private string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : Rendering.Render.Object(Input); + private string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : Rendering.Render.Object(ConstructorInput); private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); - private IEnumerable InputVariablesDeclaration => ValueFormatter.FormatVariables(Input); - private IEnumerable ExpectedVariableDeclaration => ValueFormatter.FormatVariable(Data.Expected, ExpectedVariableName); - private IEnumerable ConstructorVariablesDeclaration => ValueFormatter.FormatVariables(ConstructorInput); + private IEnumerable InputVariablesDeclaration => Rendering.Render.FormatVariables(Input); + private IEnumerable ExpectedVariableDeclaration => Rendering.Render.FormatVariable(Data.Expected, ExpectedVariableName); + private IEnumerable ConstructorVariablesDeclaration => Rendering.Render.FormatVariables(ConstructorInput); private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {Data.TestedClass}({ConstructorParameters});" }; private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; @@ -101,10 +101,10 @@ public string TestedMethodInvocation } private string RenderArrange() - => TemplateRenderer.RenderPartial(ArrangeTemplateName, ArrangeTemplateParameters); + => Template.Render(ArrangeTemplateName, ArrangeTemplateParameters); private string RenderAct() - => TemplateRenderer.RenderPartial(ActTemplateName, ActTemplateParameters); + => Template.Render(ActTemplateName, ActTemplateParameters); protected abstract string RenderAssert(); } diff --git a/generators/Output/TestMethodWithBooleanAssertion.cs b/generators/Output/TestMethodWithBooleanAssertion.cs index b2d77f6c1e..8ccb59febe 100644 --- a/generators/Output/TestMethodWithBooleanAssertion.cs +++ b/generators/Output/TestMethodWithBooleanAssertion.cs @@ -8,6 +8,6 @@ public TestMethodWithBooleanAssertion(TestData data) : base(data) { } - protected override string RenderAssert() => Assertion.Boolean(Convert.ToBoolean(Data.Expected), TestedValue); + protected override string RenderAssert() => Rendering.Render.Assert.Boolean(Convert.ToBoolean(Data.Expected), TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEmptyAssertion.cs b/generators/Output/TestMethodWithEmptyAssertion.cs index da5ae57a52..8a85d12dd6 100644 --- a/generators/Output/TestMethodWithEmptyAssertion.cs +++ b/generators/Output/TestMethodWithEmptyAssertion.cs @@ -7,6 +7,6 @@ public TestMethodWithEmptyAssertion(TestData data): base(data) Data.UseVariableForExpected = false; } - protected override string RenderAssert() => Assertion.Empty(ExpectedParameter, TestedValue); + protected override string RenderAssert() => Rendering.Render.Assert.Empty(ExpectedParameter, TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEqualityAssertion.cs b/generators/Output/TestMethodWithEqualityAssertion.cs index 9f348fd173..d99acf5794 100644 --- a/generators/Output/TestMethodWithEqualityAssertion.cs +++ b/generators/Output/TestMethodWithEqualityAssertion.cs @@ -6,6 +6,6 @@ public TestMethodWithEqualityAssertion(TestData data) : base(data) { } - protected override string RenderAssert() => Assertion.Equal(ExpectedParameter, TestedValue); + protected override string RenderAssert() => Rendering.Render.Assert.Equal(ExpectedParameter, TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithExceptionAssertion.cs b/generators/Output/TestMethodWithExceptionAssertion.cs index 4923ad6d4e..681f2418b2 100644 --- a/generators/Output/TestMethodWithExceptionAssertion.cs +++ b/generators/Output/TestMethodWithExceptionAssertion.cs @@ -8,6 +8,6 @@ public TestMethodWithExceptionAssertion(TestData data) : base(data) Data.UseVariableForTested = false; } - protected override string RenderAssert() => Assertion.Throws(Data.ExceptionThrown, TestedValue); + protected override string RenderAssert() => Rendering.Render.Assert.Throws(Data.ExceptionThrown, TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithNullAssertion.cs b/generators/Output/TestMethodWithNullAssertion.cs index 37cbcdeec7..3eda1243e9 100644 --- a/generators/Output/TestMethodWithNullAssertion.cs +++ b/generators/Output/TestMethodWithNullAssertion.cs @@ -6,6 +6,6 @@ public TestMethodWithNullAssertion(TestData data) : base(data) { } - protected override string RenderAssert() => Assertion.Null(TestedValue); + protected override string RenderAssert() => Rendering.Render.Assert.Null(TestedValue); } } \ No newline at end of file From cb0d78ca0cb266c347f480951c6fca5c8dfc4de4 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 30 Jun 2018 10:46:25 +0200 Subject: [PATCH 51/97] generators: Add enum rendering helper --- generators/Exercises/Generators/Connect.cs | 6 +++--- generators/Exercises/Generators/GoCounting.cs | 6 ++---- generators/Exercises/Generators/KindergartenGarden.cs | 3 +-- generators/Exercises/Generators/Meetup.cs | 7 ++----- generators/Exercises/Generators/PerfectNumbers.cs | 5 ++--- generators/Exercises/Generators/Sublist.cs | 3 +-- generators/Exercises/Generators/TwoBucket.cs | 10 +++------- generators/Exercises/Generators/Yacht.cs | 5 +---- generators/Exercises/Generators/ZebraPuzzle.cs | 4 +--- generators/Output/Rendering/Render.cs | 4 ++++ 10 files changed, 20 insertions(+), 33 deletions(-) diff --git a/generators/Exercises/Generators/Connect.cs b/generators/Exercises/Generators/Connect.cs index ceb3582c23..c09d10e126 100644 --- a/generators/Exercises/Generators/Connect.cs +++ b/generators/Exercises/Generators/Connect.cs @@ -14,13 +14,13 @@ protected override void UpdateTestData(TestData data) switch (data.Expected) { case "X": - data.Expected = new UnescapedValue("ConnectWinner.Black"); + data.Expected = Render.Enum("ConnectWinner", "Black"); break; case "O": - data.Expected = new UnescapedValue("ConnectWinner.White"); + data.Expected = Render.Enum("ConnectWinner", "White"); break; case "": - data.Expected = new UnescapedValue("ConnectWinner.None"); + data.Expected = Render.Enum("ConnectWinner", "None"); break; } } diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index 9d856bc042..3f58a6977d 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -4,7 +4,6 @@ using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; -using Humanizer; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators @@ -34,7 +33,7 @@ protected override void UpdateTestData(TestData data) { var owner = FormatOwner(data.Expected["owner"]); var territory = FormatTerritory(data.Expected["territory"]); - data.Expected = (new UnescapedValue(owner), territory); + data.Expected = (owner, territory); } } else @@ -81,8 +80,7 @@ private static string RenderAssert(TestMethod method) return assert.ToString(); } - private static string FormatOwner(dynamic owner) - => $"Owner.{(owner as string).ToLowerInvariant().Humanize()}"; + private static UnescapedValue FormatOwner(dynamic owner) => Render.Enum("Owner", owner); private static string FormatTerritory(dynamic territory) => Render.Object((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); diff --git a/generators/Exercises/Generators/KindergartenGarden.cs b/generators/Exercises/Generators/KindergartenGarden.cs index e414286ed0..fec25d4373 100644 --- a/generators/Exercises/Generators/KindergartenGarden.cs +++ b/generators/Exercises/Generators/KindergartenGarden.cs @@ -2,7 +2,6 @@ using System.Linq; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -20,7 +19,7 @@ protected override void UpdateTestData(TestData data) var plants = (IEnumerable)data.Expected; data.Expected = plants - .Select(x => new UnescapedValue($"Plant.{x.Humanize()}")) + .Select(plant => Render.Enum("Plant", plant)) .ToArray(); } } diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index 3d930b7edf..533646e106 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -24,10 +23,8 @@ protected override void UpdateTestData(TestData data) data.Input[ParamYear] = data.Input[ParamYear]; data.Input[ParamMonth] = data.Input[ParamMonth]; - data.Input[ParamWeek] = - new UnescapedValue($"Schedule.{((string)data.Input[ParamWeek]).Transform(To.SentenceCase)}"); - data.Input[ParamDayOfWeek] = - new UnescapedValue($"DayOfWeek.{((string)data.Input[ParamDayOfWeek]).Transform(To.SentenceCase)}"); + data.Input[ParamWeek] = Render.Enum("Schedule", data.Input[ParamWeek]); + data.Input[ParamDayOfWeek] = Render.Enum("DayOfWeek", data.Input[ParamDayOfWeek]); } protected override void UpdateTestMethod(TestMethod method) diff --git a/generators/Exercises/Generators/PerfectNumbers.cs b/generators/Exercises/Generators/PerfectNumbers.cs index 2272d150f4..4a0ba56b94 100644 --- a/generators/Exercises/Generators/PerfectNumbers.cs +++ b/generators/Exercises/Generators/PerfectNumbers.cs @@ -1,7 +1,6 @@ using System; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -9,8 +8,8 @@ public class PerfectNumbers : GeneratorExercise { protected override void UpdateTestData(TestData data) { - if (data.Expected is string classificationType) - data.Expected = new UnescapedValue($"Classification.{classificationType.Transform(To.SentenceCase)}"); + if (data.Expected is string) + data.Expected = Render.Enum("Classification", data.Expected); else data.ExceptionThrown = typeof(ArgumentOutOfRangeException); } diff --git a/generators/Exercises/Generators/Sublist.cs b/generators/Exercises/Generators/Sublist.cs index b73f86fdb6..65cc3247ba 100644 --- a/generators/Exercises/Generators/Sublist.cs +++ b/generators/Exercises/Generators/Sublist.cs @@ -2,7 +2,6 @@ using System.Linq; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -14,7 +13,7 @@ protected override void UpdateTestData(TestData data) data.Input["listTwo"] = InputValues(data.Input["listTwo"] as int[]); data.TestedMethod = "Classify"; - data.Expected = new UnescapedValue($"SublistType.{(data.Expected as string).Dehumanize()}"); + data.Expected = Render.Enum("SublistType", data.Expected); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index 71921b4e8b..d15ac5cdcb 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -1,7 +1,6 @@ using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -11,9 +10,7 @@ protected override void UpdateTestData(TestData data) { data.TestedMethodType = TestedMethodType.Instance; data.SetConstructorInputParameters("bucketOne", "bucketTwo", "startBucket"); - - var startBucket = data.Input["startBucket"]; - data.Input["startBucket"] = new UnescapedValue(startBucket == "two" ? "Bucket.Two" : "Bucket.One"); + data.Input["startBucket"] = Render.Enum("Bucket", data.Input["startBucket"]); } protected override void UpdateTestMethod(TestMethod method) @@ -30,9 +27,8 @@ private static string RenderAssert(TestMethod method) assert.AppendLine(Render.Assert.Equal(method.Data.Expected["moves"].ToString(), "result.Moves")); assert.AppendLine(Render.Assert.Equal(method.Data.Expected["otherBucket"].ToString(), "result.OtherBucket")); - var goalBucket = (string) method.Data.Expected["goalBucket"]; - var expected = $"Bucket.{goalBucket.Humanize()}"; - assert.AppendLine(Render.Assert.Equal(expected, "result.GoalBucket")); + var expected = Render.Enum("Bucket", method.Data.Expected["goalBucket"]); + assert.AppendLine(Render.Assert.Equal(expected.ToString(), "result.GoalBucket")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/Yacht.cs b/generators/Exercises/Generators/Yacht.cs index 83227d1129..080045b0ae 100644 --- a/generators/Exercises/Generators/Yacht.cs +++ b/generators/Exercises/Generators/Yacht.cs @@ -1,6 +1,5 @@ using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -9,9 +8,7 @@ public class Yacht : GeneratorExercise protected override void UpdateTestData(TestData data) { data.TestedClass = "YachtGame"; - var category = data.Input["category"].ToString(); - var formattedCategory = StringDehumanizeExtensions.Dehumanize(category); - data.Input["category"] = new UnescapedValue($"YachtCategory.{formattedCategory}"); + data.Input["category"] = Render.Enum("YachtCategory", data.Input["category"]); } } } diff --git a/generators/Exercises/Generators/ZebraPuzzle.cs b/generators/Exercises/Generators/ZebraPuzzle.cs index 62ddd79ee8..bb307b3cc4 100644 --- a/generators/Exercises/Generators/ZebraPuzzle.cs +++ b/generators/Exercises/Generators/ZebraPuzzle.cs @@ -1,6 +1,5 @@ using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -8,8 +7,7 @@ public class ZebraPuzzle : GeneratorExercise { protected override void UpdateTestData(TestData data) { - var nationality = data.Expected as string; - data.Expected = new UnescapedValue($"Nationality.{nationality.Humanize()}"); + data.Expected = Render.Enum("Nationality", data.Expected); } } } \ No newline at end of file diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 4670d9bf6f..4ec83647ac 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.Linq; using Exercism.CSharp.Helpers; +using Humanizer; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Output.Rendering @@ -10,6 +11,9 @@ namespace Exercism.CSharp.Output.Rendering public static class Render { public static readonly RenderAssert Assert = new RenderAssert(); + + public static UnescapedValue Enum(string enumType, string enumCase) + => new UnescapedValue($"{enumType}.{enumCase.ToLower().Dehumanize()}"); public static string Object(object val) { From 5f1789288354733ba06864b60d04ba3878d1f650 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 30 Jun 2018 11:45:33 +0200 Subject: [PATCH 52/97] generators: Rename Format to Render --- generators/Exercises/GeneratorExercise.cs | 3 + generators/Exercises/Generators/Allergies.cs | 6 +- .../Exercises/Generators/BinarySearchTree.cs | 20 +-- generators/Exercises/Generators/Bowling.cs | 6 +- .../Exercises/Generators/CircularBuffer.cs | 14 +- generators/Exercises/Generators/Clock.cs | 12 +- .../Exercises/Generators/ComplexNumbers.cs | 10 +- generators/Exercises/Generators/CustomSet.cs | 2 +- generators/Exercises/Generators/Dominoes.cs | 5 +- .../Exercises/Generators/FlattenArray.cs | 2 +- generators/Exercises/Generators/Gigasecond.cs | 6 +- generators/Exercises/Generators/GoCounting.cs | 28 ++-- generators/Exercises/Generators/ListOps.cs | 4 +- generators/Exercises/Generators/Meetup.cs | 4 +- .../Exercises/Generators/NucleotideCount.cs | 14 +- generators/Exercises/Generators/OcrNumbers.cs | 2 +- .../Generators/PalindromeProducts.cs | 17 +- generators/Exercises/Generators/Pov.cs | 2 +- .../Exercises/Generators/QueenAttack.cs | 6 +- .../Exercises/Generators/RationalNumbers.cs | 2 +- .../Exercises/Generators/RobotSimulator.cs | 12 +- .../Exercises/Generators/RunLengthEncoding.cs | 6 +- .../Exercises/Generators/SimpleCipher.cs | 6 +- generators/Exercises/Generators/Tournament.cs | 2 +- generators/Exercises/Generators/TwoBucket.cs | 8 +- .../Generators/VariableLengthQuantity.cs | 17 +- generators/Exercises/Generators/WordSearch.cs | 23 +-- generators/Exercises/Generators/Zipper.cs | 6 +- generators/Output/Rendering/Render.cs | 154 ++++++++---------- generators/Output/Rendering/RenderAssert.cs | 40 ++--- ...ttingExtensions.cs => RenderExtensions.cs} | 2 +- generators/Output/Rendering/RenderNumber.cs | 15 ++ generators/Output/Rendering/RenderString.cs | 14 ++ generators/Output/TestMethod.cs | 16 +- .../Output/TestMethodWithBooleanAssertion.cs | 2 +- .../Output/TestMethodWithEmptyAssertion.cs | 2 +- .../Output/TestMethodWithEqualityAssertion.cs | 2 +- .../TestMethodWithExceptionAssertion.cs | 2 +- .../Output/TestMethodWithNullAssertion.cs | 2 +- 39 files changed, 251 insertions(+), 245 deletions(-) rename generators/Output/Rendering/{FormattingExtensions.cs => RenderExtensions.cs} (94%) create mode 100644 generators/Output/Rendering/RenderNumber.cs create mode 100644 generators/Output/Rendering/RenderString.cs diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index 7f8eab7304..a799c7241a 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -4,6 +4,7 @@ using Exercism.CSharp.Helpers; using Exercism.CSharp.Input; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises { @@ -12,6 +13,8 @@ public abstract class GeneratorExercise : Exercise private CanonicalData _canonicalData; private TestData[] _testData; + protected Render Render { get; } = new Render(); + public override string Name => GetType().ToExerciseName(); public void Regenerate(CanonicalData canonicalData) diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index ceff08f034..5e444926c4 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -21,19 +21,19 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { return method.Data.Property == "allergicTo" ? RenderIsAllergicToAssert(method) : method.Assert; } - private static string RenderIsAllergicToAssert(TestMethod method) + private string RenderIsAllergicToAssert(TestMethod method) { var assert = new StringBuilder(); foreach (var allergy in method.Data.Expected) - assert.AppendLine(Render.Assert.Boolean(allergy["result"], $"sut.IsAllergicTo({Render.Object(allergy["substance"])})")); + assert.AppendLine(Render.AssertBoolean(allergy["result"], $"sut.IsAllergicTo({Render.Object(allergy["substance"])})")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 1da5f670e1..b4b39a6d10 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -18,13 +18,6 @@ public ExpectedDataBinaryTree(IReadOnlyDictionary treeNode) public string Value { get; } public ExpectedDataBinaryTree Left { get; } public ExpectedDataBinaryTree Right { get; } - - public IEnumerable TestAsserts(string traverse = "") - { - yield return Render.Assert.Equal(Value, $"tree{traverse}.Value"); - if (Left != null) foreach (var assert in Left.TestAsserts(traverse + ".Left")) yield return assert; - if (Right != null) foreach (var assert in Right.TestAsserts(traverse + ".Right")) yield return assert; - } } public class BinarySearchTree : GeneratorExercise @@ -59,17 +52,24 @@ private string RenderAssert(TestMethod method) if (canonicalDataCase.Expected is Dictionary expected) { var tree = new ExpectedDataBinaryTree(expected); - foreach (var assert in tree.TestAsserts()) + foreach (var assert in TestAsserts(tree)) AddCodeLine(assert); } else { var expectedNumbers = ((string[]) canonicalDataCase.Expected).Select(int.Parse).ToArray(); - var expectedFormatted = Render.Object(expectedNumbers); - AddCodeLine(Render.Assert.Equal(expectedFormatted, "tree.AsEnumerable()")); + var expectedRendered = Render.Object(expectedNumbers); + AddCodeLine(Render.AssertEqual(expectedRendered, "tree.AsEnumerable()")); } return _testFactCodeLines.ToString(); } + + private IEnumerable TestAsserts(ExpectedDataBinaryTree tree, string traverse = "") + { + yield return Render.AssertEqual(tree.Value, $"tree{traverse}.Value"); + if (tree.Left != null) foreach (var assert in TestAsserts(tree.Left, traverse + ".Left")) yield return assert; + if (tree.Right != null) foreach (var assert in TestAsserts(tree.Right, traverse + ".Right")) yield return assert; + } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index 78da943c91..27c95ecac1 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -53,19 +53,19 @@ private static string RenderArrange(TestMethod method) return builder.ToString(); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { if (method.Data.ExceptionThrown != null && method.Data.Input.ContainsKey("roll")) { var actual = Render.Object(method.Data.Input["roll"]); - return Render.Assert.Throws(method.Data.ExceptionThrown, $"sut.Roll({actual})"); + return Render.AssertThrows(method.Data.ExceptionThrown, $"sut.Roll({actual})"); } if (method.Data.ExceptionThrown == null || method.Data.Property != "score") return method.Assert; - return Render.Assert.Throws(method.Data.ExceptionThrown, "sut.Score()"); + return Render.AssertThrows(method.Data.ExceptionThrown, "sut.Score()"); } private static string RenderAct(TestMethod method) diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index 2b5675aeed..a213812a33 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -13,7 +13,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { var assert = new StringBuilder(); assert.AppendLine(RenderSut(method.Data)); @@ -30,7 +30,7 @@ private static string RenderSut(TestData canonicalDataCase) return $"var buffer = new CircularBuffer(capacity: {capacity});"; } - private static string RenderOperation(dynamic operation) + private string RenderOperation(dynamic operation) { switch (operation["operation"]) { @@ -47,18 +47,18 @@ private static string RenderOperation(dynamic operation) } } - private static string RenderReadOperation(dynamic operation) + private string RenderReadOperation(dynamic operation) { return operation["should_succeed"] - ? Render.Assert.Equal(operation["expected"].ToString(), "buffer.Read()") - : Render.Assert.Throws("buffer.Read()"); + ? Render.AssertEqual(operation["expected"].ToString(), "buffer.Read()") + : Render.AssertThrows("buffer.Read()"); } - private static string RenderWriteOperation(dynamic operation) + private string RenderWriteOperation(dynamic operation) { return operation["should_succeed"] ? $"buffer.Write({operation["item"]});" - : Render.Assert.Throws($"buffer.Write({operation["item"]})"); + : Render.AssertThrows($"buffer.Write({operation["item"]})"); } private static string RenderOverwriteOperation(dynamic operation) diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 0889265225..76ad1e4545 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -43,7 +43,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { if (method.Data.Property == PropertyEqual) { @@ -55,16 +55,16 @@ private static string RenderAssert(TestMethod method) : method.Assert; } - private static string RenderConsistencyToAssert(TestMethod method) - => Render.Assert.Equal(method.ExpectedParameter, $"{method.TestedValue}.ToString()"); + private string RenderConsistencyToAssert(TestMethod method) + => Render.AssertEqual(method.ExpectedParameter, $"{method.TestedValue}.ToString()"); - private static string RenderEqualToAssert(TestMethod method) + private string RenderEqualToAssert(TestMethod method) { var expected = method.Data.Input[ParamClock1].ToString(); return method.Data.Expected - ? Render.Assert.Equal(expected, "sut") - : Render.Assert.NotEqual(expected, "sut"); + ? Render.AssertEqual(expected, "sut") + : Render.AssertNotEqual(expected, "sut"); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index 1be3f12d17..d0b9ec633b 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -37,18 +37,18 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { return method.Data.UseVariableForExpected ? RenderComplexNumberAssert(method) : method.Assert; } - private static string RenderComplexNumberAssert(TestMethod method) + private string RenderComplexNumberAssert(TestMethod method) { var assert = new StringBuilder(); - assert.AppendLine(Render.Assert.EqualWithin($"{method.ExpectedParameter}.Real()", $"{method.TestedValue}.Real()", 15)); - assert.AppendLine(Render.Assert.EqualWithin($"{method.ExpectedParameter}.Imaginary()", $"{method.TestedValue}.Imaginary()", 15)); + assert.AppendLine(Render.AssertEqualWithin($"{method.ExpectedParameter}.Real()", $"{method.TestedValue}.Real()", 15)); + assert.AppendLine(Render.AssertEqualWithin($"{method.ExpectedParameter}.Imaginary()", $"{method.TestedValue}.Imaginary()", 15)); return assert.ToString(); } @@ -58,7 +58,7 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(Math).Namespace); } - private static object ConvertToType(dynamic rawValue) + private object ConvertToType(dynamic rawValue) => IsComplexNumber(rawValue) ? new UnescapedValue($"new ComplexNumber({Render.Object(ConvertMathDouble(rawValue[0]))}, {Render.Object(ConvertMathDouble(rawValue[1]))})") : rawValue; diff --git a/generators/Exercises/Generators/CustomSet.cs b/generators/Exercises/Generators/CustomSet.cs index f64b172679..966937419b 100644 --- a/generators/Exercises/Generators/CustomSet.cs +++ b/generators/Exercises/Generators/CustomSet.cs @@ -37,7 +37,7 @@ protected override void UpdateTestData(TestData data) data.Expected = ConvertCustomSet(data.Expected); } - private static dynamic ConvertCustomSet(dynamic value) + private dynamic ConvertCustomSet(dynamic value) { switch (value) { diff --git a/generators/Exercises/Generators/Dominoes.cs b/generators/Exercises/Generators/Dominoes.cs index 4f9a905044..ae19105d8d 100644 --- a/generators/Exercises/Generators/Dominoes.cs +++ b/generators/Exercises/Generators/Dominoes.cs @@ -22,10 +22,7 @@ protected override void UpdateNamespaces(ISet namespaces) private static UnescapedValue ConvertInput(dynamic input) { - var dominoes = (input as JArray).Children(); - - // Manually format array of ints to array of tuples since the ValueFormatter doesn't handle Tuple[] - // Project each jtoken element to an int array, then format to a string that will create a tuple from the 2-element array (via UnescapedValues) + var dominoes = ((JArray)input).Children(); var tuplesStringLiteral = dominoes.Select(s => s.ToObject()).Select(s => $"Tuple.Create({s[0]}, {s[1]})"); return new UnescapedValue($"new Tuple[] {{ {string.Join(", ", tuplesStringLiteral)} }}"); } diff --git a/generators/Exercises/Generators/FlattenArray.cs b/generators/Exercises/Generators/FlattenArray.cs index 5fcbdcb3c4..ed8df0fab8 100644 --- a/generators/Exercises/Generators/FlattenArray.cs +++ b/generators/Exercises/Generators/FlattenArray.cs @@ -12,7 +12,7 @@ protected override void UpdateTestData(TestData data) var stringInput = data.Input["array"].ToString(); - // We skip reformatting of pure int arrays. + // We skip rendering of pure int arrays. if (stringInput.Contains("System.Int32")) return; diff --git a/generators/Exercises/Generators/Gigasecond.cs b/generators/Exercises/Generators/Gigasecond.cs index fa76c1953d..abe6319d39 100644 --- a/generators/Exercises/Generators/Gigasecond.cs +++ b/generators/Exercises/Generators/Gigasecond.cs @@ -10,8 +10,8 @@ public class Gigasecond : GeneratorExercise protected override void UpdateTestData(TestData data) { var input = DateTime.Parse(data.Input["birthdate"].ToString()); - data.Input["birthdate"] = new UnescapedValue(FormatDateTime(input)); - data.Expected = new UnescapedValue(FormatDateTime((DateTime)data.Expected)); + data.Input["birthdate"] = new UnescapedValue(RenderDateTime(input)); + data.Expected = new UnescapedValue(RenderDateTime((DateTime)data.Expected)); } protected override void UpdateNamespaces(ISet namespaces) @@ -19,7 +19,7 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(DateTime).Namespace); } - private static string FormatDateTime(DateTime dateTime) + private static string RenderDateTime(DateTime dateTime) { return dateTime.Hour == 0 && dateTime.Minute == 0 && dateTime.Second == 0 ? $"new DateTime({dateTime.Year}, {dateTime.Month}, {dateTime.Day})" diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index 3f58a6977d..f0e07d5dbe 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -31,8 +31,8 @@ protected override void UpdateTestData(TestData data) } else { - var owner = FormatOwner(data.Expected["owner"]); - var territory = FormatTerritory(data.Expected["territory"]); + var owner = RenderOwner(data.Expected["owner"]); + var territory = RenderTerritory(data.Expected["territory"]); data.Expected = (owner, territory); } } @@ -42,9 +42,9 @@ protected override void UpdateTestData(TestData data) { "new Dictionary[]>", "{", - $" [Owner.Black] = {FormatTerritory(data.Expected["territoryBlack"])},", - $" [Owner.White] = {FormatTerritory(data.Expected["territoryWhite"])},", - $" [Owner.None] = {FormatTerritory(data.Expected["territoryNone"])}", + $" [Owner.Black] = {RenderTerritory(data.Expected["territoryBlack"])},", + $" [Owner.White] = {RenderTerritory(data.Expected["territoryWhite"])},", + $" [Owner.None] = {RenderTerritory(data.Expected["territoryNone"])}", "}" }; @@ -57,7 +57,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { if (method.Data.ExceptionThrown != null) { @@ -67,22 +67,22 @@ private static string RenderAssert(TestMethod method) if (method.Data.Property == "territories") { var territoriesAssert = new StringBuilder(); - territoriesAssert.AppendLine(Render.Assert.Equal("expected.Keys", "actual.Keys")); - territoriesAssert.AppendLine(Render.Assert.Equal("expected[Owner.Black]", "actual[Owner.Black]")); - territoriesAssert.AppendLine(Render.Assert.Equal("expected[Owner.White]", "actual[Owner.White]")); - territoriesAssert.AppendLine(Render.Assert.Equal("expected[Owner.None]", "actual[Owner.None]")); + territoriesAssert.AppendLine(Render.AssertEqual("expected.Keys", "actual.Keys")); + territoriesAssert.AppendLine(Render.AssertEqual("expected[Owner.Black]", "actual[Owner.Black]")); + territoriesAssert.AppendLine(Render.AssertEqual("expected[Owner.White]", "actual[Owner.White]")); + territoriesAssert.AppendLine(Render.AssertEqual("expected[Owner.None]", "actual[Owner.None]")); return territoriesAssert.ToString(); } var assert = new StringBuilder(); - assert.AppendLine(Render.Assert.Equal("expected.Item1", "actual.Item1")); - assert.AppendLine(Render.Assert.Equal("expected.Item2", "actual.Item2")); + assert.AppendLine(Render.AssertEqual("expected.Item1", "actual.Item1")); + assert.AppendLine(Render.AssertEqual("expected.Item2", "actual.Item2")); return assert.ToString(); } - private static UnescapedValue FormatOwner(dynamic owner) => Render.Enum("Owner", owner); + private UnescapedValue RenderOwner(dynamic owner) => Render.Enum("Owner", owner); - private static string FormatTerritory(dynamic territory) + private string RenderTerritory(dynamic territory) => Render.Object((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/ListOps.cs b/generators/Exercises/Generators/ListOps.cs index 0ae0e4ddb6..16372bfff7 100644 --- a/generators/Exercises/Generators/ListOps.cs +++ b/generators/Exercises/Generators/ListOps.cs @@ -70,7 +70,7 @@ private static dynamic ConvertToList(dynamic value) return value; } - private static dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) + private dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) { switch (value) { @@ -86,7 +86,7 @@ private static dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) .Children() .Select(ConvertToList) .Select(Render.Object) - .Select(formattedValue => new UnescapedValue(formattedValue)) + .Select(renderedValue => new UnescapedValue(renderedValue)) .ToList(); return new UnescapedValue(Render.Object(nestedList) diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index 533646e106..0909e73520 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -32,8 +32,8 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) - => Render.Assert.Equal(method.ExpectedParameter, $"{method.TestedValue}.ToString(\"yyyy-MM-dd\")"); + private string RenderAssert(TestMethod method) + => Render.AssertEqual(method.ExpectedParameter, $"{method.TestedValue}.ToString(\"yyyy-MM-dd\")"); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index 13419af8b2..0de3cf6a10 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -31,20 +31,18 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) - { - return method.Data.UseVariableForExpected + private string RenderAssert(TestMethod method) + => method.Data.UseVariableForExpected ? RenderEqualAssert(method) : RenderThrowsAssert(method); - } - private static string RenderEqualAssert(TestMethod method) - => Render.Assert.Equal("expected", $"sut.{method.Data.TestedMethod}"); + private string RenderEqualAssert(TestMethod method) + => Render.AssertEqual("expected", $"sut.{method.Data.TestedMethod}"); - private static string RenderThrowsAssert(TestMethod method) + private string RenderThrowsAssert(TestMethod method) { var strand = Render.Object(method.Data.Input["strand"]); - return Render.Assert.Throws($"new NucleotideCount({strand})"); + return Render.AssertThrows($"new NucleotideCount({strand})"); } } } diff --git a/generators/Exercises/Generators/OcrNumbers.cs b/generators/Exercises/Generators/OcrNumbers.cs index 43e7e43ddd..f9f4eabfbd 100644 --- a/generators/Exercises/Generators/OcrNumbers.cs +++ b/generators/Exercises/Generators/OcrNumbers.cs @@ -17,7 +17,7 @@ protected override void UpdateTestData(TestData data) data.UseVariablesForInput = true; } - private static UnescapedValue ToDigitStringRepresentation(string[] input) + private UnescapedValue ToDigitStringRepresentation(string[] input) { var lines = new StringBuilder(); lines.AppendLine(); diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index d3af8917c7..1eb0212806 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -19,7 +19,7 @@ protected override void UpdateTestData(TestData data) { data.UseVariableForTested = true; data.UseVariableForExpected = true; - data.Expected = (data.Expected["value"], FormatCoordinates(data.Expected["factors"])); + data.Expected = (data.Expected["value"], RenderCoordinates(data.Expected["factors"])); } } @@ -28,7 +28,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { if (method.Data.ExceptionThrown != null) { @@ -36,12 +36,17 @@ private static string RenderAssert(TestMethod method) } var assert = new StringBuilder(); - assert.AppendLine(Render.Assert.Equal("expected.Item1", "actual.Item1")); - assert.AppendLine(Render.Assert.Equal("expected.Item2", "actual.Item2")); + assert.AppendLine(Render.AssertEqual("expected.Item1", "actual.Item1")); + assert.AppendLine(Render.AssertEqual("expected.Item2", "actual.Item2")); return assert.ToString(); } - private static string FormatCoordinates(dynamic coordinates) - => Render.Object((coordinates as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); + private string RenderCoordinates(dynamic coordinates) + => Render.Object((coordinates as JArray) + .Select(RenderCoordinate) + .ToArray()); + + private static (int, int) RenderCoordinate(JToken coordinate) + => (coordinate[0].ToObject(), coordinate[1].ToObject()); } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Pov.cs b/generators/Exercises/Generators/Pov.cs index df214949d5..61b187dff0 100644 --- a/generators/Exercises/Generators/Pov.cs +++ b/generators/Exercises/Generators/Pov.cs @@ -22,7 +22,7 @@ protected override void UpdateTestData(TestData data) } } - private static UnescapedValue RenderTree(dynamic tree) + private UnescapedValue RenderTree(dynamic tree) { if (tree == null) { diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index bf8def32d4..325b0e4b62 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -19,7 +19,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { if (method.Data.Property == "canAttack") return RenderCanAttackAssert(method); @@ -29,7 +29,7 @@ private static string RenderAssert(TestMethod method) : method.Assert; } - private static string RenderCanAttackAssert(TestMethod method) + private string RenderCanAttackAssert(TestMethod method) { var assert = new StringBuilder(); @@ -38,7 +38,7 @@ private static string RenderCanAttackAssert(TestMethod method) assert.AppendLine($"var whiteQueen = QueenAttack.Create({whiteQueenX},{whiteQueenY});"); assert.AppendLine($"var blackQueen = QueenAttack.Create({blackQueenX},{blackQueenY});"); - assert.AppendLine(Render.Assert.Boolean((bool)method.Data.Expected, "QueenAttack.CanAttack(whiteQueen, blackQueen)")); + assert.AppendLine(Render.AssertBoolean((bool)method.Data.Expected, "QueenAttack.CanAttack(whiteQueen, blackQueen)")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index 83a0a7616a..71d805fefb 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -23,7 +23,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { var input = (Dictionary)method.Data.Input; var operationName = char.ToUpper(method.Data.Property[0]) + method.Data.Property.Substring(1); diff --git a/generators/Exercises/Generators/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs index 9ae2e1198a..b498e68ec0 100644 --- a/generators/Exercises/Generators/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -31,7 +31,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAct(TestMethod method) + private string RenderAct(TestMethod method) { switch (method.Data.Property) { @@ -43,13 +43,13 @@ private static string RenderAct(TestMethod method) private static string RenderDefaultAct(TestMethod method) => $"sut.{method.Data.TestedMethod}();"; - private static string RenderInstructionsAct(TestMethod method) + private string RenderInstructionsAct(TestMethod method) { var actual = Render.Object(method.Data.Input["instructions"]); return $"sut.Simulate({actual});"; } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { var expected = method.Data.Expected as Dictionary; expected.TryGetValue("position", out var position); @@ -60,7 +60,7 @@ private static string RenderAssert(TestMethod method) if (direction != null) { var expectedDirection = GetDirectionEnum(direction); - assert.AppendLine(Render.Assert.Equal(expectedDirection, "sut.Direction")); + assert.AppendLine(Render.AssertEqual(expectedDirection, "sut.Direction")); } if (position != null) @@ -68,8 +68,8 @@ private static string RenderAssert(TestMethod method) var x = Render.Object(position["x"]); var y = Render.Object(position["y"]); - assert.AppendLine(Render.Assert.Equal(x, "sut.Coordinate.X")); - assert.AppendLine(Render.Assert.Equal(y, "sut.Coordinate.Y")); + assert.AppendLine(Render.AssertEqual(x, "sut.Coordinate.X")); + assert.AppendLine(Render.AssertEqual(y, "sut.Coordinate.Y")); } return assert.ToString(); diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index 8430101751..4cc28c4413 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -15,18 +15,18 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { return method.Data.Property == "consistency" ? RenderConsistencyToAssert(method) : method.Assert; } - private static string RenderConsistencyToAssert(TestMethod method) + private string RenderConsistencyToAssert(TestMethod method) { var expected = Render.Object(method.Data.Expected); var actual = $"{method.Data.TestedClass}.Decode({method.Data.TestedClass}.Encode({expected}))"; - return Render.Assert.Equal(expected, actual); + return Render.AssertEqual(expected, actual); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index a1dfdbc360..e9cfa1929b 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -49,16 +49,16 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { switch (method.Data.Property) { case "new": var key = Render.Object(method.Data.Input["key"]); - return Render.Assert.Throws($"new SimpleCipher({key})"); + return Render.AssertThrows($"new SimpleCipher({key})"); case "key": var pattern = Render.Object(method.Data.Expected["match"]); - return Render.Assert.Matches(pattern, "sut.Key"); + return Render.AssertMatches(pattern, "sut.Key"); default: return method.Assert; } diff --git a/generators/Exercises/Generators/Tournament.cs b/generators/Exercises/Generators/Tournament.cs index 39cf63b5f6..0700b8878b 100644 --- a/generators/Exercises/Generators/Tournament.cs +++ b/generators/Exercises/Generators/Tournament.cs @@ -31,7 +31,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(); } - private static string RenderAssert() => Render.Assert.Equal("expected", "RunTally(rows)"); + private string RenderAssert() => Render.AssertEqual("expected", "RunTally(rows)"); protected override void UpdateTestClass(TestClass @class) { diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index d15ac5cdcb..2d3dee6d15 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -21,14 +21,14 @@ protected override void UpdateTestMethod(TestMethod method) private static string RenderAct(TestMethod method) => $"var result = {method.TestedMethodInvocation};"; - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { var assert = new StringBuilder(); - assert.AppendLine(Render.Assert.Equal(method.Data.Expected["moves"].ToString(), "result.Moves")); - assert.AppendLine(Render.Assert.Equal(method.Data.Expected["otherBucket"].ToString(), "result.OtherBucket")); + assert.AppendLine(Render.AssertEqual(method.Data.Expected["moves"].ToString(), "result.Moves")); + assert.AppendLine(Render.AssertEqual(method.Data.Expected["otherBucket"].ToString(), "result.OtherBucket")); var expected = Render.Enum("Bucket", method.Data.Expected["goalBucket"]); - assert.AppendLine(Render.Assert.Equal(expected.ToString(), "result.GoalBucket")); + assert.AppendLine(Render.AssertEqual(expected.ToString(), "result.GoalBucket")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/VariableLengthQuantity.cs b/generators/Exercises/Generators/VariableLengthQuantity.cs index da75e0ad30..0c63c62bd2 100644 --- a/generators/Exercises/Generators/VariableLengthQuantity.cs +++ b/generators/Exercises/Generators/VariableLengthQuantity.cs @@ -13,12 +13,12 @@ protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.UseVariablesForInput = true; - data.Input["integers"] = FormatUInt32Array(data.Input["integers"]); + data.Input["integers"] = RenderUInt32Array(data.Input["integers"]); if (data.Expected == null) data.ExceptionThrown = typeof(InvalidOperationException); else - data.Expected = FormatUInt32Array(data.Expected); + data.Expected = RenderUInt32Array(data.Expected); } protected override void UpdateNamespaces(ISet namespaces) @@ -26,15 +26,16 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(Array).Namespace); } - private static dynamic FormatUInt32Array(dynamic input) + private static dynamic RenderUInt32Array(dynamic input) { var numbers = ToUInt32Array(input as IEnumerable); - return numbers.Select(number => new UnescapedValue(string.Format("0x{0:X}u", number))).ToArray(); + return numbers.Select(RenderUInt32Number).ToArray(); } - private static IEnumerable ToUInt32Array(IEnumerable input) - { - return input.Cast().Select(number => Convert.ToUInt32(number.ToString())); - } + private static UnescapedValue RenderUInt32Number(uint number) + => new UnescapedValue(string.Format("0x{0:X}u", number)); + + private static IEnumerable ToUInt32Array(IEnumerable input) + => input.Cast().Select(number => Convert.ToUInt32(number.ToString())); } } \ No newline at end of file diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 7d0ed7371c..2c334234ab 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -29,13 +29,12 @@ protected override void UpdateTestData(TestData data) "{" }; - expected.AddRange(_expectedDictionary.Select((kv, i) => $" [\"{kv.Key}\"] = {FormatPosition(kv.Value)}{(i < _expectedDictionary.Count - 1 ? "," : "")}")); + expected.AddRange(_expectedDictionary.Select((kv, i) => $" [\"{kv.Key}\"] = {RenderPosition(kv.Value)}{(i < _expectedDictionary.Count - 1 ? "," : "")}")); expected.Add("}"); data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } - protected override void UpdateTestMethod(TestMethod method) { method.Assert = RenderAssert(); @@ -46,21 +45,17 @@ private string RenderAssert() .Select(kv => RenderAssertForSearchWord(kv.Key, kv.Value)) .Cast()); - private static string RenderAssertForSearchWord(string word, dynamic expected) - { - return expected == null - ? Render.Assert.Null($"expected[\"{word}\"]") - : Render.Assert.Equal($"expected[\"{word}\"]", $"actual[\"{word}\"]"); - } + private string RenderAssertForSearchWord(string word, dynamic expected) + => expected == null + ? Render.AssertNull($"expected[\"{word}\"]") + : Render.AssertEqual($"expected[\"{word}\"]", $"actual[\"{word}\"]"); - private static string FormatPosition(dynamic position) - { - return position == null + private string RenderPosition(dynamic position) + => position == null ? "null" : - Render.Object((FormatCoordinate(position["start"]), FormatCoordinate(position["end"]))); - } + Render.Object((RenderCoordinate(position["start"]), RenderCoordinate(position["end"]))); - private static string FormatCoordinate(dynamic coordinate) + private string RenderCoordinate(dynamic coordinate) => Render.Object((coordinate["column"], coordinate["row"])); protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index 4719225e2b..a7cf655c65 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -27,17 +27,17 @@ private static string RenderArrange(TestMethod method) return arrange.ToString(); } - private static string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod method) { var expected = RenderExpected(method.Data.Expected); if (expected == null) { - return Render.Assert.Null("actual"); + return Render.AssertNull("actual"); } var assert = new StringBuilder(); assert.AppendLine($"var expected = {expected};"); - assert.AppendLine(Render.Assert.Equal("expected", "actual")); + assert.AppendLine(Render.AssertEqual("expected", "actual")); return assert.ToString(); } diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 4ec83647ac..ab652bf24e 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -8,129 +8,109 @@ namespace Exercism.CSharp.Output.Rendering { - public static class Render + public partial class Render { - public static readonly RenderAssert Assert = new RenderAssert(); - - public static UnescapedValue Enum(string enumType, string enumCase) - => new UnescapedValue($"{enumType}.{enumCase.ToLower().Dehumanize()}"); - - public static string Object(object val) + public string Object(object val) { switch (val) { - case string str: return str.Object(); - case MultiLineString multiLineString: return multiLineString.ToString().Object(); - case double dbl: return dbl.Object(); - case float flt: return flt.Object(); - case ulong ulng: return ulng.Object(); - case char c: return c.Object(); - case Enum enumeration: return enumeration.Object(); - case Tuple tuple: return tuple.Object(); - case List ints: return ints.Object(); - case List objects: return objects.Object(); - case IEnumerable ints: return ints.Object(); - case IEnumerable strings: return strings.Object(); - case IEnumerable unescapedValues when unescapedValues.Any(): return unescapedValues.Object(); - case IDictionary dict: return dict.Object(); - case IDictionary dict: return dict.Object(); - case IDictionary dict: return dict.Object(); - case IDictionary dict: return dict.Object(); - case JArray jArray: return jArray.Object(); - case int[,] multidimensionalArray: return multidimensionalArray.Object(); - case IEnumerable> tuples: return tuples.Object(); - case IEnumerable> tuples: return tuples.Object(); - case IEnumerable objects: return objects.Object(); + case string str: return String(str); + case MultiLineString multiLineString: return String(multiLineString.ToString()); + case double dbl: return Double(dbl); + case int i: return Int(i); + case float flt: return Float(flt); + case ulong ulng: return Ulong(ulng); + case char c: return Char(c); + case Tuple tuple: return Object(tuple); + case List ints: return Object(ints); + case List objects: return Object(objects); + case IEnumerable ints: return Object(ints); + case IEnumerable strings: return Object(strings); + case IEnumerable unescapedValues when unescapedValues.Any(): return Object(unescapedValues); + case IDictionary dict: return Object(dict); + case IDictionary dict: return Object(dict); + case IDictionary dict: return Object(dict); + case IDictionary dict: return Object(dict); + case JArray jArray: return Object(jArray); + case int[,] multidimensionalArray: return Object(multidimensionalArray); + case IEnumerable> tuples: return Object(tuples); + case IEnumerable> tuples: return Object(tuples); + case IEnumerable objects: return Object(objects); default: return val?.ToString(); } } - public static IEnumerable FormatVariables(IDictionary dict) - => dict.Keys.SelectMany(key => FormatVariable(dict[key], key.ToVariableName())).ToArray(); + public IEnumerable Variables(IDictionary dict) + => dict.Keys.SelectMany(key => Variable(dict[key], key.ToVariableName())).ToArray(); - public static IEnumerable FormatVariable(object val, string name) + public IEnumerable Variable(object val, string name) { switch (val) { case string str when str.Contains("\n"): - return FormatMultiLineString(name, str); + return MultiLineString(name, str); case MultiLineString multiLineValue when multiLineValue.ToString().Contains("\n"): - return FormatMultiLineString(name, multiLineValue.ToString()); + return MultiLineString(name, multiLineValue.ToString()); case IEnumerable strings: if (!strings.Any()) { return new[] { $"var {name} = Array.Empty();" }; } - return FormatMultiLineEnumerable(strings.Select((str, i) => str.Object() + (i < strings.Count() - 1 ? "," : "")), name, "new[]"); + return MultiLineEnumerable(strings.Select((str, i) => String(str) + (i < strings.Count() - 1 ? "," : "")), name, "new[]"); case IDictionary dict: - return FormatMultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Object(key)}] = {Object(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); + return MultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Char(key)}] = {Int(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); case IDictionary dict: - return FormatMultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Object(key)}] = {Object(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); + return MultiLineEnumerable(dict.Keys.Select((key, i) => $"[{String(key)}] = {Int(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); case IDictionary dict: - return FormatMultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Object(key)}] = {Object(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); + return MultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Int(key)}] = {Object(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); case IEnumerable> tuples: - return new[] { tuples.Object() }; + return new[] { Object(tuples) }; default: return new[] { $"var {name} = {Object(val)};" }; } } - private static string Object(this string s) => s.EscapeSpecialCharacters().Quote(); - - private static string Object(this char c) => $"'{c}'"; - - private static string Object(this double dbl) => dbl.ToString(CultureInfo.InvariantCulture); - - private static string Object(this float flt) => flt.ToString(CultureInfo.InvariantCulture); - - private static string Object(this int i) => i.ToString(CultureInfo.InvariantCulture); - - private static string Object(this ulong ulng) => $"{ulng}UL"; - - private static string Object(this Enum enumeration) => - $"{enumeration.GetType().Name}.{enumeration}"; - - private static string Object(this Tuple tuple) => + private string Object(Tuple tuple) => $"Tuple.Create({tuple.Item1}, {tuple.Item2})"; - private static string Object(this IEnumerable ints) => ints.Any() ? + private string Object(IEnumerable ints) => ints.Any() ? $"new[] {{ {string.Join(", ", ints)} }}" : "Array.Empty()"; - private static string Object(this IEnumerable strings) => - strings.Any() ? $"new[] {{ {string.Join(", ", strings.Select(Object))} }}" : "Array.Empty()"; + private string Object(IEnumerable strings) => + strings.Any() ? $"new[] {{ {string.Join(", ", strings.Select(String))} }}" : "Array.Empty()"; - private static string Object(this IEnumerable objects) => + private string Object(IEnumerable objects) => objects.Any() ? $"new[] {{ {string.Join(", ", objects.Select(Object))} }}" : "Array.Empty()"; - private static string Object(this List ints) => - ints.Any() ? $"new List {{ {string.Join(", ", ints.Select(Object))} }}" : "new List()"; + private string Object(List ints) => + ints.Any() ? $"new List {{ {string.Join(", ", ints.Select(Int))} }}" : "new List()"; - private static string Object(this List objects) => + private string Object(List objects) => objects.Any() ? $"new List {{ {string.Join(", ", objects.Select(Object))} }}" : "new List()"; - private static string Object(this IEnumerable unescapedValues) => + private string Object(IEnumerable unescapedValues) => $"new[] {{ {string.Join(", ", unescapedValues.Select(Object))} }}"; - private static string Object(this IEnumerable> tuples) => tuples.Any() ? + private string Object(IEnumerable> tuples) => tuples.Any() ? $"new[] {{ {string.Join(", ", tuples)} }}" : "Array.Empty>()"; - private static string Object(this IDictionary dict) => + private string Object(IDictionary dict) => string.Join(", ", dict.Values.Select(Object)); - private static string Object(this IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}"; + private string Object(IDictionary dict) => + $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Char(key)}] = {Int(dict[key])}"))} }}"; - private static string Object(this IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}"; + private string Object(IDictionary dict) => + $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{String(key)}] = {Int(dict[key])}"))} }}"; - private static string Object(this IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}"; + private string Object(IDictionary dict) => + $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Int(key)}] = {Object(dict[key])}"))} }}"; - private static string Object(this JArray jArray) => + private string Object(JArray jArray) => $"new[] {{ {string.Join(", ", jArray.Select(Object))} }}"; - private static string Object(this int[,] multidimensionalArray) + private string Object(int[,] multidimensionalArray) { IEnumerable SliceRow(T[,] array, int row) { @@ -141,34 +121,30 @@ IEnumerable SliceRow(T[,] array, int row) } return multidimensionalArray.GetLength(0) > 0 - ? $"new[,]\r\n{{\r\n {string.Join(",\r\n ", Enumerable.Range(0, multidimensionalArray.GetUpperBound(0) + 1).Select(x => SliceRow(multidimensionalArray, x).ToNestedArray()))}\r\n}}" + ? $"new[,]\r\n{{\r\n {string.Join(",\r\n ", Enumerable.Range(0, multidimensionalArray.GetUpperBound(0) + 1).Select(x => ToNestedArray(SliceRow(multidimensionalArray, x))))}\r\n}}" : "new int[,] { }"; } - private static string Object(this IEnumerable> tuples) => + private string Object(IEnumerable> tuples) => $"new[] {{ {string.Join(", ", tuples.Select(Object))} }}"; - private static string ToNestedArray(this IEnumerable enumerable) => + private string ToNestedArray(IEnumerable enumerable) => enumerable.Any() ? $"{{ {string.Join(", ", enumerable)} }}" : string.Empty; - private static IEnumerable FormatMultiLineString(string name, string str) + private IEnumerable MultiLineString(string name, string str) { var strings = str.Split('\n'); - var formattedStrings = strings - .Select((t, i) => i < strings.Length - 1 - ? $"{Object(t + "\n")} +" - : $"{Object(t)}"); + var renderedStrings = strings.Select((t, i) => i < strings.Length - 1 + ? $"{String(t + "\n")} +" + : $"{String(t)}"); - return FormatMultiLineVariable(formattedStrings, name); + return MultiLineVariable(renderedStrings, name); } - private static IEnumerable FormatMultiLineEnumerable(IEnumerable enumerable, string name, string constructor = null) - => FormatMultiLineVariable(enumerable.Prepend("{").Append("}"), name, constructor); + private IEnumerable MultiLineEnumerable(IEnumerable enumerable, string name, string constructor = null) + => MultiLineVariable(enumerable.Prepend("{").Append("}"), name, constructor); - private static IEnumerable FormatMultiLineVariable(IEnumerable enumerable, string name, string constructor = null) - => enumerable.Select(line => line == "{" || line == "}" ? line : line.Indent()) - .AddTrailingSemicolon() - .Prepend($"var {name} = {constructor}") - .ToArray(); + private IEnumerable MultiLineVariable(IEnumerable enumerable, string name, string constructor = null) + => enumerable.Select(line => line == "{" || line == "}" ? line : line.Indent()).AddTrailingSemicolon().Prepend($"var {name} = {constructor}").ToArray(); } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderAssert.cs b/generators/Output/Rendering/RenderAssert.cs index 81d18951bb..4f857fd52b 100644 --- a/generators/Output/Rendering/RenderAssert.cs +++ b/generators/Output/Rendering/RenderAssert.cs @@ -2,36 +2,36 @@ namespace Exercism.CSharp.Output.Rendering { - public class RenderAssert + public partial class Render { - public string Null(string actual) - => Render("AssertNull", new { actual }); + public string AssertNull(string actual) + => RenderTemplate("AssertNull", new { actual }); - public string Empty(string expected, string actual) - => Render("AssertEmpty", new { expected, actual }); + public string AssertEmpty(string expected, string actual) + => RenderTemplate("AssertEmpty", new { expected, actual }); - public string Equal(string expected, string actual) - => Render("AssertEqual", new { expected, actual }); + public string AssertEqual(string expected, string actual) + => RenderTemplate("AssertEqual", new { expected, actual }); - public string EqualWithin(string expected, string actual, int precision) - => Render("AssertEqualWithin", new { expected, actual, precision }); + public string AssertEqualWithin(string expected, string actual, int precision) + => RenderTemplate("AssertEqualWithin", new { expected, actual, precision }); - public string NotEqual(string expected, string actual) - => Render("AssertNotEqual", new { expected, actual }); + public string AssertNotEqual(string expected, string actual) + => RenderTemplate("AssertNotEqual", new { expected, actual }); - public string Boolean(bool expected, string actual) - => Render("AssertBoolean", new { expected = expected.ToString(), actual }); + public string AssertBoolean(bool expected, string actual) + => RenderTemplate("AssertBoolean", new { expected = expected.ToString(), actual }); - public string Matches(string expected, string actual) - => Render("AssertMatches", new { expected, actual }); + public string AssertMatches(string expected, string actual) + => RenderTemplate("AssertMatches", new { expected, actual }); - public string Throws(Type expectedException, string actual) - => Render("AssertThrows", new { expected = expectedException.Name, actual }); + public string AssertThrows(Type expectedException, string actual) + => RenderTemplate("AssertThrows", new { expected = expectedException.Name, actual }); - public string Throws(string actual) - => Throws(typeof(T), actual); + public string AssertThrows(string actual) + => AssertThrows(typeof(T), actual); - private static string Render(string template, object parameters) + private static string RenderTemplate(string template, object parameters) => Template.Render(template, parameters); } } \ No newline at end of file diff --git a/generators/Output/Rendering/FormattingExtensions.cs b/generators/Output/Rendering/RenderExtensions.cs similarity index 94% rename from generators/Output/Rendering/FormattingExtensions.cs rename to generators/Output/Rendering/RenderExtensions.cs index 588104fe43..4edb689631 100644 --- a/generators/Output/Rendering/FormattingExtensions.cs +++ b/generators/Output/Rendering/RenderExtensions.cs @@ -3,7 +3,7 @@ namespace Exercism.CSharp.Output.Rendering { - public static class FormattingExtensions + public static class RenderExtensions { public static string Indent(this string str, int level = 1) => $"{new string(' ', 4 * level)}{str}"; diff --git a/generators/Output/Rendering/RenderNumber.cs b/generators/Output/Rendering/RenderNumber.cs new file mode 100644 index 0000000000..ff49ed84c0 --- /dev/null +++ b/generators/Output/Rendering/RenderNumber.cs @@ -0,0 +1,15 @@ +using System.Globalization; + +namespace Exercism.CSharp.Output.Rendering +{ + public partial class Render + { + public string Double(double dbl) => dbl.ToString(CultureInfo.InvariantCulture); + + public string Float(float flt) => flt.ToString(CultureInfo.InvariantCulture); + + public string Int(int i) => i.ToString(CultureInfo.InvariantCulture); + + public string Ulong(ulong ulng) => $"{ulng}UL"; + } +} \ No newline at end of file diff --git a/generators/Output/Rendering/RenderString.cs b/generators/Output/Rendering/RenderString.cs new file mode 100644 index 0000000000..b035c37f55 --- /dev/null +++ b/generators/Output/Rendering/RenderString.cs @@ -0,0 +1,14 @@ +using Humanizer; + +namespace Exercism.CSharp.Output.Rendering +{ + public partial class Render + { + public UnescapedValue Enum(string enumType, string enumCase) + => new UnescapedValue($"{enumType}.{enumCase.ToLower().Dehumanize()}"); + + public string String(string s) => s.EscapeSpecialCharacters().Quote(); + + public string Char(char c) => $"'{c}'"; + } +} \ No newline at end of file diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index e7b60dd10a..16cc2dbe74 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -16,6 +16,8 @@ public abstract class TestMethod private const string ArrangeTemplateName = "Arrange"; private const string ActTemplateName = "Act"; + + protected Render Renderer { get; } = new Render(); protected TestMethod(TestData data) => Data = data; @@ -28,7 +30,7 @@ public abstract class TestMethod public string Act { get; set; } public string Arrange { get; set; } public string Assert { get; set; } - + public string Render() { ArrangeTemplateParameters = ArrangeTemplateParameters ?? new { Variables }; @@ -43,17 +45,17 @@ public string Render() } public string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; - public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : Rendering.Render.Object(Data.Expected); + public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : Renderer.Object(Data.Expected); - private string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : Rendering.Render.Object(Input); - private string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : Rendering.Render.Object(ConstructorInput); + private string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : Renderer.Object(Input); + private string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : Renderer.Object(ConstructorInput); private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); - private IEnumerable InputVariablesDeclaration => Rendering.Render.FormatVariables(Input); - private IEnumerable ExpectedVariableDeclaration => Rendering.Render.FormatVariable(Data.Expected, ExpectedVariableName); - private IEnumerable ConstructorVariablesDeclaration => Rendering.Render.FormatVariables(ConstructorInput); + private IEnumerable InputVariablesDeclaration => Renderer.Variables(Input); + private IEnumerable ExpectedVariableDeclaration => Renderer.Variable(Data.Expected, ExpectedVariableName); + private IEnumerable ConstructorVariablesDeclaration => Renderer.Variables(ConstructorInput); private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {Data.TestedClass}({ConstructorParameters});" }; private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; diff --git a/generators/Output/TestMethodWithBooleanAssertion.cs b/generators/Output/TestMethodWithBooleanAssertion.cs index 8ccb59febe..114b82241d 100644 --- a/generators/Output/TestMethodWithBooleanAssertion.cs +++ b/generators/Output/TestMethodWithBooleanAssertion.cs @@ -8,6 +8,6 @@ public TestMethodWithBooleanAssertion(TestData data) : base(data) { } - protected override string RenderAssert() => Rendering.Render.Assert.Boolean(Convert.ToBoolean(Data.Expected), TestedValue); + protected override string RenderAssert() => Renderer.AssertBoolean(Convert.ToBoolean(Data.Expected), TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEmptyAssertion.cs b/generators/Output/TestMethodWithEmptyAssertion.cs index 8a85d12dd6..a10963d792 100644 --- a/generators/Output/TestMethodWithEmptyAssertion.cs +++ b/generators/Output/TestMethodWithEmptyAssertion.cs @@ -7,6 +7,6 @@ public TestMethodWithEmptyAssertion(TestData data): base(data) Data.UseVariableForExpected = false; } - protected override string RenderAssert() => Rendering.Render.Assert.Empty(ExpectedParameter, TestedValue); + protected override string RenderAssert() => Renderer.AssertEmpty(ExpectedParameter, TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithEqualityAssertion.cs b/generators/Output/TestMethodWithEqualityAssertion.cs index d99acf5794..9a5e57078c 100644 --- a/generators/Output/TestMethodWithEqualityAssertion.cs +++ b/generators/Output/TestMethodWithEqualityAssertion.cs @@ -6,6 +6,6 @@ public TestMethodWithEqualityAssertion(TestData data) : base(data) { } - protected override string RenderAssert() => Rendering.Render.Assert.Equal(ExpectedParameter, TestedValue); + protected override string RenderAssert() => Renderer.AssertEqual(ExpectedParameter, TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithExceptionAssertion.cs b/generators/Output/TestMethodWithExceptionAssertion.cs index 681f2418b2..87e7678b5b 100644 --- a/generators/Output/TestMethodWithExceptionAssertion.cs +++ b/generators/Output/TestMethodWithExceptionAssertion.cs @@ -8,6 +8,6 @@ public TestMethodWithExceptionAssertion(TestData data) : base(data) Data.UseVariableForTested = false; } - protected override string RenderAssert() => Rendering.Render.Assert.Throws(Data.ExceptionThrown, TestedValue); + protected override string RenderAssert() => Renderer.AssertThrows(Data.ExceptionThrown, TestedValue); } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithNullAssertion.cs b/generators/Output/TestMethodWithNullAssertion.cs index 3eda1243e9..a78c3131c3 100644 --- a/generators/Output/TestMethodWithNullAssertion.cs +++ b/generators/Output/TestMethodWithNullAssertion.cs @@ -6,6 +6,6 @@ public TestMethodWithNullAssertion(TestData data) : base(data) { } - protected override string RenderAssert() => Rendering.Render.Assert.Null(TestedValue); + protected override string RenderAssert() => Renderer.AssertNull(TestedValue); } } \ No newline at end of file From 07874ba53f408abe34b5fc0ba0729f6dad8e2179 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 30 Jun 2018 11:54:45 +0200 Subject: [PATCH 53/97] generators: Move rendering logic to separate partial classes --- generators/Output/Rendering/Render.cs | 137 ++---------------- generators/Output/Rendering/RenderArray.cs | 53 +++++++ .../Output/Rendering/RenderDictionary.cs | 20 +++ generators/Output/Rendering/RenderList.cs | 16 ++ generators/Output/Rendering/RenderString.cs | 14 +- generators/Output/Rendering/RenderTuple.cs | 12 ++ generators/Output/Rendering/RenderVariable.cs | 54 +++++++ 7 files changed, 183 insertions(+), 123 deletions(-) create mode 100644 generators/Output/Rendering/RenderArray.cs create mode 100644 generators/Output/Rendering/RenderDictionary.cs create mode 100644 generators/Output/Rendering/RenderList.cs create mode 100644 generators/Output/Rendering/RenderTuple.cs create mode 100644 generators/Output/Rendering/RenderVariable.cs diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index ab652bf24e..1bf75d05cf 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -21,130 +21,23 @@ public string Object(object val) case float flt: return Float(flt); case ulong ulng: return Ulong(ulng); case char c: return Char(c); - case Tuple tuple: return Object(tuple); - case List ints: return Object(ints); - case List objects: return Object(objects); - case IEnumerable ints: return Object(ints); - case IEnumerable strings: return Object(strings); - case IEnumerable unescapedValues when unescapedValues.Any(): return Object(unescapedValues); - case IDictionary dict: return Object(dict); - case IDictionary dict: return Object(dict); - case IDictionary dict: return Object(dict); - case IDictionary dict: return Object(dict); - case JArray jArray: return Object(jArray); - case int[,] multidimensionalArray: return Object(multidimensionalArray); - case IEnumerable> tuples: return Object(tuples); - case IEnumerable> tuples: return Object(tuples); - case IEnumerable objects: return Object(objects); + case Tuple tuple: return Tuple(tuple); + case List ints: return List(ints); + case List objects: return List(objects); + case IEnumerable ints: return Array(ints); + case IEnumerable strings: return Array(strings); + case IEnumerable unescapedValues when unescapedValues.Any(): return Array(unescapedValues); + case IDictionary dict: return Dictionary(dict); + case IDictionary dict: return Dictionary(dict); + case IDictionary dict: return Dictionary(dict); + case IDictionary dict: return Dictionary(dict); + case JArray jArray: return Array(jArray); + case int[,] multidimensionalArray: return MultidimensionalArray(multidimensionalArray); + case IEnumerable> tuples: return Array(tuples); + case IEnumerable> tuples: return Array(tuples); + case IEnumerable objects: return Array(objects); default: return val?.ToString(); } } - - public IEnumerable Variables(IDictionary dict) - => dict.Keys.SelectMany(key => Variable(dict[key], key.ToVariableName())).ToArray(); - - public IEnumerable Variable(object val, string name) - { - switch (val) - { - case string str when str.Contains("\n"): - return MultiLineString(name, str); - case MultiLineString multiLineValue when multiLineValue.ToString().Contains("\n"): - return MultiLineString(name, multiLineValue.ToString()); - case IEnumerable strings: - if (!strings.Any()) - { - return new[] { $"var {name} = Array.Empty();" }; - } - - return MultiLineEnumerable(strings.Select((str, i) => String(str) + (i < strings.Count() - 1 ? "," : "")), name, "new[]"); - case IDictionary dict: - return MultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Char(key)}] = {Int(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); - case IDictionary dict: - return MultiLineEnumerable(dict.Keys.Select((key, i) => $"[{String(key)}] = {Int(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); - case IDictionary dict: - return MultiLineEnumerable(dict.Keys.Select((key, i) => $"[{Int(key)}] = {Object(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); - case IEnumerable> tuples: - return new[] { Object(tuples) }; - default: - return new[] { $"var {name} = {Object(val)};" }; - } - } - - private string Object(Tuple tuple) => - $"Tuple.Create({tuple.Item1}, {tuple.Item2})"; - - private string Object(IEnumerable ints) => ints.Any() ? - $"new[] {{ {string.Join(", ", ints)} }}" : "Array.Empty()"; - - private string Object(IEnumerable strings) => - strings.Any() ? $"new[] {{ {string.Join(", ", strings.Select(String))} }}" : "Array.Empty()"; - - private string Object(IEnumerable objects) => - objects.Any() ? $"new[] {{ {string.Join(", ", objects.Select(Object))} }}" : "Array.Empty()"; - - private string Object(List ints) => - ints.Any() ? $"new List {{ {string.Join(", ", ints.Select(Int))} }}" : "new List()"; - - private string Object(List objects) => - objects.Any() ? $"new List {{ {string.Join(", ", objects.Select(Object))} }}" : "new List()"; - - private string Object(IEnumerable unescapedValues) => - $"new[] {{ {string.Join(", ", unescapedValues.Select(Object))} }}"; - - private string Object(IEnumerable> tuples) => tuples.Any() ? - $"new[] {{ {string.Join(", ", tuples)} }}" : "Array.Empty>()"; - - private string Object(IDictionary dict) => - string.Join(", ", dict.Values.Select(Object)); - - private string Object(IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Char(key)}] = {Int(dict[key])}"))} }}"; - - private string Object(IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{String(key)}] = {Int(dict[key])}"))} }}"; - - private string Object(IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Int(key)}] = {Object(dict[key])}"))} }}"; - - private string Object(JArray jArray) => - $"new[] {{ {string.Join(", ", jArray.Select(Object))} }}"; - - private string Object(int[,] multidimensionalArray) - { - IEnumerable SliceRow(T[,] array, int row) - { - for (var i = array.GetLowerBound(1); i <= array.GetUpperBound(1); i++) - { - yield return array[row, i]; - } - } - - return multidimensionalArray.GetLength(0) > 0 - ? $"new[,]\r\n{{\r\n {string.Join(",\r\n ", Enumerable.Range(0, multidimensionalArray.GetUpperBound(0) + 1).Select(x => ToNestedArray(SliceRow(multidimensionalArray, x))))}\r\n}}" - : "new int[,] { }"; - } - - private string Object(IEnumerable> tuples) => - $"new[] {{ {string.Join(", ", tuples.Select(Object))} }}"; - - private string ToNestedArray(IEnumerable enumerable) => - enumerable.Any() ? $"{{ {string.Join(", ", enumerable)} }}" : string.Empty; - - private IEnumerable MultiLineString(string name, string str) - { - var strings = str.Split('\n'); - var renderedStrings = strings.Select((t, i) => i < strings.Length - 1 - ? $"{String(t + "\n")} +" - : $"{String(t)}"); - - return MultiLineVariable(renderedStrings, name); - } - - private IEnumerable MultiLineEnumerable(IEnumerable enumerable, string name, string constructor = null) - => MultiLineVariable(enumerable.Prepend("{").Append("}"), name, constructor); - - private IEnumerable MultiLineVariable(IEnumerable enumerable, string name, string constructor = null) - => enumerable.Select(line => line == "{" || line == "}" ? line : line.Indent()).AddTrailingSemicolon().Prepend($"var {name} = {constructor}").ToArray(); } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs new file mode 100644 index 0000000000..d23080b0a9 --- /dev/null +++ b/generators/Output/Rendering/RenderArray.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Newtonsoft.Json.Linq; + +namespace Exercism.CSharp.Output.Rendering +{ + public partial class Render + { + public string Array(IEnumerable ints) => + ints.Any() ? $"new[] {{ {string.Join(", ", ints)} }}" : "Array.Empty()"; + + public string Array(IEnumerable strings) => + strings.Any() ? $"new[] {{ {string.Join(", ", strings.Select(String))} }}" : "Array.Empty()"; + + public string Array(IEnumerable objects) => + objects.Any() ? $"new[] {{ {string.Join(", ", objects.Select(Object))} }}" : "Array.Empty()"; + + public string Array(JArray jArray) => + $"new[] {{ {string.Join(", ", jArray.Select(Array))} }}"; + + public string Array(IEnumerable unescapedValues) => + $"new[] {{ {string.Join(", ", unescapedValues.Select(Object))} }}"; + + public string Array(IEnumerable> tuples) => + $"new[] {{ {string.Join(", ", tuples.Select(Tuple))} }}"; + + public string Array(IEnumerable> tuples) => tuples.Any() ? + $"new[] {{ {string.Join(", ", tuples)} }}" : "Array.Empty>()"; + + public string MultidimensionalArray(int[,] multidimensionalArray) + { + IEnumerable SliceRow(T[,] array, int row) + { + for (var i = array.GetLowerBound(1); i <= array.GetUpperBound(1); i++) + { + yield return array[row, i]; + } + } + + return multidimensionalArray.GetLength(0) > 0 + ? $"new[,]\r\n{{\r\n {string.Join(",\r\n ", System.Linq.Enumerable.Range(0, multidimensionalArray.GetUpperBound(0) + 1).Select(x => ToNestedArray(SliceRow(multidimensionalArray, x))))}\r\n}}" + : "new int[,] { }"; + } + + public IEnumerable MultiLineEnumerable(IEnumerable enumerable, string name, + string constructor = null) + => MultiLineVariable(enumerable.Prepend("{").Append("}"), name, constructor); + + private string ToNestedArray(IEnumerable enumerable) => + enumerable.Any() ? $"{{ {string.Join(", ", enumerable)} }}" : string.Empty; + } +} \ No newline at end of file diff --git a/generators/Output/Rendering/RenderDictionary.cs b/generators/Output/Rendering/RenderDictionary.cs new file mode 100644 index 0000000000..d18ec34f46 --- /dev/null +++ b/generators/Output/Rendering/RenderDictionary.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Linq; + +namespace Exercism.CSharp.Output.Rendering +{ + public partial class Render + { + public string Dictionary(IDictionary dict) => + string.Join(", ", dict.Values.Select(Object)); + + public string Dictionary(IDictionary dict) => + $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Char(key)}] = {Int(dict[key])}"))} }}"; + + public string Dictionary(IDictionary dict) => + $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{String(key)}] = {Int(dict[key])}"))} }}"; + + public string Dictionary(IDictionary dict) => + $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Int(key)}] = {Array(dict[key])}"))} }}"; + } +} \ No newline at end of file diff --git a/generators/Output/Rendering/RenderList.cs b/generators/Output/Rendering/RenderList.cs new file mode 100644 index 0000000000..39022a4dee --- /dev/null +++ b/generators/Output/Rendering/RenderList.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; +using System.Linq; + +namespace Exercism.CSharp.Output.Rendering +{ + public partial class Render + { + public string List(List ints) => + ints.Any() ? $"new List {{ {string.Join(", ", ints.Select(Int))} }}" : "new List()"; + + public string List(List objects) => + objects.Any() + ? $"new List {{ {string.Join(", ", objects.Select(Object))} }}" + : "new List()"; + } +} \ No newline at end of file diff --git a/generators/Output/Rendering/RenderString.cs b/generators/Output/Rendering/RenderString.cs index b035c37f55..80060a1726 100644 --- a/generators/Output/Rendering/RenderString.cs +++ b/generators/Output/Rendering/RenderString.cs @@ -1,4 +1,6 @@ -using Humanizer; +using System.Collections.Generic; +using System.Linq; +using Humanizer; namespace Exercism.CSharp.Output.Rendering { @@ -10,5 +12,15 @@ public UnescapedValue Enum(string enumType, string enumCase) public string String(string s) => s.EscapeSpecialCharacters().Quote(); public string Char(char c) => $"'{c}'"; + + public IEnumerable MultiLineString(string name, string str) + { + var strings = str.Split('\n'); + var renderedStrings = strings.Select((t, i) => i < strings.Length - 1 + ? $"{String(t + "\n")} +" + : $"{String(t)}"); + + return MultiLineVariable(renderedStrings, name); + } } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderTuple.cs b/generators/Output/Rendering/RenderTuple.cs new file mode 100644 index 0000000000..23609114d6 --- /dev/null +++ b/generators/Output/Rendering/RenderTuple.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Exercism.CSharp.Output.Rendering +{ + public partial class Render + { + public string Tuple(Tuple tuple) => + $"Tuple.Create({tuple.Item1}, {tuple.Item2})"; + } +} \ No newline at end of file diff --git a/generators/Output/Rendering/RenderVariable.cs b/generators/Output/Rendering/RenderVariable.cs new file mode 100644 index 0000000000..69c2397aeb --- /dev/null +++ b/generators/Output/Rendering/RenderVariable.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Exercism.CSharp.Helpers; + +namespace Exercism.CSharp.Output.Rendering +{ + public partial class Render + { + public IEnumerable Variables(IDictionary dict) + => dict.Keys.SelectMany(key => Variable(dict[key], key.ToVariableName())).ToArray(); + + public IEnumerable Variable(object val, string name) + { + switch (val) + { + case string str when str.Contains("\n"): + return MultiLineString(name, str); + case MultiLineString multiLineValue when multiLineValue.ToString().Contains("\n"): + return MultiLineString(name, multiLineValue.ToString()); + case IEnumerable strings: + if (!strings.Any()) + { + return new[] {$"var {name} = Array.Empty();"}; + } + + return MultiLineEnumerable( + strings.Select((str, i) => String(str) + (i < strings.Count() - 1 ? "," : "")), name, "new[]"); + case IDictionary dict: + return MultiLineEnumerable( + dict.Keys.Select((key, i) => + $"[{Char(key)}] = {Int(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, + "new Dictionary"); + case IDictionary dict: + return MultiLineEnumerable( + dict.Keys.Select((key, i) => + $"[{String(key)}] = {Int(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, + "new Dictionary"); + case IDictionary dict: + return MultiLineEnumerable( + dict.Keys.Select((key, i) => + $"[{Int(key)}] = {Array(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, + "new Dictionary"); + case IEnumerable> tuples: + return new[] {Array(tuples)}; + default: + return new[] {$"var {name} = {Object(val)};"}; + } + } + + public IEnumerable MultiLineVariable(IEnumerable enumerable, string name, string constructor = null) + => enumerable.Select(line => line == "{" || line == "}" ? line : line.Indent()).AddTrailingSemicolon().Prepend($"var {name} = {constructor}").ToArray(); + } +} \ No newline at end of file From e77a86f1e8822627ed6c8b468103dd699432c778 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 30 Jun 2018 14:51:45 +0200 Subject: [PATCH 54/97] generators: Make list rendering generic --- generators/Exercises/Generators/ListOps.cs | 4 +++- generators/Helpers/NameExtensions.cs | 14 +++++++++++ generators/Output/Rendering/Render.cs | 27 ++++++++++++++++------ generators/Output/Rendering/RenderList.cs | 12 ++++------ 4 files changed, 42 insertions(+), 15 deletions(-) diff --git a/generators/Exercises/Generators/ListOps.cs b/generators/Exercises/Generators/ListOps.cs index 16372bfff7..cced7d955b 100644 --- a/generators/Exercises/Generators/ListOps.cs +++ b/generators/Exercises/Generators/ListOps.cs @@ -93,7 +93,9 @@ private dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) .Replace("", "") .Replace("new List { new List", "new List> { new List") .Replace("new[] { new List>", "new List>> { new List>") - .Replace("new[] { new List", "new List> { new List")); + .Replace("new[] { new List", "new List> { new List") + .Replace("new List { new List>", "new List>> { new List>") + .Replace("new List { new List", "new List> { new List")); case IEnumerable ints: return new UnescapedValue(Render.Object(ints.ToList())); } diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index a8459d398e..7dd0f5a411 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Net; using System.Text.RegularExpressions; using Humanizer; @@ -32,5 +33,18 @@ public static string ToTestMethodName(this string input) public static string ToTestedMethodName(this string input) => input.Dehumanize(); public static string ToVariableName(this string input) => input.Camelize(); + + public static string ToBuiltInTypeName(this Type type) + { + switch (type.FullName) + { + case "System.Int32": + return "int"; + case "System.Object": + return "object"; + default: + return type.Name; + } + } } } \ No newline at end of file diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 1bf75d05cf..e429ceb08f 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -12,6 +12,15 @@ public partial class Render { public string Object(object val) { + if (val == null) + return null; + + if (RenderList(val)) + return List((dynamic)val); + +// if (val.IsEnumerable()) +// return Array((dynamic) val); + switch (val) { case string str: return String(str); @@ -22,22 +31,26 @@ public string Object(object val) case ulong ulng: return Ulong(ulng); case char c: return Char(c); case Tuple tuple: return Tuple(tuple); - case List ints: return List(ints); - case List objects: return List(objects); + case JArray jArray: return Array(jArray); case IEnumerable ints: return Array(ints); case IEnumerable strings: return Array(strings); case IEnumerable unescapedValues when unescapedValues.Any(): return Array(unescapedValues); + case IEnumerable> tuples: return Array(tuples); + case IEnumerable> tuples: return Array(tuples); + case IEnumerable objects: return Array(objects); case IDictionary dict: return Dictionary(dict); case IDictionary dict: return Dictionary(dict); case IDictionary dict: return Dictionary(dict); case IDictionary dict: return Dictionary(dict); - case JArray jArray: return Array(jArray); case int[,] multidimensionalArray: return MultidimensionalArray(multidimensionalArray); - case IEnumerable> tuples: return Array(tuples); - case IEnumerable> tuples: return Array(tuples); - case IEnumerable objects: return Array(objects); - default: return val?.ToString(); + default: return val.ToString(); } } + + public static bool RenderEnumerable(object obj) + => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(IEnumerable<>); + + public static bool RenderList(object obj) + => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(List<>); } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderList.cs b/generators/Output/Rendering/RenderList.cs index 39022a4dee..5d17643925 100644 --- a/generators/Output/Rendering/RenderList.cs +++ b/generators/Output/Rendering/RenderList.cs @@ -1,16 +1,14 @@ using System.Collections.Generic; using System.Linq; +using Exercism.CSharp.Helpers; namespace Exercism.CSharp.Output.Rendering { public partial class Render - { - public string List(List ints) => - ints.Any() ? $"new List {{ {string.Join(", ", ints.Select(Int))} }}" : "new List()"; - - public string List(List objects) => + { + public string List(List objects) => objects.Any() - ? $"new List {{ {string.Join(", ", objects.Select(Object))} }}" - : "new List()"; + ? $"new List<{typeof(T).ToBuiltInTypeName()}> {{ {string.Join(", ", objects.Cast().Select(Object))} }}" + : $"new List<{typeof(T).ToBuiltInTypeName()}>()"; } } \ No newline at end of file From 5e459c51bbe1dc75adcdbe427fb51aea74a4c09b Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sat, 30 Jun 2018 15:15:05 +0200 Subject: [PATCH 55/97] generators: Make array rendering generic --- .../Exercises/Generators/SaddlePoints.cs | 8 +++-- generators/Helpers/NameExtensions.cs | 10 ++++++ generators/Output/Rendering/Render.cs | 32 ++++++++----------- generators/Output/Rendering/RenderArray.cs | 29 ++++------------- generators/Output/Rendering/RenderList.cs | 6 ++-- 5 files changed, 38 insertions(+), 47 deletions(-) diff --git a/generators/Exercises/Generators/SaddlePoints.cs b/generators/Exercises/Generators/SaddlePoints.cs index 20991ac52e..b17ee0c720 100644 --- a/generators/Exercises/Generators/SaddlePoints.cs +++ b/generators/Exercises/Generators/SaddlePoints.cs @@ -39,13 +39,17 @@ private static dynamic ToMultiDimensionalArray(dynamic array) return jArray.ToObject(); } - private static IEnumerable> ToTupleCollection(Array array) + private static Tuple[] ToTupleCollection(Array array) { + var tuples = new List>(); + for (var x = 0; x < array.GetLength(0); x++) { var current = array.GetValue(x) as Dictionary; - yield return new Tuple(current["row"].ToString(), current["column"].ToString()); + tuples.Add(new Tuple(current["row"].ToString(), current["column"].ToString())); } + + return tuples.ToArray(); } } } diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index 7dd0f5a411..739a01fe1a 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Net; using System.Text.RegularExpressions; using Humanizer; @@ -36,12 +37,21 @@ public static string ToTestMethodName(this string input) public static string ToBuiltInTypeName(this Type type) { + if (type.GenericTypeArguments.Any()) + { + var genericTypeName = type.Name.Substring(0, type.Name.IndexOf("`", StringComparison.OrdinalIgnoreCase)); + var genericTypeArguments = string.Join(",", type.GenericTypeArguments.Select(ToBuiltInTypeName)); + return $"{genericTypeName}<{genericTypeArguments}>"; + } + switch (type.FullName) { case "System.Int32": return "int"; case "System.Object": return "object"; + case "System.String": + return "string"; default: return type.Name; } diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index e429ceb08f..a914dd3376 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -15,12 +15,6 @@ public string Object(object val) if (val == null) return null; - if (RenderList(val)) - return List((dynamic)val); - -// if (val.IsEnumerable()) -// return Array((dynamic) val); - switch (val) { case string str: return String(str); @@ -31,26 +25,26 @@ public string Object(object val) case ulong ulng: return Ulong(ulng); case char c: return Char(c); case Tuple tuple: return Tuple(tuple); - case JArray jArray: return Array(jArray); - case IEnumerable ints: return Array(ints); - case IEnumerable strings: return Array(strings); - case IEnumerable unescapedValues when unescapedValues.Any(): return Array(unescapedValues); - case IEnumerable> tuples: return Array(tuples); - case IEnumerable> tuples: return Array(tuples); - case IEnumerable objects: return Array(objects); case IDictionary dict: return Dictionary(dict); case IDictionary dict: return Dictionary(dict); case IDictionary dict: return Dictionary(dict); case IDictionary dict: return Dictionary(dict); case int[,] multidimensionalArray: return MultidimensionalArray(multidimensionalArray); - default: return val.ToString(); + default: + if (RenderList(val)) + return List((dynamic)val); + + if (RenderArray(val)) + return Array((dynamic) val); + + return val.ToString(); } } - - public static bool RenderEnumerable(object obj) - => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(IEnumerable<>); - - public static bool RenderList(object obj) + + private static bool RenderList(object obj) => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(List<>); + + private static bool RenderArray(object obj) + => obj.GetType().IsArray; } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs index d23080b0a9..376061a523 100644 --- a/generators/Output/Rendering/RenderArray.cs +++ b/generators/Output/Rendering/RenderArray.cs @@ -1,32 +1,15 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using Newtonsoft.Json.Linq; +using Exercism.CSharp.Helpers; namespace Exercism.CSharp.Output.Rendering { public partial class Render { - public string Array(IEnumerable ints) => - ints.Any() ? $"new[] {{ {string.Join(", ", ints)} }}" : "Array.Empty()"; - - public string Array(IEnumerable strings) => - strings.Any() ? $"new[] {{ {string.Join(", ", strings.Select(String))} }}" : "Array.Empty()"; - - public string Array(IEnumerable objects) => - objects.Any() ? $"new[] {{ {string.Join(", ", objects.Select(Object))} }}" : "Array.Empty()"; - - public string Array(JArray jArray) => - $"new[] {{ {string.Join(", ", jArray.Select(Array))} }}"; - - public string Array(IEnumerable unescapedValues) => - $"new[] {{ {string.Join(", ", unescapedValues.Select(Object))} }}"; - - public string Array(IEnumerable> tuples) => - $"new[] {{ {string.Join(", ", tuples.Select(Tuple))} }}"; - - public string Array(IEnumerable> tuples) => tuples.Any() ? - $"new[] {{ {string.Join(", ", tuples)} }}" : "Array.Empty>()"; + public string Array(IEnumerable elements) => + elements.Any() + ? $"new[] {{ {string.Join(", ", elements.Cast().Select(Object))} }}" + : $"Array.Empty<{typeof(T).ToBuiltInTypeName()}>()"; public string MultidimensionalArray(int[,] multidimensionalArray) { diff --git a/generators/Output/Rendering/RenderList.cs b/generators/Output/Rendering/RenderList.cs index 5d17643925..57295f5ef8 100644 --- a/generators/Output/Rendering/RenderList.cs +++ b/generators/Output/Rendering/RenderList.cs @@ -6,9 +6,9 @@ namespace Exercism.CSharp.Output.Rendering { public partial class Render { - public string List(List objects) => - objects.Any() - ? $"new List<{typeof(T).ToBuiltInTypeName()}> {{ {string.Join(", ", objects.Cast().Select(Object))} }}" + public string List(List elements) => + elements.Any() + ? $"new List<{typeof(T).ToBuiltInTypeName()}> {{ {string.Join(", ", elements.Cast().Select(Object))} }}" : $"new List<{typeof(T).ToBuiltInTypeName()}>()"; } } \ No newline at end of file From fafae7839d28c90df9fd7ab27b98dcb1d02ebdc3 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 1 Jul 2018 10:17:31 +0200 Subject: [PATCH 56/97] generators: Make dictionary rendering generic --- generators/Exercises/Generators/Allergies.cs | 1 - .../Exercises/Generators/BinarySearchTree.cs | 1 - generators/Exercises/Generators/Bowling.cs | 1 - .../Exercises/Generators/CircularBuffer.cs | 1 - generators/Exercises/Generators/Clock.cs | 25 +++++++++---------- generators/Exercises/Generators/Connect.cs | 1 - .../Generators/KindergartenGarden.cs | 1 - generators/Exercises/Generators/Meetup.cs | 1 - .../Exercises/Generators/NucleotideCount.cs | 1 - .../Generators/PalindromeProducts.cs | 1 - .../Exercises/Generators/PerfectNumbers.cs | 1 - .../Exercises/Generators/QueenAttack.cs | 1 - .../Exercises/Generators/RationalNumbers.cs | 1 - .../Exercises/Generators/RunLengthEncoding.cs | 1 - generators/Exercises/Generators/TwoBucket.cs | 1 - generators/Exercises/Generators/Yacht.cs | 1 - .../Exercises/Generators/ZebraPuzzle.cs | 1 - generators/Exercises/Generators/Zipper.cs | 1 - generators/Helpers/NameExtensions.cs | 1 - generators/Output/Rendering/Render.cs | 23 ++++++++--------- .../Output/Rendering/RenderDictionary.cs | 18 +++++-------- generators/Output/Rendering/RenderTuple.cs | 2 -- generators/Output/TestMethod.cs | 4 +-- 23 files changed, 30 insertions(+), 60 deletions(-) diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index 5e444926c4..633bcd3d9e 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -1,6 +1,5 @@ using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index b4b39a6d10..80604d00b4 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index 27c95ecac1..f495c2ae45 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index a213812a33..a72ad1b8e3 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 76ad1e4545..2edcbfa1fa 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -1,5 +1,4 @@ -using System.Collections.Generic; -using Exercism.CSharp.Output; +using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators @@ -15,17 +14,17 @@ public class Clock : GeneratorExercise private const string PropertyEqual = "equal"; protected override void UpdateTestData(TestData data) - { - if (data.Property != PropertyEqual) - { - data.SetConstructorInputParameters(ParamHour, ParamMinute); - } - else + { + data.SetConstructorInputParameters(ParamHour, ParamMinute); + + if (data.Property == PropertyEqual) { - data.SetConstructorInputParameters(ParamClock2); - - var result = (Dictionary)data.Input[ParamClock1]; - data.Input[ParamClock1] = new UnescapedValue($"new Clock({result[ParamHour]}, {result[ParamMinute]})"); + var clock1 = data.Input[ParamClock1]; + data.Input[ParamClock1] = new UnescapedValue($"new Clock({clock1[ParamHour]}, {clock1[ParamMinute]})"); + + var clock2 = data.Input[ParamClock2]; + data.Input[ParamHour] = clock2[ParamHour]; + data.Input[ParamMinute] = clock2[ParamMinute]; } if (data.Property == PropertyCreate) @@ -60,7 +59,7 @@ private string RenderConsistencyToAssert(TestMethod method) private string RenderEqualToAssert(TestMethod method) { - var expected = method.Data.Input[ParamClock1].ToString(); + var expected = Render.Object(method.Data.Input[ParamClock1]); return method.Data.Expected ? Render.AssertEqual(expected, "sut") diff --git a/generators/Exercises/Generators/Connect.cs b/generators/Exercises/Generators/Connect.cs index c09d10e126..e71a653445 100644 --- a/generators/Exercises/Generators/Connect.cs +++ b/generators/Exercises/Generators/Connect.cs @@ -1,5 +1,4 @@ using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/KindergartenGarden.cs b/generators/Exercises/Generators/KindergartenGarden.cs index fec25d4373..e93b7c094c 100644 --- a/generators/Exercises/Generators/KindergartenGarden.cs +++ b/generators/Exercises/Generators/KindergartenGarden.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index 0909e73520..1df8779188 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index 0de3cf6a10..63a72d2cf7 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index 1eb0212806..bc7b2a1d9f 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Exercises/Generators/PerfectNumbers.cs b/generators/Exercises/Generators/PerfectNumbers.cs index 4a0ba56b94..d61f27404e 100644 --- a/generators/Exercises/Generators/PerfectNumbers.cs +++ b/generators/Exercises/Generators/PerfectNumbers.cs @@ -1,6 +1,5 @@ using System; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index 325b0e4b62..0ffe7862e0 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index 71d805fefb..59f6693a6d 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index 4cc28c4413..cc723571b4 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -1,5 +1,4 @@ using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index 2d3dee6d15..9019186f56 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -1,6 +1,5 @@ using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/Yacht.cs b/generators/Exercises/Generators/Yacht.cs index 080045b0ae..c9abf0c6bf 100644 --- a/generators/Exercises/Generators/Yacht.cs +++ b/generators/Exercises/Generators/Yacht.cs @@ -1,5 +1,4 @@ using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/ZebraPuzzle.cs b/generators/Exercises/Generators/ZebraPuzzle.cs index bb307b3cc4..4eb04cd17b 100644 --- a/generators/Exercises/Generators/ZebraPuzzle.cs +++ b/generators/Exercises/Generators/ZebraPuzzle.cs @@ -1,5 +1,4 @@ using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index a7cf655c65..b8721eade9 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Text; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; using Humanizer; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index 739a01fe1a..7ca8fda270 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using System.Net; using System.Text.RegularExpressions; using Humanizer; diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index a914dd3376..9981346cfa 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -1,15 +1,10 @@ using System; using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using Exercism.CSharp.Helpers; -using Humanizer; -using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Output.Rendering { public partial class Render - { + { public string Object(object val) { if (val == null) @@ -25,18 +20,17 @@ public string Object(object val) case ulong ulng: return Ulong(ulng); case char c: return Char(c); case Tuple tuple: return Tuple(tuple); - case IDictionary dict: return Dictionary(dict); - case IDictionary dict: return Dictionary(dict); - case IDictionary dict: return Dictionary(dict); - case IDictionary dict: return Dictionary(dict); case int[,] multidimensionalArray: return MultidimensionalArray(multidimensionalArray); - default: + default: if (RenderList(val)) return List((dynamic)val); if (RenderArray(val)) - return Array((dynamic) val); - + return Array((dynamic)val); + + if (RenderDictionary(val)) + return Dictionary((dynamic)val); + return val.ToString(); } } @@ -46,5 +40,8 @@ private static bool RenderList(object obj) private static bool RenderArray(object obj) => obj.GetType().IsArray; + + private static bool RenderDictionary(object obj) + => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>); } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderDictionary.cs b/generators/Output/Rendering/RenderDictionary.cs index d18ec34f46..96b07a1448 100644 --- a/generators/Output/Rendering/RenderDictionary.cs +++ b/generators/Output/Rendering/RenderDictionary.cs @@ -1,20 +1,14 @@ using System.Collections.Generic; using System.Linq; +using Exercism.CSharp.Helpers; namespace Exercism.CSharp.Output.Rendering { public partial class Render - { - public string Dictionary(IDictionary dict) => - string.Join(", ", dict.Values.Select(Object)); - - public string Dictionary(IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Char(key)}] = {Int(dict[key])}"))} }}"; - - public string Dictionary(IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{String(key)}] = {Int(dict[key])}"))} }}"; - - public string Dictionary(IDictionary dict) => - $"new Dictionary {{ {string.Join(", ", dict.Keys.Select(key => $"[{Int(key)}] = {Array(dict[key])}"))} }}"; + { + public string Dictionary(IDictionary dict) => + dict.Count == 0 + ? $"new Dictionary<{typeof(TKey).ToBuiltInTypeName()}, {typeof(TValue).ToBuiltInTypeName()}> {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}" + : $"new Dictionary<{typeof(TKey).ToBuiltInTypeName()}, {typeof(TValue).ToBuiltInTypeName()}>"; } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderTuple.cs b/generators/Output/Rendering/RenderTuple.cs index 23609114d6..885bb1d987 100644 --- a/generators/Output/Rendering/RenderTuple.cs +++ b/generators/Output/Rendering/RenderTuple.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; namespace Exercism.CSharp.Output.Rendering { diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index 16cc2dbe74..99fc9c3c3b 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -47,8 +47,8 @@ public string Render() public string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : Renderer.Object(Data.Expected); - private string InputParameters => Data.UseVariablesForInput ? string.Join(", ", Data.InputParameters.Select(key => key.ToVariableName())) : Renderer.Object(Input); - private string ConstructorParameters => Data.UseVariablesForConstructorParameters ? string.Join(", ", Data.ConstructorInputParameters.Select(key => key.ToVariableName())) : Renderer.Object(ConstructorInput); + private string InputParameters => string.Join(", ", Data.InputParameters.Select(key => Data.UseVariablesForInput ? key.ToVariableName() : Renderer.Object(Data.Input[key]))); + private string ConstructorParameters => string.Join(", ", Data.ConstructorInputParameters.Select(key => Data.UseVariablesForConstructorParameters ? key.ToVariableName() : Renderer.Object(Data.Input[key]))); private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); From f58aa780ee4ed8f5cc40516d569d8eb398326af2 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 1 Jul 2018 10:22:05 +0200 Subject: [PATCH 57/97] generators: Improved friendly name generation --- exercises/go-counting/GoCountingTest.cs | 12 +++--- exercises/list-ops/ListOpsTest.cs | 2 +- generators/Helpers/NameExtensions.cs | 41 ++++++++++--------- generators/Output/Rendering/RenderArray.cs | 2 +- .../Output/Rendering/RenderDictionary.cs | 4 +- generators/Output/Rendering/RenderList.cs | 4 +- 6 files changed, 34 insertions(+), 31 deletions(-) diff --git a/exercises/go-counting/GoCountingTest.cs b/exercises/go-counting/GoCountingTest.cs index 49e2ada09b..518a7c8722 100644 --- a/exercises/go-counting/GoCountingTest.cs +++ b/exercises/go-counting/GoCountingTest.cs @@ -69,7 +69,7 @@ public void A_stone_and_not_a_territory_on_5x5_board() " W "; var sut = new GoCounting(board); var actual = sut.Territory(coordinate); - var expected = (Owner.None, Array.Empty>()); + var expected = (Owner.None, Array.Empty>()); Assert.Equal(expected.Item1, actual.Item1); Assert.Equal(expected.Item2, actual.Item2); } @@ -138,8 +138,8 @@ public void One_territory_is_the_whole_board() var actual = sut.Territories(); var expected = new Dictionary[]> { - [Owner.Black] = Array.Empty>(), - [Owner.White] = Array.Empty>(), + [Owner.Black] = Array.Empty>(), + [Owner.White] = Array.Empty>(), [Owner.None] = new[] { (0, 0) } }; Assert.Equal(expected.Keys, actual.Keys); @@ -160,7 +160,7 @@ public void Two_territory_rectangular_board() { [Owner.Black] = new[] { (0, 0), (0, 1) }, [Owner.White] = new[] { (3, 0), (3, 1) }, - [Owner.None] = Array.Empty>() + [Owner.None] = Array.Empty>() }; Assert.Equal(expected.Keys, actual.Keys); Assert.Equal(expected[Owner.Black], actual[Owner.Black]); @@ -177,8 +177,8 @@ public void Two_region_rectangular_board() var expected = new Dictionary[]> { [Owner.Black] = new[] { (0, 0), (2, 0) }, - [Owner.White] = Array.Empty>(), - [Owner.None] = Array.Empty>() + [Owner.White] = Array.Empty>(), + [Owner.None] = Array.Empty>() }; Assert.Equal(expected.Keys, actual.Keys); Assert.Equal(expected[Owner.Black], actual[Owner.Black]); diff --git a/exercises/list-ops/ListOpsTest.cs b/exercises/list-ops/ListOpsTest.cs index 38cbc1cf28..cd86fcec64 100644 --- a/exercises/list-ops/ListOpsTest.cs +++ b/exercises/list-ops/ListOpsTest.cs @@ -50,7 +50,7 @@ public void Concatenate_a_list_of_lists_list_of_lists() [Fact(Skip = "Remove to run test")] public void Concatenate_a_list_of_lists_list_of_nested_lists() { - var lists = new List>> { new List> { new List { 1 }, new List { 2 } }, new List> { new List { 3 } }, new List> { new List() }, new List> { new List { 4, 5, 6 } } }; + var lists = new List { new List { new List { 1 }, new List { 2 } }, new List { new List { 3 } }, new List { new List() }, new List { new List { 4, 5, 6 } } }; var expected = new List> { new List { 1 }, new List { 2 }, new List { 3 }, new List(), new List { 4, 5, 6 } }; Assert.Equal(expected, ListOps.Concat(lists)); } diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index 7ca8fda270..328b1af27e 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -34,26 +34,29 @@ public static string ToTestMethodName(this string input) public static string ToVariableName(this string input) => input.Camelize(); - public static string ToBuiltInTypeName(this Type type) + public static string ToFriendlyName(this Type type) { - if (type.GenericTypeArguments.Any()) - { - var genericTypeName = type.Name.Substring(0, type.Name.IndexOf("`", StringComparison.OrdinalIgnoreCase)); - var genericTypeArguments = string.Join(",", type.GenericTypeArguments.Select(ToBuiltInTypeName)); - return $"{genericTypeName}<{genericTypeArguments}>"; - } - - switch (type.FullName) - { - case "System.Int32": - return "int"; - case "System.Object": - return "object"; - case "System.String": - return "string"; - default: - return type.Name; - } + if (type == typeof(int)) + return "int"; + if (type == typeof(short)) + return "short"; + if (type == typeof(byte)) + return "byte"; + if (type == typeof(bool)) + return "bool"; + if (type == typeof(long)) + return "long"; + if (type == typeof(float)) + return "float"; + if (type == typeof(double)) + return "double"; + if (type == typeof(decimal)) + return "decimal"; + if (type == typeof(string)) + return "string"; + if (type.IsGenericType) + return type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(ToFriendlyName).ToArray()) + ">"; + return type.Name; } } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs index 376061a523..0e3f46f8e3 100644 --- a/generators/Output/Rendering/RenderArray.cs +++ b/generators/Output/Rendering/RenderArray.cs @@ -9,7 +9,7 @@ public partial class Render public string Array(IEnumerable elements) => elements.Any() ? $"new[] {{ {string.Join(", ", elements.Cast().Select(Object))} }}" - : $"Array.Empty<{typeof(T).ToBuiltInTypeName()}>()"; + : $"Array.Empty<{typeof(T).ToFriendlyName()}>()"; public string MultidimensionalArray(int[,] multidimensionalArray) { diff --git a/generators/Output/Rendering/RenderDictionary.cs b/generators/Output/Rendering/RenderDictionary.cs index 96b07a1448..3b299f5893 100644 --- a/generators/Output/Rendering/RenderDictionary.cs +++ b/generators/Output/Rendering/RenderDictionary.cs @@ -8,7 +8,7 @@ public partial class Render { public string Dictionary(IDictionary dict) => dict.Count == 0 - ? $"new Dictionary<{typeof(TKey).ToBuiltInTypeName()}, {typeof(TValue).ToBuiltInTypeName()}> {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}" - : $"new Dictionary<{typeof(TKey).ToBuiltInTypeName()}, {typeof(TValue).ToBuiltInTypeName()}>"; + ? $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}> {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}" + : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>"; } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderList.cs b/generators/Output/Rendering/RenderList.cs index 57295f5ef8..3dd350bd4e 100644 --- a/generators/Output/Rendering/RenderList.cs +++ b/generators/Output/Rendering/RenderList.cs @@ -8,7 +8,7 @@ public partial class Render { public string List(List elements) => elements.Any() - ? $"new List<{typeof(T).ToBuiltInTypeName()}> {{ {string.Join(", ", elements.Cast().Select(Object))} }}" - : $"new List<{typeof(T).ToBuiltInTypeName()}>()"; + ? $"new List<{typeof(T).ToFriendlyName()}> {{ {string.Join(", ", elements.Cast().Select(Object))} }}" + : $"new List<{typeof(T).ToFriendlyName()}>()"; } } \ No newline at end of file From eced4e93b5511ed9b133bcd7587f37f9422531e0 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 1 Jul 2018 10:58:46 +0200 Subject: [PATCH 58/97] generators: Make multidimensional array rendering generic --- exercises/saddle-points/SaddlePointsTest.cs | 28 +++------------ exercises/spiral-matrix/SpiralMatrixTest.cs | 35 +++---------------- generators/Output/Rendering/Render.cs | 1 - generators/Output/Rendering/RenderArray.cs | 33 ++++++++--------- generators/Output/Rendering/RenderVariable.cs | 2 +- 5 files changed, 27 insertions(+), 72 deletions(-) diff --git a/exercises/saddle-points/SaddlePointsTest.cs b/exercises/saddle-points/SaddlePointsTest.cs index 0e913a31ab..d679182702 100644 --- a/exercises/saddle-points/SaddlePointsTest.cs +++ b/exercises/saddle-points/SaddlePointsTest.cs @@ -8,12 +8,7 @@ public class SaddlePointsTest [Fact] public void Can_identify_single_saddle_point() { - var matrix = new[,] - { - { 9, 8, 7 }, - { 5, 3, 2 }, - { 6, 6, 7 } - }; + var matrix = new[,] { { 9, 8, 7 }, { 5, 3, 2 }, { 6, 6, 7 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); var expected = new[] { Tuple.Create(1, 0) }; @@ -32,12 +27,7 @@ public void Can_identify_that_empty_matrix_has_no_saddle_points() [Fact(Skip = "Remove to run test")] public void Can_identify_lack_of_saddle_points_when_there_are_none() { - var matrix = new[,] - { - { 1, 2, 3 }, - { 3, 1, 2 }, - { 2, 3, 1 } - }; + var matrix = new[,] { { 1, 2, 3 }, { 3, 1, 2 }, { 2, 3, 1 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); Assert.Empty(actual); @@ -46,12 +36,7 @@ public void Can_identify_lack_of_saddle_points_when_there_are_none() [Fact(Skip = "Remove to run test")] public void Can_identify_multiple_saddle_points() { - var matrix = new[,] - { - { 4, 5, 4 }, - { 3, 5, 5 }, - { 1, 5, 4 } - }; + var matrix = new[,] { { 4, 5, 4 }, { 3, 5, 5 }, { 1, 5, 4 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); var expected = new[] { Tuple.Create(0, 1), Tuple.Create(1, 1), Tuple.Create(2, 1) }; @@ -61,12 +46,7 @@ public void Can_identify_multiple_saddle_points() [Fact(Skip = "Remove to run test")] public void Can_identify_saddle_point_in_bottom_right_corner() { - var matrix = new[,] - { - { 8, 7, 9 }, - { 6, 7, 6 }, - { 3, 2, 5 } - }; + var matrix = new[,] { { 8, 7, 9 }, { 6, 7, 6 }, { 3, 2, 5 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); var expected = new[] { Tuple.Create(2, 2) }; diff --git a/exercises/spiral-matrix/SpiralMatrixTest.cs b/exercises/spiral-matrix/SpiralMatrixTest.cs index f4622b5b39..b5be47a47d 100644 --- a/exercises/spiral-matrix/SpiralMatrixTest.cs +++ b/exercises/spiral-matrix/SpiralMatrixTest.cs @@ -13,60 +13,35 @@ public void Empty_spiral() [Fact(Skip = "Remove to run test")] public void Trivial_spiral() { - var expected = new[,] - { - { 1 } - }; + var expected = new[,] { { 1 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(1)); } [Fact(Skip = "Remove to run test")] public void Spiral_of_size_2() { - var expected = new[,] - { - { 1, 2 }, - { 4, 3 } - }; + var expected = new[,] { { 1, 2 }, { 4, 3 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(2)); } [Fact(Skip = "Remove to run test")] public void Spiral_of_size_3() { - var expected = new[,] - { - { 1, 2, 3 }, - { 8, 9, 4 }, - { 7, 6, 5 } - }; + var expected = new[,] { { 1, 2, 3 }, { 8, 9, 4 }, { 7, 6, 5 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(3)); } [Fact(Skip = "Remove to run test")] public void Spiral_of_size_4() { - var expected = new[,] - { - { 1, 2, 3, 4 }, - { 12, 13, 14, 5 }, - { 11, 16, 15, 6 }, - { 10, 9, 8, 7 } - }; + var expected = new[,] { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(4)); } [Fact(Skip = "Remove to run test")] public void Spiral_of_size_5() { - var expected = new[,] - { - { 1, 2, 3, 4, 5 }, - { 16, 17, 18, 19, 6 }, - { 15, 24, 25, 20, 7 }, - { 14, 23, 22, 21, 8 }, - { 13, 12, 11, 10, 9 } - }; + var expected = new[,] { { 1, 2, 3, 4, 5 }, { 16, 17, 18, 19, 6 }, { 15, 24, 25, 20, 7 }, { 14, 23, 22, 21, 8 }, { 13, 12, 11, 10, 9 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(5)); } } \ No newline at end of file diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 9981346cfa..f3f09cef13 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -20,7 +20,6 @@ public string Object(object val) case ulong ulng: return Ulong(ulng); case char c: return Char(c); case Tuple tuple: return Tuple(tuple); - case int[,] multidimensionalArray: return MultidimensionalArray(multidimensionalArray); default: if (RenderList(val)) return List((dynamic)val); diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs index 0e3f46f8e3..73de75763e 100644 --- a/generators/Output/Rendering/RenderArray.cs +++ b/generators/Output/Rendering/RenderArray.cs @@ -1,36 +1,37 @@ using System.Collections.Generic; using System.Linq; +using System.Text; using Exercism.CSharp.Helpers; namespace Exercism.CSharp.Output.Rendering { public partial class Render - { - public string Array(IEnumerable elements) => + { + public string Array(T[] elements) => elements.Any() ? $"new[] {{ {string.Join(", ", elements.Cast().Select(Object))} }}" : $"Array.Empty<{typeof(T).ToFriendlyName()}>()"; + + public string Array(T[,] elements) + { + return elements.Length == 0 + ? $"new {typeof(T).ToFriendlyName()}[,] {{ }}" + : $"new[,] {{ {string.Join(", ", Rows(elements).Select(Row))} }}"; + + string Row(T[] row) => $"{{ {string.Join(", ", row.Cast().Select(Object))} }}"; + } - public string MultidimensionalArray(int[,] multidimensionalArray) + private static T[][] Rows(T[,] elements) { - IEnumerable SliceRow(T[,] array, int row) - { - for (var i = array.GetLowerBound(1); i <= array.GetUpperBound(1); i++) - { - yield return array[row, i]; - } - } + return Enumerable.Range(0, elements.GetLength(0)) + .Select(Row) + .ToArray(); - return multidimensionalArray.GetLength(0) > 0 - ? $"new[,]\r\n{{\r\n {string.Join(",\r\n ", System.Linq.Enumerable.Range(0, multidimensionalArray.GetUpperBound(0) + 1).Select(x => ToNestedArray(SliceRow(multidimensionalArray, x))))}\r\n}}" - : "new int[,] { }"; + T[] Row(int row) => Enumerable.Range(0, elements.GetLength(1)).Select(col => elements[row, col]).ToArray(); } public IEnumerable MultiLineEnumerable(IEnumerable enumerable, string name, string constructor = null) => MultiLineVariable(enumerable.Prepend("{").Append("}"), name, constructor); - - private string ToNestedArray(IEnumerable enumerable) => - enumerable.Any() ? $"{{ {string.Join(", ", enumerable)} }}" : string.Empty; } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderVariable.cs b/generators/Output/Rendering/RenderVariable.cs index 69c2397aeb..8730d2da88 100644 --- a/generators/Output/Rendering/RenderVariable.cs +++ b/generators/Output/Rendering/RenderVariable.cs @@ -41,7 +41,7 @@ public IEnumerable Variable(object val, string name) dict.Keys.Select((key, i) => $"[{Int(key)}] = {Array(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); - case IEnumerable> tuples: + case ValueTuple[] tuples: return new[] {Array(tuples)}; default: return new[] {$"var {name} = {Object(val)};"}; From 72a1b21eeb95c3742b48a67d48d280e262d40075 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 1 Jul 2018 11:13:58 +0200 Subject: [PATCH 59/97] generators: Make tuple rendering generic --- exercises/dominoes/Dominoes.cs | 2 +- exercises/dominoes/DominoesTest.cs | 24 +++++++++---------- exercises/dominoes/Example.cs | 8 +++---- exercises/saddle-points/Example.cs | 8 +++---- exercises/saddle-points/SaddlePoints.cs | 2 +- exercises/saddle-points/SaddlePointsTest.cs | 6 ++--- generators/Exercises/Generators/Dominoes.cs | 12 ++++------ .../Exercises/Generators/SaddlePoints.cs | 6 ++--- .../Exercises/Generators/SpiralMatrix.cs | 22 ++--------------- generators/Output/Rendering/Render.cs | 1 - generators/Output/Rendering/RenderTuple.cs | 10 -------- generators/Output/Rendering/RenderVariable.cs | 5 +--- 12 files changed, 35 insertions(+), 71 deletions(-) delete mode 100644 generators/Output/Rendering/RenderTuple.cs diff --git a/exercises/dominoes/Dominoes.cs b/exercises/dominoes/Dominoes.cs index 134f76eea3..df8c56dcfc 100644 --- a/exercises/dominoes/Dominoes.cs +++ b/exercises/dominoes/Dominoes.cs @@ -3,7 +3,7 @@ public static class Dominoes { - public static bool CanChain(IEnumerable> dominoes) + public static bool CanChain(IEnumerable<(int, int)> dominoes) { throw new NotImplementedException("You need to implement this function."); } diff --git a/exercises/dominoes/DominoesTest.cs b/exercises/dominoes/DominoesTest.cs index 03d2270700..c8fe30e196 100644 --- a/exercises/dominoes/DominoesTest.cs +++ b/exercises/dominoes/DominoesTest.cs @@ -8,84 +8,84 @@ public class DominoesTest [Fact] public void Empty_input_empty_output() { - var dominoes = new Tuple[] { }; + var dominoes = Array.Empty>(); Assert.True(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Singleton_input_singleton_output() { - var dominoes = new Tuple[] { Tuple.Create(1, 1) }; + var dominoes = new[] { (1, 1) }; Assert.True(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Singleton_that_cant_be_chained() { - var dominoes = new Tuple[] { Tuple.Create(1, 2) }; + var dominoes = new[] { (1, 2) }; Assert.False(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Three_elements() { - var dominoes = new Tuple[] { Tuple.Create(1, 2), Tuple.Create(3, 1), Tuple.Create(2, 3) }; + var dominoes = new[] { (1, 2), (3, 1), (2, 3) }; Assert.True(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Can_reverse_dominoes() { - var dominoes = new Tuple[] { Tuple.Create(1, 2), Tuple.Create(1, 3), Tuple.Create(2, 3) }; + var dominoes = new[] { (1, 2), (1, 3), (2, 3) }; Assert.True(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Cant_be_chained() { - var dominoes = new Tuple[] { Tuple.Create(1, 2), Tuple.Create(4, 1), Tuple.Create(2, 3) }; + var dominoes = new[] { (1, 2), (4, 1), (2, 3) }; Assert.False(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Disconnected_simple() { - var dominoes = new Tuple[] { Tuple.Create(1, 1), Tuple.Create(2, 2) }; + var dominoes = new[] { (1, 1), (2, 2) }; Assert.False(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Disconnected_double_loop() { - var dominoes = new Tuple[] { Tuple.Create(1, 2), Tuple.Create(2, 1), Tuple.Create(3, 4), Tuple.Create(4, 3) }; + var dominoes = new[] { (1, 2), (2, 1), (3, 4), (4, 3) }; Assert.False(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Disconnected_single_isolated() { - var dominoes = new Tuple[] { Tuple.Create(1, 2), Tuple.Create(2, 3), Tuple.Create(3, 1), Tuple.Create(4, 4) }; + var dominoes = new[] { (1, 2), (2, 3), (3, 1), (4, 4) }; Assert.False(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Need_backtrack() { - var dominoes = new Tuple[] { Tuple.Create(1, 2), Tuple.Create(2, 3), Tuple.Create(3, 1), Tuple.Create(2, 4), Tuple.Create(2, 4) }; + var dominoes = new[] { (1, 2), (2, 3), (3, 1), (2, 4), (2, 4) }; Assert.True(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Separate_loops() { - var dominoes = new Tuple[] { Tuple.Create(1, 2), Tuple.Create(2, 3), Tuple.Create(3, 1), Tuple.Create(1, 1), Tuple.Create(2, 2), Tuple.Create(3, 3) }; + var dominoes = new[] { (1, 2), (2, 3), (3, 1), (1, 1), (2, 2), (3, 3) }; Assert.True(Dominoes.CanChain(dominoes)); } [Fact(Skip = "Remove to run test")] public void Nine_elements() { - var dominoes = new Tuple[] { Tuple.Create(1, 2), Tuple.Create(5, 3), Tuple.Create(3, 1), Tuple.Create(1, 2), Tuple.Create(2, 4), Tuple.Create(1, 6), Tuple.Create(2, 3), Tuple.Create(3, 4), Tuple.Create(5, 6) }; + var dominoes = new[] { (1, 2), (5, 3), (3, 1), (1, 2), (2, 4), (1, 6), (2, 3), (3, 4), (5, 6) }; Assert.True(Dominoes.CanChain(dominoes)); } } \ No newline at end of file diff --git a/exercises/dominoes/Example.cs b/exercises/dominoes/Example.cs index d11a0ba022..e530ca8706 100644 --- a/exercises/dominoes/Example.cs +++ b/exercises/dominoes/Example.cs @@ -4,7 +4,7 @@ public static class Dominoes { - public static bool CanChain(IEnumerable> dominoes) + public static bool CanChain(IEnumerable<(int, int)> dominoes) { if (!dominoes.Any()) { @@ -21,17 +21,17 @@ public static bool CanChain(IEnumerable> dominoes) return dominoes.Skip(1).Rotate().Any(sublist => PossibleChains(domino, sublist).Any(CanChain)); } - public static IEnumerable[]> PossibleChains(Tuple domino, IEnumerable> remainder) + public static IEnumerable<(int, int)[]> PossibleChains((int, int) domino, IEnumerable<(int, int)> remainder) { var head = remainder.First(); if (domino.Item2 == head.Item1) { - yield return new[] { Tuple.Create(domino.Item1, head.Item2) }.Concat(remainder.Skip(1)).ToArray(); + yield return new[] { (domino.Item1, head.Item2) }.Concat(remainder.Skip(1)).ToArray(); } else if (domino.Item2 == head.Item2) { - yield return new[] { Tuple.Create(domino.Item1, head.Item1) }.Concat(remainder.Skip(1)).ToArray(); + yield return new[] { (domino.Item1, head.Item1) }.Concat(remainder.Skip(1)).ToArray(); } } diff --git a/exercises/saddle-points/Example.cs b/exercises/saddle-points/Example.cs index 4decb02f87..4b17b1b7f1 100644 --- a/exercises/saddle-points/Example.cs +++ b/exercises/saddle-points/Example.cs @@ -15,20 +15,20 @@ public SaddlePoints(int[,] values) this.minCols = Columns().Select(r => r.Min()).ToArray(); } - public IEnumerable> Calculate() + public IEnumerable<(int, int)> Calculate() { return Coordinates().Where(IsSaddlePoint); } - private bool IsSaddlePoint(Tuple coordinate) + private bool IsSaddlePoint((int, int) coordinate) { return maxRows[coordinate.Item1] == values[coordinate.Item1, coordinate.Item2] && minCols[coordinate.Item2] == values[coordinate.Item1, coordinate.Item2]; } - private IEnumerable> Coordinates() + private IEnumerable<(int, int)> Coordinates() { - return Enumerable.Range(0, RowCount).SelectMany(x => Enumerable.Range(0, ColumnCount).Select(y => Tuple.Create(x, y))); + return Enumerable.Range(0, RowCount).SelectMany(x => Enumerable.Range(0, ColumnCount).Select(y => (x, y))); } private IEnumerable> Rows() diff --git a/exercises/saddle-points/SaddlePoints.cs b/exercises/saddle-points/SaddlePoints.cs index 7d19831ddc..a472688c7f 100644 --- a/exercises/saddle-points/SaddlePoints.cs +++ b/exercises/saddle-points/SaddlePoints.cs @@ -8,7 +8,7 @@ public SaddlePoints(int[,] values) { } - public IEnumerable> Calculate() + public IEnumerable<(int, int)> Calculate() { throw new NotImplementedException("You need to implement this function."); } diff --git a/exercises/saddle-points/SaddlePointsTest.cs b/exercises/saddle-points/SaddlePointsTest.cs index d679182702..10d2be2e99 100644 --- a/exercises/saddle-points/SaddlePointsTest.cs +++ b/exercises/saddle-points/SaddlePointsTest.cs @@ -11,7 +11,7 @@ public void Can_identify_single_saddle_point() var matrix = new[,] { { 9, 8, 7 }, { 5, 3, 2 }, { 6, 6, 7 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); - var expected = new[] { Tuple.Create(1, 0) }; + var expected = new[] { (1, 0) }; Assert.Equal(expected, actual); } @@ -39,7 +39,7 @@ public void Can_identify_multiple_saddle_points() var matrix = new[,] { { 4, 5, 4 }, { 3, 5, 5 }, { 1, 5, 4 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); - var expected = new[] { Tuple.Create(0, 1), Tuple.Create(1, 1), Tuple.Create(2, 1) }; + var expected = new[] { (0, 1), (1, 1), (2, 1) }; Assert.Equal(expected, actual); } @@ -49,7 +49,7 @@ public void Can_identify_saddle_point_in_bottom_right_corner() var matrix = new[,] { { 8, 7, 9 }, { 6, 7, 6 }, { 3, 2, 5 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); - var expected = new[] { Tuple.Create(2, 2) }; + var expected = new[] { (2, 2) }; Assert.Equal(expected, actual); } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Dominoes.cs b/generators/Exercises/Generators/Dominoes.cs index ae19105d8d..7d2e6dc7fb 100644 --- a/generators/Exercises/Generators/Dominoes.cs +++ b/generators/Exercises/Generators/Dominoes.cs @@ -12,19 +12,15 @@ public class Dominoes : GeneratorExercise protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; - data.Input["dominoes"] = ConvertInput(data.Input["dominoes"]); + data.Input["dominoes"] = ConvertDominoes(data.Input["dominoes"]); } protected override void UpdateNamespaces(ISet namespaces) { - namespaces.Add(typeof(Tuple).Namespace); + namespaces.Add(typeof(ValueTuple).Namespace); } - private static UnescapedValue ConvertInput(dynamic input) - { - var dominoes = ((JArray)input).Children(); - var tuplesStringLiteral = dominoes.Select(s => s.ToObject()).Select(s => $"Tuple.Create({s[0]}, {s[1]})"); - return new UnescapedValue($"new Tuple[] {{ {string.Join(", ", tuplesStringLiteral)} }}"); - } + private static ValueTuple[] ConvertDominoes(dynamic input) + => ((JToken)input).ToObject().Select(x => (x[0], x[1])).ToArray(); } } diff --git a/generators/Exercises/Generators/SaddlePoints.cs b/generators/Exercises/Generators/SaddlePoints.cs index b17ee0c720..f7eab38c68 100644 --- a/generators/Exercises/Generators/SaddlePoints.cs +++ b/generators/Exercises/Generators/SaddlePoints.cs @@ -39,14 +39,14 @@ private static dynamic ToMultiDimensionalArray(dynamic array) return jArray.ToObject(); } - private static Tuple[] ToTupleCollection(Array array) + private static ValueTuple[] ToTupleCollection(Array array) { - var tuples = new List>(); + var tuples = new List>(); for (var x = 0; x < array.GetLength(0); x++) { var current = array.GetValue(x) as Dictionary; - tuples.Add(new Tuple(current["row"].ToString(), current["column"].ToString())); + tuples.Add(new ValueTuple(current["row"].ToString(), current["column"].ToString())); } return tuples.ToArray(); diff --git a/generators/Exercises/Generators/SpiralMatrix.cs b/generators/Exercises/Generators/SpiralMatrix.cs index 177d7dde2e..e38c496110 100644 --- a/generators/Exercises/Generators/SpiralMatrix.cs +++ b/generators/Exercises/Generators/SpiralMatrix.cs @@ -1,5 +1,4 @@ -using System.Linq; -using Exercism.CSharp.Output; +using Exercism.CSharp.Output; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators @@ -16,24 +15,7 @@ protected override void UpdateTestData(TestData data) private static dynamic ConvertExpected(dynamic expected) { var jArray = (JArray)expected; - - if (jArray.Count == 0) - return new int[0, 0]; - - var rows = jArray.Count; - var cols = jArray[0].Count(); - - var matrix = new int[rows, cols]; - - for (var y = 0; y < rows; y++) - { - for (var x = 0; x < cols; x++) - { - matrix[y, x] = jArray[y][x].ToObject(); - } - } - - return matrix; + return jArray.Count == 0 ? new int[0, 0] : jArray.ToObject(); } } } diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index f3f09cef13..43518fb89f 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -19,7 +19,6 @@ public string Object(object val) case float flt: return Float(flt); case ulong ulng: return Ulong(ulng); case char c: return Char(c); - case Tuple tuple: return Tuple(tuple); default: if (RenderList(val)) return List((dynamic)val); diff --git a/generators/Output/Rendering/RenderTuple.cs b/generators/Output/Rendering/RenderTuple.cs deleted file mode 100644 index 885bb1d987..0000000000 --- a/generators/Output/Rendering/RenderTuple.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace Exercism.CSharp.Output.Rendering -{ - public partial class Render - { - public string Tuple(Tuple tuple) => - $"Tuple.Create({tuple.Item1}, {tuple.Item2})"; - } -} \ No newline at end of file diff --git a/generators/Output/Rendering/RenderVariable.cs b/generators/Output/Rendering/RenderVariable.cs index 8730d2da88..e81da1a125 100644 --- a/generators/Output/Rendering/RenderVariable.cs +++ b/generators/Output/Rendering/RenderVariable.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Helpers; @@ -41,8 +40,6 @@ public IEnumerable Variable(object val, string name) dict.Keys.Select((key, i) => $"[{Int(key)}] = {Array(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, "new Dictionary"); - case ValueTuple[] tuples: - return new[] {Array(tuples)}; default: return new[] {$"var {name} = {Object(val)};"}; } From b4efb09912e7030257ad01a98f612df5a8ec704f Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 12:44:25 +0200 Subject: [PATCH 60/97] isbn-verifier: Update tests --- exercises/isbn-verifier/IsbnVerifierTest.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/exercises/isbn-verifier/IsbnVerifierTest.cs b/exercises/isbn-verifier/IsbnVerifierTest.cs index b21c789098..5a2ae46dd2 100644 --- a/exercises/isbn-verifier/IsbnVerifierTest.cs +++ b/exercises/isbn-verifier/IsbnVerifierTest.cs @@ -1,4 +1,4 @@ -// This file was auto-generated based on version 2.6.0 of the canonical data. +// This file was auto-generated based on version 2.7.0 of the canonical data. using Xunit; @@ -76,12 +76,6 @@ public void Isbn_without_check_digit() Assert.False(IsbnVerifier.IsValid("3-598-21507")); } - [Fact(Skip = "Remove to run test")] - public void Too_long_isbn() - { - Assert.False(IsbnVerifier.IsValid("3-598-21507-XX")); - } - [Fact(Skip = "Remove to run test")] public void Check_digit_of_x_should_not_be_used_for_0() { @@ -105,4 +99,10 @@ public void Invalid_characters_are_not_ignored() { Assert.False(IsbnVerifier.IsValid("3132P34035")); } + + [Fact(Skip = "Remove to run test")] + public void Input_is_too_long_but_contains_a_valid_isbn() + { + Assert.False(IsbnVerifier.IsValid("98245726788")); + } } \ No newline at end of file From 45bfaa05bcc8adb0970544f0e36120fb3df06586 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 12:51:41 +0200 Subject: [PATCH 61/97] generators: Add friendly name support for char and array types --- generators/Helpers/NameExtensions.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index 328b1af27e..8e7b7590b4 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -54,8 +54,12 @@ public static string ToFriendlyName(this Type type) return "decimal"; if (type == typeof(string)) return "string"; + if (type == typeof(char)) + return "char"; if (type.IsGenericType) - return type.Name.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments().Select(ToFriendlyName).ToArray()) + ">"; + return $"{type.Name.Split('`')[0]}<{string.Join(", ", type.GetGenericArguments().Select(ToFriendlyName).ToArray())}>"; + if (type.IsArray) + return $"{type.GetElementType().ToFriendlyName()}[]"; return type.Name; } } From ac62465e040792453dcaa5dfdd814822d935b1cd Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 13:02:39 +0200 Subject: [PATCH 62/97] generators: Refactor dictionary variable rendering --- generators/Output/Rendering/Render.cs | 12 ++++----- .../Output/Rendering/RenderDictionary.cs | 11 ++++++-- generators/Output/Rendering/RenderVariable.cs | 25 ++++++------------- 3 files changed, 22 insertions(+), 26 deletions(-) diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 43518fb89f..7d6852021d 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -20,26 +20,26 @@ public string Object(object val) case ulong ulng: return Ulong(ulng); case char c: return Char(c); default: - if (RenderList(val)) + if (IsList(val)) return List((dynamic)val); - if (RenderArray(val)) + if (IsArray(val)) return Array((dynamic)val); - if (RenderDictionary(val)) + if (IsDictionary(val)) return Dictionary((dynamic)val); return val.ToString(); } } - private static bool RenderList(object obj) + private static bool IsList(object obj) => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(List<>); - private static bool RenderArray(object obj) + private static bool IsArray(object obj) => obj.GetType().IsArray; - private static bool RenderDictionary(object obj) + private static bool IsDictionary(object obj) => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>); } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderDictionary.cs b/generators/Output/Rendering/RenderDictionary.cs index 3b299f5893..9876a355ed 100644 --- a/generators/Output/Rendering/RenderDictionary.cs +++ b/generators/Output/Rendering/RenderDictionary.cs @@ -8,7 +8,14 @@ public partial class Render { public string Dictionary(IDictionary dict) => dict.Count == 0 - ? $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}> {{ {string.Join(", ", dict.Keys.Select(key => $"[{Object(key)}] = {Object(dict[key])}"))} }}" - : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>"; + ? $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>()" + : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}> {{ {string.Join(", ", dict.Select(KeyValueAssignment))} }}"; + + public string DictionaryMultiLine(IDictionary dict) => + dict.Count == 0 + ? $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>()" + : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>\n{{\n{string.Join(",\n", dict.Select(KeyValueAssignment).Select(assignment => assignment.Indent()))}\n}}"; + + private string KeyValueAssignment(KeyValuePair kv) => $"[{Object(kv.Key)}] = {Object(kv.Value)}"; } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderVariable.cs b/generators/Output/Rendering/RenderVariable.cs index e81da1a125..c6f22314c2 100644 --- a/generators/Output/Rendering/RenderVariable.cs +++ b/generators/Output/Rendering/RenderVariable.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Helpers; @@ -20,28 +21,16 @@ public IEnumerable Variable(object val, string name) case IEnumerable strings: if (!strings.Any()) { - return new[] {$"var {name} = Array.Empty();"}; + return new[] { $"var {name} = Array.Empty();" }; } return MultiLineEnumerable( strings.Select((str, i) => String(str) + (i < strings.Count() - 1 ? "," : "")), name, "new[]"); - case IDictionary dict: - return MultiLineEnumerable( - dict.Keys.Select((key, i) => - $"[{Char(key)}] = {Int(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, - "new Dictionary"); - case IDictionary dict: - return MultiLineEnumerable( - dict.Keys.Select((key, i) => - $"[{String(key)}] = {Int(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, - "new Dictionary"); - case IDictionary dict: - return MultiLineEnumerable( - dict.Keys.Select((key, i) => - $"[{Int(key)}] = {Array(dict[key])}" + (i < dict.Keys.Count - 1 ? "," : "")), name, - "new Dictionary"); default: - return new[] {$"var {name} = {Object(val)};"}; + if (IsDictionary(val)) + return new[] { $"var {name} = {DictionaryMultiLine((dynamic)val)};" }; + + return new[] { $"var {name} = {Object(val)};" }; } } From dc07152850d6442a9e4ffd06cfaeb4eb8c8645bb Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 18 Jun 2018 08:21:26 +0200 Subject: [PATCH 63/97] maintainers: Update ErikSchierboom info (#599) * maintainers: Update ErikSchierboom info --- config/maintainers.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/maintainers.json b/config/maintainers.json index ca61dd1c8c..1c2c90c0ec 100644 --- a/config/maintainers.json +++ b/config/maintainers.json @@ -8,8 +8,8 @@ "name": "Erik Schierboom", "link_text": "My blog", "link_url": "http://www.erikschierboom.com/", - "avatar_url": null, - "bio": null + "avatar_url": "https://nl.gravatar.com/userimage/27030165/64dc5009cee6a1177883121d464d7743.jpg", + "bio": "I am a developer with a passion for learning new languages. C# is a well-designed and expressive language that I love programming in." }, { "github_username": "burtlo", From b01c1a64edcabee4f6885a173a207b29c9a841c8 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 13:02:39 +0200 Subject: [PATCH 64/97] generators: Refactor dictionary variable rendering --- generators/Helpers/ArrayExtensions.cs | 16 ++++++++++++++++ generators/Output/Rendering/RenderArray.cs | 13 ++----------- 2 files changed, 18 insertions(+), 11 deletions(-) create mode 100644 generators/Helpers/ArrayExtensions.cs diff --git a/generators/Helpers/ArrayExtensions.cs b/generators/Helpers/ArrayExtensions.cs new file mode 100644 index 0000000000..e9a9397c88 --- /dev/null +++ b/generators/Helpers/ArrayExtensions.cs @@ -0,0 +1,16 @@ +using System.Linq; + +namespace Exercism.CSharp.Helpers +{ + public static class ArrayExtensions + { + public static T[][] Rows(this T[,] array) + { + return Enumerable.Range(0, array.GetLength(0)) + .Select(Row) + .ToArray(); + + T[] Row(int row) => Enumerable.Range(0, array.GetLength(1)).Select(col => array[row, col]).ToArray(); + } + } +} \ No newline at end of file diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs index 73de75763e..b9eaaae2c4 100644 --- a/generators/Output/Rendering/RenderArray.cs +++ b/generators/Output/Rendering/RenderArray.cs @@ -16,18 +16,9 @@ public string Array(T[,] elements) { return elements.Length == 0 ? $"new {typeof(T).ToFriendlyName()}[,] {{ }}" - : $"new[,] {{ {string.Join(", ", Rows(elements).Select(Row))} }}"; + : $"new[,] {{ {string.Join(", ", elements.Rows().Select(RenderRow))} }}"; - string Row(T[] row) => $"{{ {string.Join(", ", row.Cast().Select(Object))} }}"; - } - - private static T[][] Rows(T[,] elements) - { - return Enumerable.Range(0, elements.GetLength(0)) - .Select(Row) - .ToArray(); - - T[] Row(int row) => Enumerable.Range(0, elements.GetLength(1)).Select(col => elements[row, col]).ToArray(); + string RenderRow(T[] row) => $"{{ {string.Join(", ", row.Cast().Select(Object))} }}"; } public IEnumerable MultiLineEnumerable(IEnumerable enumerable, string name, From 34ebcd466e3f7c112d44d969f64ddae2266204e7 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 13:45:41 +0200 Subject: [PATCH 65/97] generators: Refactor multi-line string (variable) rendering --- generators/Exercises/Generators/Markdown.cs | 2 ++ .../Output/Rendering/MultiLineString.cs | 31 +++++++++++++------ generators/Output/Rendering/Render.cs | 4 +-- generators/Output/Rendering/RenderString.cs | 27 ++++++++++------ generators/Output/Rendering/RenderVariable.cs | 6 ++-- 5 files changed, 43 insertions(+), 27 deletions(-) diff --git a/generators/Exercises/Generators/Markdown.cs b/generators/Exercises/Generators/Markdown.cs index 9dfb31f1ab..53aa1b3734 100644 --- a/generators/Exercises/Generators/Markdown.cs +++ b/generators/Exercises/Generators/Markdown.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -8,6 +9,7 @@ protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; + data.Input["markdown"] = new MultiLineString(data.Input["markdown"]); data.Skip = false; } } diff --git a/generators/Output/Rendering/MultiLineString.cs b/generators/Output/Rendering/MultiLineString.cs index 81094a0fd0..1e13fe76f5 100644 --- a/generators/Output/Rendering/MultiLineString.cs +++ b/generators/Output/Rendering/MultiLineString.cs @@ -1,17 +1,28 @@ using System; -using DotLiquid; +using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Output.Rendering { - public class MultiLineString : ILiquidizable + public class MultiLineString { - private readonly string _value; - - public MultiLineString(object obj) - => _value = string.Join("\n", obj as object[] ?? Array.Empty()); - - public override string ToString() => _value; - - public object ToLiquid() => _value; + public MultiLineString(object obj) + { + switch (obj) + { + case string[] lines: + Lines = lines; + break; + case string line: + Lines = line.Split("\n"); + break; + case JArray _: + Lines = Array.Empty(); + break; + default: + throw new ArgumentException("Unsupported multi-line string type", nameof(obj)); + } + } + + public string[] Lines { get; } } } diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 7d6852021d..4e4fcac80f 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; namespace Exercism.CSharp.Output.Rendering { @@ -13,7 +12,6 @@ public string Object(object val) switch (val) { case string str: return String(str); - case MultiLineString multiLineString: return String(multiLineString.ToString()); case double dbl: return Double(dbl); case int i: return Int(i); case float flt: return Float(flt); diff --git a/generators/Output/Rendering/RenderString.cs b/generators/Output/Rendering/RenderString.cs index 80060a1726..a114bcdb2a 100644 --- a/generators/Output/Rendering/RenderString.cs +++ b/generators/Output/Rendering/RenderString.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Humanizer; @@ -8,19 +9,25 @@ public partial class Render { public UnescapedValue Enum(string enumType, string enumCase) => new UnescapedValue($"{enumType}.{enumCase.ToLower().Dehumanize()}"); - - public string String(string s) => s.EscapeSpecialCharacters().Quote(); public string Char(char c) => $"'{c}'"; + + public string String(string s) => s.EscapeSpecialCharacters().Quote(); - public IEnumerable MultiLineString(string name, string str) + public string StringMultiLine(MultiLineString multiLineString) { - var strings = str.Split('\n'); - var renderedStrings = strings.Select((t, i) => i < strings.Length - 1 - ? $"{String(t + "\n")} +" - : $"{String(t)}"); - - return MultiLineVariable(renderedStrings, name); + if (multiLineString.Lines.Length == 0) + return String(string.Empty); + + if (multiLineString.Lines.Length == 1) + return String(multiLineString.Lines[0]); + + return $"{Environment.NewLine}{string.Join(Environment.NewLine, RenderLines())}"; + + IEnumerable RenderLines() => + multiLineString.Lines.Select((t, i) => i < multiLineString.Lines.Length - 1 + ? $"{String($"{t}\n").Indent()} +" + : $"{String(t).Indent()}"); } } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderVariable.cs b/generators/Output/Rendering/RenderVariable.cs index c6f22314c2..b372bfc9ea 100644 --- a/generators/Output/Rendering/RenderVariable.cs +++ b/generators/Output/Rendering/RenderVariable.cs @@ -14,10 +14,8 @@ public IEnumerable Variable(object val, string name) { switch (val) { - case string str when str.Contains("\n"): - return MultiLineString(name, str); - case MultiLineString multiLineValue when multiLineValue.ToString().Contains("\n"): - return MultiLineString(name, multiLineValue.ToString()); + case MultiLineString multiLineValue: + return new[] { $"var {name} = {StringMultiLine(multiLineValue)};" }; case IEnumerable strings: if (!strings.Any()) { From 291dd130d9c8a60a3ea7a8558a35ce9707a2a64e Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 13:49:29 +0200 Subject: [PATCH 66/97] generators: Simplify binary search tree generator --- .../Exercises/Generators/BinarySearchTree.cs | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 80604d00b4..0288fdb9ee 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -26,9 +26,6 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(IQueryable).Namespace); } - private StringBuilder _testFactCodeLines; - private void AddCodeLine(string line) => _testFactCodeLines.Append(line + "\r\n"); - protected override void UpdateTestMethod(TestMethod method) { method.Assert = RenderAssert(method); @@ -36,39 +33,39 @@ protected override void UpdateTestMethod(TestMethod method) private string RenderAssert(TestMethod method) { - _testFactCodeLines = new StringBuilder(); + var assert = new StringBuilder(); var canonicalDataCase = method.Data; var input = canonicalDataCase.Input as Dictionary; var constructorData = input["treeData"] as string[]; - if (constructorData.Length == 1) AddCodeLine($"var tree = new BinarySearchTree({constructorData[0]});"); + if (constructorData.Length == 1) assert.AppendLine($"var tree = new BinarySearchTree({constructorData[0]});"); else { var constructorDataString = string.Join(", ", constructorData); - AddCodeLine($"var tree = new BinarySearchTree(new[] {{ {constructorDataString} }});"); + assert.AppendLine($"var tree = new BinarySearchTree(new[] {{ {constructorDataString} }});"); } if (canonicalDataCase.Expected is Dictionary expected) { var tree = new ExpectedDataBinaryTree(expected); - foreach (var assert in TestAsserts(tree)) - AddCodeLine(assert); + foreach (var testAssert in TestAsserts(tree)) + assert.AppendLine(testAssert); } else { var expectedNumbers = ((string[]) canonicalDataCase.Expected).Select(int.Parse).ToArray(); var expectedRendered = Render.Object(expectedNumbers); - AddCodeLine(Render.AssertEqual(expectedRendered, "tree.AsEnumerable()")); + assert.AppendLine(Render.AssertEqual(expectedRendered, "tree.AsEnumerable()")); } - return _testFactCodeLines.ToString(); + return assert.ToString(); } private IEnumerable TestAsserts(ExpectedDataBinaryTree tree, string traverse = "") { yield return Render.AssertEqual(tree.Value, $"tree{traverse}.Value"); - if (tree.Left != null) foreach (var assert in TestAsserts(tree.Left, traverse + ".Left")) yield return assert; - if (tree.Right != null) foreach (var assert in TestAsserts(tree.Right, traverse + ".Right")) yield return assert; + if (tree.Left != null) foreach (var assert in TestAsserts(tree.Left, $"{traverse}.Left")) yield return assert; + if (tree.Right != null) foreach (var assert in TestAsserts(tree.Right, $"{traverse}.Right")) yield return assert; } } } \ No newline at end of file From ac0fd06db5a7b5dc596d83e780d776d1b4d825c3 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 13:55:19 +0200 Subject: [PATCH 67/97] generators: Have variable rendering only return single value --- generators/Output/Rendering/RenderVariable.cs | 19 +++++++++++-------- generators/Output/TestMethod.cs | 4 ++-- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/generators/Output/Rendering/RenderVariable.cs b/generators/Output/Rendering/RenderVariable.cs index b372bfc9ea..a4e9a65c7e 100644 --- a/generators/Output/Rendering/RenderVariable.cs +++ b/generators/Output/Rendering/RenderVariable.cs @@ -8,27 +8,30 @@ namespace Exercism.CSharp.Output.Rendering public partial class Render { public IEnumerable Variables(IDictionary dict) - => dict.Keys.SelectMany(key => Variable(dict[key], key.ToVariableName())).ToArray(); + => dict.Select(Variable).ToArray(); - public IEnumerable Variable(object val, string name) + private string Variable(KeyValuePair kv) + => Variable(kv.Key.ToVariableName(), kv.Value); + + public string Variable(string name, object val) { switch (val) { case MultiLineString multiLineValue: - return new[] { $"var {name} = {StringMultiLine(multiLineValue)};" }; + return $"var {name} = {StringMultiLine(multiLineValue)};"; case IEnumerable strings: if (!strings.Any()) { - return new[] { $"var {name} = Array.Empty();" }; + return $"var {name} = Array.Empty();"; } - return MultiLineEnumerable( - strings.Select((str, i) => String(str) + (i < strings.Count() - 1 ? "," : "")), name, "new[]"); + return string.Join(Environment.NewLine, MultiLineEnumerable( + strings.Select((str, i) => String(str) + (i < strings.Count() - 1 ? "," : "")), name, "new[]")); default: if (IsDictionary(val)) - return new[] { $"var {name} = {DictionaryMultiLine((dynamic)val)};" }; + return $"var {name} = {DictionaryMultiLine((dynamic)val)};"; - return new[] { $"var {name} = {Object(val)};" }; + return $"var {name} = {Object(val)};"; } } diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index 99fc9c3c3b..6f3148910c 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -53,8 +53,8 @@ public string Render() private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); + private string ExpectedVariableDeclaration => Renderer.Variable(ExpectedVariableName, Data.Expected); private IEnumerable InputVariablesDeclaration => Renderer.Variables(Input); - private IEnumerable ExpectedVariableDeclaration => Renderer.Variable(Data.Expected, ExpectedVariableName); private IEnumerable ConstructorVariablesDeclaration => Renderer.Variables(ConstructorInput); private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {Data.TestedClass}({ConstructorParameters});" }; private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; @@ -78,7 +78,7 @@ public IEnumerable Variables lines.AddRange(ActualVariableDeclaration); if (Data.UseVariableForExpected) - lines.AddRange(ExpectedVariableDeclaration); + lines.Add(ExpectedVariableDeclaration); return lines; } From 102e033dcca787e4e2ed75081621f03488738875 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 13:58:21 +0200 Subject: [PATCH 68/97] generators: Use Environment.Newline where possible --- generators/Exercises/Generators/OcrNumbers.cs | 20 ++----------------- .../Output/Rendering/RenderDictionary.cs | 5 +++-- generators/Output/Rendering/RenderString.cs | 2 +- 3 files changed, 6 insertions(+), 21 deletions(-) diff --git a/generators/Exercises/Generators/OcrNumbers.cs b/generators/Exercises/Generators/OcrNumbers.cs index f9f4eabfbd..f7463e8ee3 100644 --- a/generators/Exercises/Generators/OcrNumbers.cs +++ b/generators/Exercises/Generators/OcrNumbers.cs @@ -10,29 +10,13 @@ public class OcrNumbers : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.ExceptionThrown = data.Expected is int && data.Expected <= 0 ? typeof(ArgumentException) : null; - data.Input["rows"] = ToDigitStringRepresentation(data.Input["rows"]); + data.ExceptionThrown = data.Expected is int i && i <= 0 ? typeof(ArgumentException) : null; + data.Input["rows"] = new MultiLineString(data.Input["rows"]); data.Expected = data.Expected.ToString(); data.UseVariableForTested = true; data.UseVariablesForInput = true; } - private UnescapedValue ToDigitStringRepresentation(string[] input) - { - var lines = new StringBuilder(); - lines.AppendLine(); - - for (var i = 0; i < input.Length; i++) - { - lines.Append(Render.Object(input[i]).Indent()); - - if (i < input.Length - 1) - lines.Append(" + \"\\n\" +\n"); - } - - return new UnescapedValue(lines.ToString()); - } - protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(Array).Namespace); diff --git a/generators/Output/Rendering/RenderDictionary.cs b/generators/Output/Rendering/RenderDictionary.cs index 9876a355ed..be250ddf3d 100644 --- a/generators/Output/Rendering/RenderDictionary.cs +++ b/generators/Output/Rendering/RenderDictionary.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Helpers; @@ -14,7 +15,7 @@ public string Dictionary(IDictionary dict) => public string DictionaryMultiLine(IDictionary dict) => dict.Count == 0 ? $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>()" - : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>\n{{\n{string.Join(",\n", dict.Select(KeyValueAssignment).Select(assignment => assignment.Indent()))}\n}}"; + : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>{Environment.NewLine}{{{Environment.NewLine}{string.Join($",{Environment.NewLine}", dict.Select(KeyValueAssignment).Select(assignment => assignment.Indent()))}{Environment.NewLine}}}"; private string KeyValueAssignment(KeyValuePair kv) => $"[{Object(kv.Key)}] = {Object(kv.Value)}"; } diff --git a/generators/Output/Rendering/RenderString.cs b/generators/Output/Rendering/RenderString.cs index a114bcdb2a..d80cbe8c4e 100644 --- a/generators/Output/Rendering/RenderString.cs +++ b/generators/Output/Rendering/RenderString.cs @@ -26,7 +26,7 @@ public string StringMultiLine(MultiLineString multiLineString) IEnumerable RenderLines() => multiLineString.Lines.Select((t, i) => i < multiLineString.Lines.Length - 1 - ? $"{String($"{t}\n").Indent()} +" + ? $"{String($"{t}{Environment.NewLine}").Indent()} +" : $"{String(t).Indent()}"); } } From 8257eb73b20ffc95c3c6c57980d0605071e600fc Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 14:01:30 +0200 Subject: [PATCH 69/97] generators: Simplify ocr-numbers generator --- exercises/ocr-numbers/OcrNumbersTest.cs | 116 ++++++++++++------------ 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/exercises/ocr-numbers/OcrNumbersTest.cs b/exercises/ocr-numbers/OcrNumbersTest.cs index 16da4b0dc8..cb55c05e08 100644 --- a/exercises/ocr-numbers/OcrNumbersTest.cs +++ b/exercises/ocr-numbers/OcrNumbersTest.cs @@ -9,9 +9,9 @@ public class OcrNumbersTest public void Recognizes_0() { var rows = - " _ " + "\n" + - "| |" + "\n" + - "|_|" + "\n" + + " _ \n" + + "| |\n" + + "|_|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("0", actual); @@ -21,9 +21,9 @@ public void Recognizes_0() public void Recognizes_1() { var rows = - " " + "\n" + - " |" + "\n" + - " |" + "\n" + + " \n" + + " |\n" + + " |\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("1", actual); @@ -33,9 +33,9 @@ public void Recognizes_1() public void Unreadable_but_correctly_sized_inputs_return_() { var rows = - " " + "\n" + - " _" + "\n" + - " |" + "\n" + + " \n" + + " _\n" + + " |\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("?", actual); @@ -45,8 +45,8 @@ public void Unreadable_but_correctly_sized_inputs_return_() public void Input_with_a_number_of_lines_that_is_not_a_multiple_of_four_raises_an_error() { var rows = - " _ " + "\n" + - "| |" + "\n" + + " _ \n" + + "| |\n" + " "; Assert.Throws(() => OcrNumbers.Convert(rows)); } @@ -55,9 +55,9 @@ public void Input_with_a_number_of_lines_that_is_not_a_multiple_of_four_raises_a public void Input_with_a_number_of_columns_that_is_not_a_multiple_of_three_raises_an_error() { var rows = - " " + "\n" + - " |" + "\n" + - " |" + "\n" + + " \n" + + " |\n" + + " |\n" + " "; Assert.Throws(() => OcrNumbers.Convert(rows)); } @@ -66,9 +66,9 @@ public void Input_with_a_number_of_columns_that_is_not_a_multiple_of_three_raise public void Recognizes_110101100() { var rows = - " _ _ _ _ " + "\n" + - " | || | || | | || || |" + "\n" + - " | ||_| ||_| | ||_||_|" + "\n" + + " _ _ _ _ \n" + + " | || | || | | || || |\n" + + " | ||_| ||_| | ||_||_|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("110101100", actual); @@ -78,9 +78,9 @@ public void Recognizes_110101100() public void Garbled_numbers_in_a_string_are_replaced_with_() { var rows = - " _ _ _ " + "\n" + - " | || | || | || || |" + "\n" + - " | | _| ||_| | ||_||_|" + "\n" + + " _ _ _ \n" + + " | || | || | || || |\n" + + " | | _| ||_| | ||_||_|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("11?10?1?0", actual); @@ -90,9 +90,9 @@ public void Garbled_numbers_in_a_string_are_replaced_with_() public void Recognizes_2() { var rows = - " _ " + "\n" + - " _|" + "\n" + - "|_ " + "\n" + + " _ \n" + + " _|\n" + + "|_ \n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("2", actual); @@ -102,9 +102,9 @@ public void Recognizes_2() public void Recognizes_3() { var rows = - " _ " + "\n" + - " _|" + "\n" + - " _|" + "\n" + + " _ \n" + + " _|\n" + + " _|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("3", actual); @@ -114,9 +114,9 @@ public void Recognizes_3() public void Recognizes_4() { var rows = - " " + "\n" + - "|_|" + "\n" + - " |" + "\n" + + " \n" + + "|_|\n" + + " |\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("4", actual); @@ -126,9 +126,9 @@ public void Recognizes_4() public void Recognizes_5() { var rows = - " _ " + "\n" + - "|_ " + "\n" + - " _|" + "\n" + + " _ \n" + + "|_ \n" + + " _|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("5", actual); @@ -138,9 +138,9 @@ public void Recognizes_5() public void Recognizes_6() { var rows = - " _ " + "\n" + - "|_ " + "\n" + - "|_|" + "\n" + + " _ \n" + + "|_ \n" + + "|_|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("6", actual); @@ -150,9 +150,9 @@ public void Recognizes_6() public void Recognizes_7() { var rows = - " _ " + "\n" + - " |" + "\n" + - " |" + "\n" + + " _ \n" + + " |\n" + + " |\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("7", actual); @@ -162,9 +162,9 @@ public void Recognizes_7() public void Recognizes_8() { var rows = - " _ " + "\n" + - "|_|" + "\n" + - "|_|" + "\n" + + " _ \n" + + "|_|\n" + + "|_|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("8", actual); @@ -174,9 +174,9 @@ public void Recognizes_8() public void Recognizes_9() { var rows = - " _ " + "\n" + - "|_|" + "\n" + - " _|" + "\n" + + " _ \n" + + "|_|\n" + + " _|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("9", actual); @@ -186,9 +186,9 @@ public void Recognizes_9() public void Recognizes_string_of_decimal_numbers() { var rows = - " _ _ _ _ _ _ _ _ " + "\n" + - " | _| _||_||_ |_ ||_||_|| |" + "\n" + - " ||_ _| | _||_| ||_| _||_|" + "\n" + + " _ _ _ _ _ _ _ _ \n" + + " | _| _||_||_ |_ ||_||_|| |\n" + + " ||_ _| | _||_| ||_| _||_|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("1234567890", actual); @@ -198,17 +198,17 @@ public void Recognizes_string_of_decimal_numbers() public void Numbers_separated_by_empty_lines_are_recognized_lines_are_joined_by_commas_() { var rows = - " _ _ " + "\n" + - " | _| _|" + "\n" + - " ||_ _|" + "\n" + - " " + "\n" + - " _ _ " + "\n" + - "|_||_ |_ " + "\n" + - " | _||_|" + "\n" + - " " + "\n" + - " _ _ _ " + "\n" + - " ||_||_|" + "\n" + - " ||_| _|" + "\n" + + " _ _ \n" + + " | _| _|\n" + + " ||_ _|\n" + + " \n" + + " _ _ \n" + + "|_||_ |_ \n" + + " | _||_|\n" + + " \n" + + " _ _ _ \n" + + " ||_||_|\n" + + " ||_| _|\n" + " "; var actual = OcrNumbers.Convert(rows); Assert.Equal("123,456,789", actual); From 4c9d6f5b505f8d18d7a3d604bdd681f290c96b5d Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 14:29:20 +0200 Subject: [PATCH 70/97] generators: Refactor array variable rendering --- exercises/allergies/AllergiesTest.cs | 36 +-- exercises/anagram/AnagramTest.cs | 103 +----- exercises/change/ChangeTest.cs | 19 +- exercises/connect/ConnectTest.cs | 18 +- exercises/dominoes/DominoesTest.cs | 13 +- exercises/grep/GrepTest.cs | 123 ++----- exercises/minesweeper/MinesweeperTest.cs | 160 ++------- .../pascals-triangle/PascalsTriangleTest.cs | 59 +++- exercises/poker/PokerTest.cs | 303 ++++-------------- exercises/pov/PovTest.cs | 36 +-- exercises/proverb/ProverbTest.cs | 5 +- exercises/rectangles/RectanglesTest.cs | 63 +--- exercises/saddle-points/SaddlePointsTest.cs | 28 +- .../scale-generator/ScaleGeneratorTest.cs | 163 +--------- exercises/sieve/SieveTest.cs | 172 +++++++++- exercises/spiral-matrix/SpiralMatrixTest.cs | 35 +- .../VariableLengthQuantityTest.cs | 38 ++- exercises/word-search/WordSearchTest.cs | 101 +----- generators/Exercises/Generators/Dominoes.cs | 1 - generators/Exercises/Generators/OcrNumbers.cs | 1 - generators/Output/Rendering/Render.cs | 17 + generators/Output/Rendering/RenderArray.cs | 36 ++- generators/Output/Rendering/RenderVariable.cs | 28 +- 23 files changed, 562 insertions(+), 996 deletions(-) diff --git a/exercises/allergies/AllergiesTest.cs b/exercises/allergies/AllergiesTest.cs index 4d46cd3b9b..37f0efb6b0 100644 --- a/exercises/allergies/AllergiesTest.cs +++ b/exercises/allergies/AllergiesTest.cs @@ -40,10 +40,7 @@ public void No_allergies_at_all() public void Allergic_to_just_eggs() { var sut = new Allergies(1); - var expected = new[] - { - "eggs" - }; + var expected = new[] { "eggs" }; Assert.Equal(expected, sut.List()); } @@ -51,10 +48,7 @@ public void Allergic_to_just_eggs() public void Allergic_to_just_peanuts() { var sut = new Allergies(2); - var expected = new[] - { - "peanuts" - }; + var expected = new[] { "peanuts" }; Assert.Equal(expected, sut.List()); } @@ -62,10 +56,7 @@ public void Allergic_to_just_peanuts() public void Allergic_to_just_strawberries() { var sut = new Allergies(8); - var expected = new[] - { - "strawberries" - }; + var expected = new[] { "strawberries" }; Assert.Equal(expected, sut.List()); } @@ -73,11 +64,7 @@ public void Allergic_to_just_strawberries() public void Allergic_to_eggs_and_peanuts() { var sut = new Allergies(3); - var expected = new[] - { - "eggs", - "peanuts" - }; + var expected = new[] { "eggs", "peanuts" }; Assert.Equal(expected, sut.List()); } @@ -85,11 +72,7 @@ public void Allergic_to_eggs_and_peanuts() public void Allergic_to_more_than_eggs_but_not_peanuts() { var sut = new Allergies(5); - var expected = new[] - { - "eggs", - "shellfish" - }; + var expected = new[] { "eggs", "shellfish" }; Assert.Equal(expected, sut.List()); } @@ -97,14 +80,7 @@ public void Allergic_to_more_than_eggs_but_not_peanuts() public void Allergic_to_lots_of_stuff() { var sut = new Allergies(248); - var expected = new[] - { - "strawberries", - "tomatoes", - "chocolate", - "pollen", - "cats" - }; + var expected = new[] { "strawberries", "tomatoes", "chocolate", "pollen", "cats" }; Assert.Equal(expected, sut.List()); } diff --git a/exercises/anagram/AnagramTest.cs b/exercises/anagram/AnagramTest.cs index f943df9d6c..6775007db3 100644 --- a/exercises/anagram/AnagramTest.cs +++ b/exercises/anagram/AnagramTest.cs @@ -7,13 +7,7 @@ public class AnagramTest [Fact] public void No_matches() { - var candidates = new[] - { - "hello", - "world", - "zombies", - "pants" - }; + var candidates = new[] { "hello", "world", "zombies", "pants" }; var sut = new Anagram("diaper"); Assert.Empty(sut.Anagrams(candidates)); } @@ -21,29 +15,16 @@ public void No_matches() [Fact(Skip = "Remove to run test")] public void Detects_two_anagrams() { - var candidates = new[] - { - "stream", - "pigeon", - "maters" - }; + var candidates = new[] { "stream", "pigeon", "maters" }; var sut = new Anagram("master"); - var expected = new[] - { - "stream", - "maters" - }; + var expected = new[] { "stream", "maters" }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Does_not_detect_anagram_subsets() { - var candidates = new[] - { - "dog", - "goody" - }; + var candidates = new[] { "dog", "goody" }; var sut = new Anagram("good"); Assert.Empty(sut.Anagrams(candidates)); } @@ -51,18 +32,9 @@ public void Does_not_detect_anagram_subsets() [Fact(Skip = "Remove to run test")] public void Detects_anagram() { - var candidates = new[] - { - "enlists", - "google", - "inlets", - "banana" - }; + var candidates = new[] { "enlists", "google", "inlets", "banana" }; var sut = new Anagram("listen"); - var expected = new[] - { - "inlets" - }; + var expected = new[] { "inlets" }; Assert.Equal(expected, sut.Anagrams(candidates)); } @@ -79,22 +51,14 @@ public void Detects_three_anagrams() "leading" }; var sut = new Anagram("allergy"); - var expected = new[] - { - "gallery", - "regally", - "largely" - }; + var expected = new[] { "gallery", "regally", "largely" }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Does_not_detect_non_anagrams_with_identical_checksum() { - var candidates = new[] - { - "last" - }; + var candidates = new[] { "last" }; var sut = new Anagram("mass"); Assert.Empty(sut.Anagrams(candidates)); } @@ -102,61 +66,34 @@ public void Does_not_detect_non_anagrams_with_identical_checksum() [Fact(Skip = "Remove to run test")] public void Detects_anagrams_case_insensitively() { - var candidates = new[] - { - "cashregister", - "Carthorse", - "radishes" - }; + var candidates = new[] { "cashregister", "Carthorse", "radishes" }; var sut = new Anagram("Orchestra"); - var expected = new[] - { - "Carthorse" - }; + var expected = new[] { "Carthorse" }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Detects_anagrams_using_case_insensitive_subject() { - var candidates = new[] - { - "cashregister", - "carthorse", - "radishes" - }; + var candidates = new[] { "cashregister", "carthorse", "radishes" }; var sut = new Anagram("Orchestra"); - var expected = new[] - { - "carthorse" - }; + var expected = new[] { "carthorse" }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Detects_anagrams_using_case_insensitive_possible_matches() { - var candidates = new[] - { - "cashregister", - "Carthorse", - "radishes" - }; + var candidates = new[] { "cashregister", "Carthorse", "radishes" }; var sut = new Anagram("orchestra"); - var expected = new[] - { - "Carthorse" - }; + var expected = new[] { "Carthorse" }; Assert.Equal(expected, sut.Anagrams(candidates)); } [Fact(Skip = "Remove to run test")] public void Does_not_detect_a_anagram_if_the_original_word_is_repeated() { - var candidates = new[] - { - "go Go GO" - }; + var candidates = new[] { "go Go GO" }; var sut = new Anagram("go"); Assert.Empty(sut.Anagrams(candidates)); } @@ -164,10 +101,7 @@ public void Does_not_detect_a_anagram_if_the_original_word_is_repeated() [Fact(Skip = "Remove to run test")] public void Anagrams_must_use_all_letters_exactly_once() { - var candidates = new[] - { - "patter" - }; + var candidates = new[] { "patter" }; var sut = new Anagram("tapper"); Assert.Empty(sut.Anagrams(candidates)); } @@ -175,10 +109,7 @@ public void Anagrams_must_use_all_letters_exactly_once() [Fact(Skip = "Remove to run test")] public void Capital_word_is_not_own_anagram() { - var candidates = new[] - { - "Banana" - }; + var candidates = new[] { "Banana" }; var sut = new Anagram("BANANA"); Assert.Empty(sut.Anagrams(candidates)); } diff --git a/exercises/change/ChangeTest.cs b/exercises/change/ChangeTest.cs index 9663ad5867..6e58d44197 100644 --- a/exercises/change/ChangeTest.cs +++ b/exercises/change/ChangeTest.cs @@ -46,7 +46,24 @@ public void Large_target_values() { var coins = new[] { 1, 2, 5, 10, 20, 50, 100 }; var target = 999; - var expected = new[] { 2, 2, 5, 20, 20, 50, 100, 100, 100, 100, 100, 100, 100, 100, 100 }; + var expected = new[] + { + 2, + 2, + 5, + 20, + 20, + 50, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100, + 100 + }; Assert.Equal(expected, Change.FindFewestCoins(coins, target)); } diff --git a/exercises/connect/ConnectTest.cs b/exercises/connect/ConnectTest.cs index 6e0da7f075..969b1ab6ba 100644 --- a/exercises/connect/ConnectTest.cs +++ b/exercises/connect/ConnectTest.cs @@ -22,10 +22,7 @@ public void An_empty_board_has_no_winner() [Fact(Skip = "Remove to run test")] public void X_can_win_on_a_1x1_board() { - var board = new[] - { - "X" - }; + var board = new[] { "X" }; var sut = new Connect(board); Assert.Equal(ConnectWinner.Black, sut.Result()); } @@ -33,10 +30,7 @@ public void X_can_win_on_a_1x1_board() [Fact(Skip = "Remove to run test")] public void O_can_win_on_a_1x1_board() { - var board = new[] - { - "O" - }; + var board = new[] { "O" }; var sut = new Connect(board); Assert.Equal(ConnectWinner.White, sut.Result()); } @@ -44,13 +38,7 @@ public void O_can_win_on_a_1x1_board() [Fact(Skip = "Remove to run test")] public void Only_edges_does_not_make_a_winner() { - var board = new[] - { - "O O O X", - " X . . X", - " X . . X", - " X O O O" - }; + var board = new[] { "O O O X", " X . . X", " X . . X", " X O O O" }; var sut = new Connect(board); Assert.Equal(ConnectWinner.None, sut.Result()); } diff --git a/exercises/dominoes/DominoesTest.cs b/exercises/dominoes/DominoesTest.cs index c8fe30e196..b1b0bc70f4 100644 --- a/exercises/dominoes/DominoesTest.cs +++ b/exercises/dominoes/DominoesTest.cs @@ -85,7 +85,18 @@ public void Separate_loops() [Fact(Skip = "Remove to run test")] public void Nine_elements() { - var dominoes = new[] { (1, 2), (5, 3), (3, 1), (1, 2), (2, 4), (1, 6), (2, 3), (3, 4), (5, 6) }; + var dominoes = new[] + { + (1, 2), + (5, 3), + (3, 1), + (1, 2), + (2, 4), + (1, 6), + (2, 3), + (3, 4), + (5, 6) + }; Assert.True(Dominoes.CanChain(dominoes)); } } \ No newline at end of file diff --git a/exercises/grep/GrepTest.cs b/exercises/grep/GrepTest.cs index 7cb9de6d9f..5576c9f93d 100644 --- a/exercises/grep/GrepTest.cs +++ b/exercises/grep/GrepTest.cs @@ -11,10 +11,7 @@ public void One_file_one_match_no_flags() { var pattern = "Agamemnon"; var flags = ""; - var files = new[] - { - "iliad.txt" - }; + var files = new[] { "iliad.txt" }; var expected = "Of Atreus, Agamemnon, King of men.\n"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); @@ -25,10 +22,7 @@ public void One_file_one_match_print_line_numbers_flag() { var pattern = "Forbidden"; var flags = "-n"; - var files = new[] - { - "paradise-lost.txt" - }; + var files = new[] { "paradise-lost.txt" }; var expected = "2:Of that Forbidden Tree, whose mortal tast\n"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); @@ -39,10 +33,7 @@ public void One_file_one_match_case_insensitive_flag() { var pattern = "FORBIDDEN"; var flags = "-i"; - var files = new[] - { - "paradise-lost.txt" - }; + var files = new[] { "paradise-lost.txt" }; var expected = "Of that Forbidden Tree, whose mortal tast\n"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); @@ -53,10 +44,7 @@ public void One_file_one_match_print_file_names_flag() { var pattern = "Forbidden"; var flags = "-l"; - var files = new[] - { - "paradise-lost.txt" - }; + var files = new[] { "paradise-lost.txt" }; var expected = "paradise-lost.txt\n"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); @@ -67,10 +55,7 @@ public void One_file_one_match_match_entire_lines_flag() { var pattern = "With loss of Eden, till one greater Man"; var flags = "-x"; - var files = new[] - { - "paradise-lost.txt" - }; + var files = new[] { "paradise-lost.txt" }; var expected = "With loss of Eden, till one greater Man\n"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); @@ -81,10 +66,7 @@ public void One_file_one_match_multiple_flags() { var pattern = "OF ATREUS, Agamemnon, KIng of MEN."; var flags = "-n -i -x"; - var files = new[] - { - "iliad.txt" - }; + var files = new[] { "iliad.txt" }; var expected = "9:Of Atreus, Agamemnon, King of men.\n"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); @@ -95,10 +77,7 @@ public void One_file_several_matches_no_flags() { var pattern = "may"; var flags = ""; - var files = new[] - { - "midsummer-night.txt" - }; + var files = new[] { "midsummer-night.txt" }; var expected = "Nor how it may concern my modesty,\n" + "But I beseech your grace that I may know\n" + @@ -111,10 +90,7 @@ public void One_file_several_matches_print_line_numbers_flag() { var pattern = "may"; var flags = "-n"; - var files = new[] - { - "midsummer-night.txt" - }; + var files = new[] { "midsummer-night.txt" }; var expected = "3:Nor how it may concern my modesty,\n" + "5:But I beseech your grace that I may know\n" + @@ -127,10 +103,7 @@ public void One_file_several_matches_match_entire_lines_flag() { var pattern = "may"; var flags = "-x"; - var files = new[] - { - "midsummer-night.txt" - }; + var files = new[] { "midsummer-night.txt" }; var expected = ""; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -140,10 +113,7 @@ public void One_file_several_matches_case_insensitive_flag() { var pattern = "ACHILLES"; var flags = "-i"; - var files = new[] - { - "iliad.txt" - }; + var files = new[] { "iliad.txt" }; var expected = "Achilles sing, O Goddess! Peleus' son;\n" + "The noble Chief Achilles from the son\n"; @@ -155,10 +125,7 @@ public void One_file_several_matches_inverted_flag() { var pattern = "Of"; var flags = "-v"; - var files = new[] - { - "paradise-lost.txt" - }; + var files = new[] { "paradise-lost.txt" }; var expected = "Brought Death into the World, and all our woe,\n" + "With loss of Eden, till one greater Man\n" + @@ -173,10 +140,7 @@ public void One_file_no_matches_various_flags() { var pattern = "Gandalf"; var flags = "-n -l -x -i"; - var files = new[] - { - "iliad.txt" - }; + var files = new[] { "iliad.txt" }; var expected = ""; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -186,12 +150,7 @@ public void Multiple_files_one_match_no_flags() { var pattern = "Agamemnon"; var flags = ""; - var files = new[] - { - "iliad.txt", - "midsummer-night.txt", - "paradise-lost.txt" - }; + var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "iliad.txt:Of Atreus, Agamemnon, King of men.\n"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); @@ -202,12 +161,7 @@ public void Multiple_files_several_matches_no_flags() { var pattern = "may"; var flags = ""; - var files = new[] - { - "iliad.txt", - "midsummer-night.txt", - "paradise-lost.txt" - }; + var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "midsummer-night.txt:Nor how it may concern my modesty,\n" + "midsummer-night.txt:But I beseech your grace that I may know\n" + @@ -220,12 +174,7 @@ public void Multiple_files_several_matches_print_line_numbers_flag() { var pattern = "that"; var flags = "-n"; - var files = new[] - { - "iliad.txt", - "midsummer-night.txt", - "paradise-lost.txt" - }; + var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "midsummer-night.txt:5:But I beseech your grace that I may know\n" + "midsummer-night.txt:6:The worst that may befall me in this case,\n" + @@ -239,12 +188,7 @@ public void Multiple_files_one_match_print_file_names_flag() { var pattern = "who"; var flags = "-l"; - var files = new[] - { - "iliad.txt", - "midsummer-night.txt", - "paradise-lost.txt" - }; + var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "iliad.txt\n" + "paradise-lost.txt\n"; @@ -256,12 +200,7 @@ public void Multiple_files_several_matches_case_insensitive_flag() { var pattern = "TO"; var flags = "-i"; - var files = new[] - { - "iliad.txt", - "midsummer-night.txt", - "paradise-lost.txt" - }; + var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "iliad.txt:Caused to Achaia's host, sent many a soul\n" + "iliad.txt:Illustrious into Ades premature,\n" + @@ -281,12 +220,7 @@ public void Multiple_files_several_matches_inverted_flag() { var pattern = "a"; var flags = "-v"; - var files = new[] - { - "iliad.txt", - "midsummer-night.txt", - "paradise-lost.txt" - }; + var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "iliad.txt:Achilles sing, O Goddess! Peleus' son;\n" + "iliad.txt:The noble Chief Achilles from the son\n" + @@ -299,12 +233,7 @@ public void Multiple_files_one_match_match_entire_lines_flag() { var pattern = "But I beseech your grace that I may know"; var flags = "-x"; - var files = new[] - { - "iliad.txt", - "midsummer-night.txt", - "paradise-lost.txt" - }; + var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "midsummer-night.txt:But I beseech your grace that I may know\n"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); @@ -315,12 +244,7 @@ public void Multiple_files_one_match_multiple_flags() { var pattern = "WITH LOSS OF EDEN, TILL ONE GREATER MAN"; var flags = "-n -i -x"; - var files = new[] - { - "iliad.txt", - "midsummer-night.txt", - "paradise-lost.txt" - }; + var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "paradise-lost.txt:4:With loss of Eden, till one greater Man\n"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); @@ -331,12 +255,7 @@ public void Multiple_files_no_matches_various_flags() { var pattern = "Frodo"; var flags = "-n -l -x -i"; - var files = new[] - { - "iliad.txt", - "midsummer-night.txt", - "paradise-lost.txt" - }; + var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = ""; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } diff --git a/exercises/minesweeper/MinesweeperTest.cs b/exercises/minesweeper/MinesweeperTest.cs index 422b386b76..ea37117527 100644 --- a/exercises/minesweeper/MinesweeperTest.cs +++ b/exercises/minesweeper/MinesweeperTest.cs @@ -15,204 +15,88 @@ public void No_rows() [Fact(Skip = "Remove to run test")] public void No_columns() { - var minefield = new[] - { - "" - }; - var expected = new[] - { - "" - }; + var minefield = new[] { "" }; + var expected = new[] { "" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void No_mines() { - var minefield = new[] - { - " ", - " ", - " " - }; - var expected = new[] - { - " ", - " ", - " " - }; + var minefield = new[] { " ", " ", " " }; + var expected = new[] { " ", " ", " " }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void Minefield_with_only_mines() { - var minefield = new[] - { - "***", - "***", - "***" - }; - var expected = new[] - { - "***", - "***", - "***" - }; + var minefield = new[] { "***", "***", "***" }; + var expected = new[] { "***", "***", "***" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void Mine_surrounded_by_spaces() { - var minefield = new[] - { - " ", - " * ", - " " - }; - var expected = new[] - { - "111", - "1*1", - "111" - }; + var minefield = new[] { " ", " * ", " " }; + var expected = new[] { "111", "1*1", "111" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void Space_surrounded_by_mines() { - var minefield = new[] - { - "***", - "* *", - "***" - }; - var expected = new[] - { - "***", - "*8*", - "***" - }; + var minefield = new[] { "***", "* *", "***" }; + var expected = new[] { "***", "*8*", "***" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void Horizontal_line() { - var minefield = new[] - { - " * * " - }; - var expected = new[] - { - "1*2*1" - }; + var minefield = new[] { " * * " }; + var expected = new[] { "1*2*1" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void Horizontal_line_mines_at_edges() { - var minefield = new[] - { - "* *" - }; - var expected = new[] - { - "*1 1*" - }; + var minefield = new[] { "* *" }; + var expected = new[] { "*1 1*" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void Vertical_line() { - var minefield = new[] - { - " ", - "*", - " ", - "*", - " " - }; - var expected = new[] - { - "1", - "*", - "2", - "*", - "1" - }; + var minefield = new[] { " ", "*", " ", "*", " " }; + var expected = new[] { "1", "*", "2", "*", "1" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void Vertical_line_mines_at_edges() { - var minefield = new[] - { - "*", - " ", - " ", - " ", - "*" - }; - var expected = new[] - { - "*", - "1", - " ", - "1", - "*" - }; + var minefield = new[] { "*", " ", " ", " ", "*" }; + var expected = new[] { "*", "1", " ", "1", "*" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void Cross() { - var minefield = new[] - { - " * ", - " * ", - "*****", - " * ", - " * " - }; - var expected = new[] - { - " 2*2 ", - "25*52", - "*****", - "25*52", - " 2*2 " - }; + var minefield = new[] { " * ", " * ", "*****", " * ", " * " }; + var expected = new[] { " 2*2 ", "25*52", "*****", "25*52", " 2*2 " }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] public void Large_minefield() { - var minefield = new[] - { - " * * ", - " * ", - " * ", - " * *", - " * * ", - " " - }; - var expected = new[] - { - "1*22*1", - "12*322", - " 123*2", - "112*4*", - "1*22*2", - "111111" - }; + var minefield = new[] { " * * ", " * ", " * ", " * *", " * * ", " " }; + var expected = new[] { "1*22*1", "12*322", " 123*2", "112*4*", "1*22*2", "111111" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } } \ No newline at end of file diff --git a/exercises/pascals-triangle/PascalsTriangleTest.cs b/exercises/pascals-triangle/PascalsTriangleTest.cs index 81e5fc93bc..2034d549fe 100644 --- a/exercises/pascals-triangle/PascalsTriangleTest.cs +++ b/exercises/pascals-triangle/PascalsTriangleTest.cs @@ -14,49 +14,94 @@ public void Zero_rows() [Fact(Skip = "Remove to run test")] public void Single_row() { - var expected = new[] { new[] { 1 } }; + var expected = new[] + { + new[] { 1 } + }; Assert.Equal(expected, PascalsTriangle.Calculate(1)); } [Fact(Skip = "Remove to run test")] public void Two_rows() { - var expected = new[] { new[] { 1 }, new[] { 1, 1 } }; + var expected = new[] + { + new[] { 1 }, + new[] { 1, 1 } + }; Assert.Equal(expected, PascalsTriangle.Calculate(2)); } [Fact(Skip = "Remove to run test")] public void Three_rows() { - var expected = new[] { new[] { 1 }, new[] { 1, 1 }, new[] { 1, 2, 1 } }; + var expected = new[] + { + new[] { 1 }, + new[] { 1, 1 }, + new[] { 1, 2, 1 } + }; Assert.Equal(expected, PascalsTriangle.Calculate(3)); } [Fact(Skip = "Remove to run test")] public void Four_rows() { - var expected = new[] { new[] { 1 }, new[] { 1, 1 }, new[] { 1, 2, 1 }, new[] { 1, 3, 3, 1 } }; + var expected = new[] + { + new[] { 1 }, + new[] { 1, 1 }, + new[] { 1, 2, 1 }, + new[] { 1, 3, 3, 1 } + }; Assert.Equal(expected, PascalsTriangle.Calculate(4)); } [Fact(Skip = "Remove to run test")] public void Five_rows() { - var expected = new[] { new[] { 1 }, new[] { 1, 1 }, new[] { 1, 2, 1 }, new[] { 1, 3, 3, 1 }, new[] { 1, 4, 6, 4, 1 } }; + var expected = new[] + { + new[] { 1 }, + new[] { 1, 1 }, + new[] { 1, 2, 1 }, + new[] { 1, 3, 3, 1 }, + new[] { 1, 4, 6, 4, 1 } + }; Assert.Equal(expected, PascalsTriangle.Calculate(5)); } [Fact(Skip = "Remove to run test")] public void Six_rows() { - var expected = new[] { new[] { 1 }, new[] { 1, 1 }, new[] { 1, 2, 1 }, new[] { 1, 3, 3, 1 }, new[] { 1, 4, 6, 4, 1 }, new[] { 1, 5, 10, 10, 5, 1 } }; + var expected = new[] + { + new[] { 1 }, + new[] { 1, 1 }, + new[] { 1, 2, 1 }, + new[] { 1, 3, 3, 1 }, + new[] { 1, 4, 6, 4, 1 }, + new[] { 1, 5, 10, 10, 5, 1 } + }; Assert.Equal(expected, PascalsTriangle.Calculate(6)); } [Fact(Skip = "Remove to run test")] public void Ten_rows() { - var expected = new[] { new[] { 1 }, new[] { 1, 1 }, new[] { 1, 2, 1 }, new[] { 1, 3, 3, 1 }, new[] { 1, 4, 6, 4, 1 }, new[] { 1, 5, 10, 10, 5, 1 }, new[] { 1, 6, 15, 20, 15, 6, 1 }, new[] { 1, 7, 21, 35, 35, 21, 7, 1 }, new[] { 1, 8, 28, 56, 70, 56, 28, 8, 1 }, new[] { 1, 9, 36, 84, 126, 126, 84, 36, 9, 1 } }; + var expected = new[] + { + new[] { 1 }, + new[] { 1, 1 }, + new[] { 1, 2, 1 }, + new[] { 1, 3, 3, 1 }, + new[] { 1, 4, 6, 4, 1 }, + new[] { 1, 5, 10, 10, 5, 1 }, + new[] { 1, 6, 15, 20, 15, 6, 1 }, + new[] { 1, 7, 21, 35, 35, 21, 7, 1 }, + new[] { 1, 8, 28, 56, 70, 56, 28, 8, 1 }, + new[] { 1, 9, 36, 84, 126, 126, 84, 36, 9, 1 } + }; Assert.Equal(expected, PascalsTriangle.Calculate(10)); } diff --git a/exercises/poker/PokerTest.cs b/exercises/poker/PokerTest.cs index 8428d26757..5ac37e2ea2 100644 --- a/exercises/poker/PokerTest.cs +++ b/exercises/poker/PokerTest.cs @@ -7,32 +7,18 @@ public class PokerTest [Fact] public void Single_hand_always_wins() { - var hands = new[] - { - "4S 5S 7H 8D JC" - }; + var hands = new[] { "4S 5S 7H 8D JC" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "4S 5S 7H 8D JC" - }; + var expected = new[] { "4S 5S 7H 8D JC" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Highest_card_out_of_all_hands_wins() { - var hands = new[] - { - "4D 5S 6S 8D 3C", - "2S 4C 7S 9H 10H", - "3S 4S 5D 6H JH" - }; + var hands = new[] { "4D 5S 6S 8D 3C", "2S 4C 7S 9H 10H", "3S 4S 5D 6H JH" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "3S 4S 5D 6H JH" - }; + var expected = new[] { "3S 4S 5D 6H JH" }; Assert.Equal(expected, actual); } @@ -47,411 +33,232 @@ public void A_tie_has_multiple_winners() "3H 4H 5C 6C JD" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "3S 4S 5D 6H JH", - "3H 4H 5C 6C JD" - }; + var expected = new[] { "3S 4S 5D 6H JH", "3H 4H 5C 6C JD" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Multiple_hands_with_the_same_high_cards_tie_compares_next_highest_ranked_down_to_last_card() { - var hands = new[] - { - "3S 5H 6S 8D 7H", - "2S 5D 6D 8C 7S" - }; + var hands = new[] { "3S 5H 6S 8D 7H", "2S 5D 6D 8C 7S" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "3S 5H 6S 8D 7H" - }; + var expected = new[] { "3S 5H 6S 8D 7H" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void One_pair_beats_high_card() { - var hands = new[] - { - "4S 5H 6C 8D KH", - "2S 4H 6S 4D JH" - }; + var hands = new[] { "4S 5H 6C 8D KH", "2S 4H 6S 4D JH" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "2S 4H 6S 4D JH" - }; + var expected = new[] { "2S 4H 6S 4D JH" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Highest_pair_wins() { - var hands = new[] - { - "4S 2H 6S 2D JH", - "2S 4H 6C 4D JD" - }; + var hands = new[] { "4S 2H 6S 2D JH", "2S 4H 6C 4D JD" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "2S 4H 6C 4D JD" - }; + var expected = new[] { "2S 4H 6C 4D JD" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Two_pairs_beats_one_pair() { - var hands = new[] - { - "2S 8H 6S 8D JH", - "4S 5H 4C 8C 5C" - }; + var hands = new[] { "2S 8H 6S 8D JH", "4S 5H 4C 8C 5C" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "4S 5H 4C 8C 5C" - }; + var expected = new[] { "4S 5H 4C 8C 5C" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_two_pairs_highest_ranked_pair_wins() { - var hands = new[] - { - "2S 8H 2D 8D 3H", - "4S 5H 4C 8S 5D" - }; + var hands = new[] { "2S 8H 2D 8D 3H", "4S 5H 4C 8S 5D" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "2S 8H 2D 8D 3H" - }; + var expected = new[] { "2S 8H 2D 8D 3H" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_two_pairs_with_the_same_highest_ranked_pair_tie_goes_to_low_pair() { - var hands = new[] - { - "2S QS 2C QD JH", - "JD QH JS 8D QC" - }; + var hands = new[] { "2S QS 2C QD JH", "JD QH JS 8D QC" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "JD QH JS 8D QC" - }; + var expected = new[] { "JD QH JS 8D QC" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_two_identically_ranked_pairs_tie_goes_to_remaining_card_kicker_() { - var hands = new[] - { - "JD QH JS 8D QC", - "JS QS JC 2D QD" - }; + var hands = new[] { "JD QH JS 8D QC", "JS QS JC 2D QD" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "JD QH JS 8D QC" - }; + var expected = new[] { "JD QH JS 8D QC" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Three_of_a_kind_beats_two_pair() { - var hands = new[] - { - "2S 8H 2H 8D JH", - "4S 5H 4C 8S 4H" - }; + var hands = new[] { "2S 8H 2H 8D JH", "4S 5H 4C 8S 4H" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "4S 5H 4C 8S 4H" - }; + var expected = new[] { "4S 5H 4C 8S 4H" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_three_of_a_kind_tie_goes_to_highest_ranked_triplet() { - var hands = new[] - { - "2S 2H 2C 8D JH", - "4S AH AS 8C AD" - }; + var hands = new[] { "2S 2H 2C 8D JH", "4S AH AS 8C AD" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "4S AH AS 8C AD" - }; + var expected = new[] { "4S AH AS 8C AD" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void With_multiple_decks_two_players_can_have_same_three_of_a_kind_ties_go_to_highest_remaining_cards() { - var hands = new[] - { - "4S AH AS 7C AD", - "4S AH AS 8C AD" - }; + var hands = new[] { "4S AH AS 7C AD", "4S AH AS 8C AD" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "4S AH AS 8C AD" - }; + var expected = new[] { "4S AH AS 8C AD" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void A_straight_beats_three_of_a_kind() { - var hands = new[] - { - "4S 5H 4C 8D 4H", - "3S 4D 2S 6D 5C" - }; + var hands = new[] { "4S 5H 4C 8D 4H", "3S 4D 2S 6D 5C" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "3S 4D 2S 6D 5C" - }; + var expected = new[] { "3S 4D 2S 6D 5C" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Aces_can_end_a_straight_10_j_q_k_a_() { - var hands = new[] - { - "4S 5H 4C 8D 4H", - "10D JH QS KD AC" - }; + var hands = new[] { "4S 5H 4C 8D 4H", "10D JH QS KD AC" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "10D JH QS KD AC" - }; + var expected = new[] { "10D JH QS KD AC" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Aces_can_start_a_straight_a_2_3_4_5_() { - var hands = new[] - { - "4S 5H 4C 8D 4H", - "4D AH 3S 2D 5C" - }; + var hands = new[] { "4S 5H 4C 8D 4H", "4D AH 3S 2D 5C" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "4D AH 3S 2D 5C" - }; + var expected = new[] { "4D AH 3S 2D 5C" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_with_a_straight_tie_goes_to_highest_ranked_card() { - var hands = new[] - { - "4S 6C 7S 8D 5H", - "5S 7H 8S 9D 6H" - }; + var hands = new[] { "4S 6C 7S 8D 5H", "5S 7H 8S 9D 6H" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "5S 7H 8S 9D 6H" - }; + var expected = new[] { "5S 7H 8S 9D 6H" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Even_though_an_ace_is_usually_high_a_5_high_straight_is_the_lowest_scoring_straight() { - var hands = new[] - { - "2H 3C 4D 5D 6H", - "4S AH 3S 2D 5H" - }; + var hands = new[] { "2H 3C 4D 5D 6H", "4S AH 3S 2D 5H" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "2H 3C 4D 5D 6H" - }; + var expected = new[] { "2H 3C 4D 5D 6H" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Flush_beats_a_straight() { - var hands = new[] - { - "4C 6H 7D 8D 5H", - "2S 4S 5S 6S 7S" - }; + var hands = new[] { "4C 6H 7D 8D 5H", "2S 4S 5S 6S 7S" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "2S 4S 5S 6S 7S" - }; + var expected = new[] { "2S 4S 5S 6S 7S" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_a_flush_tie_goes_to_high_card_down_to_the_last_one_if_necessary() { - var hands = new[] - { - "4H 7H 8H 9H 6H", - "2S 4S 5S 6S 7S" - }; + var hands = new[] { "4H 7H 8H 9H 6H", "2S 4S 5S 6S 7S" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "4H 7H 8H 9H 6H" - }; + var expected = new[] { "4H 7H 8H 9H 6H" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Full_house_beats_a_flush() { - var hands = new[] - { - "3H 6H 7H 8H 5H", - "4S 5H 4C 5D 4H" - }; + var hands = new[] { "3H 6H 7H 8H 5H", "4S 5H 4C 5D 4H" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "4S 5H 4C 5D 4H" - }; + var expected = new[] { "4S 5H 4C 5D 4H" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_a_full_house_tie_goes_to_highest_ranked_triplet() { - var hands = new[] - { - "4H 4S 4D 9S 9D", - "5H 5S 5D 8S 8D" - }; + var hands = new[] { "4H 4S 4D 9S 9D", "5H 5S 5D 8S 8D" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "5H 5S 5D 8S 8D" - }; + var expected = new[] { "5H 5S 5D 8S 8D" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void With_multiple_decks_both_hands_have_a_full_house_with_the_same_triplet_tie_goes_to_the_pair() { - var hands = new[] - { - "5H 5S 5D 9S 9D", - "5H 5S 5D 8S 8D" - }; + var hands = new[] { "5H 5S 5D 9S 9D", "5H 5S 5D 8S 8D" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "5H 5S 5D 9S 9D" - }; + var expected = new[] { "5H 5S 5D 9S 9D" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Four_of_a_kind_beats_a_full_house() { - var hands = new[] - { - "4S 5H 4D 5D 4H", - "3S 3H 2S 3D 3C" - }; + var hands = new[] { "4S 5H 4D 5D 4H", "3S 3H 2S 3D 3C" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "3S 3H 2S 3D 3C" - }; + var expected = new[] { "3S 3H 2S 3D 3C" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_four_of_a_kind_tie_goes_to_high_quad() { - var hands = new[] - { - "2S 2H 2C 8D 2D", - "4S 5H 5S 5D 5C" - }; + var hands = new[] { "2S 2H 2C 8D 2D", "4S 5H 5S 5D 5C" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "4S 5H 5S 5D 5C" - }; + var expected = new[] { "4S 5H 5S 5D 5C" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void With_multiple_decks_both_hands_with_identical_four_of_a_kind_tie_determined_by_kicker() { - var hands = new[] - { - "3S 3H 2S 3D 3C", - "3S 3H 4S 3D 3C" - }; + var hands = new[] { "3S 3H 2S 3D 3C", "3S 3H 4S 3D 3C" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "3S 3H 4S 3D 3C" - }; + var expected = new[] { "3S 3H 4S 3D 3C" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Straight_flush_beats_four_of_a_kind() { - var hands = new[] - { - "4S 5H 5S 5D 5C", - "7S 8S 9S 6S 10S" - }; + var hands = new[] { "4S 5H 5S 5D 5C", "7S 8S 9S 6S 10S" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "7S 8S 9S 6S 10S" - }; + var expected = new[] { "7S 8S 9S 6S 10S" }; Assert.Equal(expected, actual); } [Fact(Skip = "Remove to run test")] public void Both_hands_have_straight_flush_tie_goes_to_highest_ranked_card() { - var hands = new[] - { - "4H 6H 7H 8H 5H", - "5S 7S 8S 9S 6S" - }; + var hands = new[] { "4H 6H 7H 8H 5H", "5S 7S 8S 9S 6S" }; var actual = Poker.BestHands(hands); - var expected = new[] - { - "5S 7S 8S 9S 6S" - }; + var expected = new[] { "5S 7S 8S 9S 6S" }; Assert.Equal(expected, actual); } } \ No newline at end of file diff --git a/exercises/pov/PovTest.cs b/exercises/pov/PovTest.cs index acfc683f46..58dab05582 100644 --- a/exercises/pov/PovTest.cs +++ b/exercises/pov/PovTest.cs @@ -81,11 +81,7 @@ public void Can_find_path_to_parent() var from = "x"; var to = "parent"; var tree = new Tree("parent", new Tree("x"), new Tree("sibling")); - var expected = new[] - { - "x", - "parent" - }; + var expected = new[] { "x", "parent" }; Assert.Equal(expected, Pov.PathTo(from, to, tree)); } @@ -95,12 +91,7 @@ public void Can_find_path_to_sibling() var from = "x"; var to = "b"; var tree = new Tree("parent", new Tree("a"), new Tree("x"), new Tree("b"), new Tree("c")); - var expected = new[] - { - "x", - "parent", - "b" - }; + var expected = new[] { "x", "parent", "b" }; Assert.Equal(expected, Pov.PathTo(from, to, tree)); } @@ -110,14 +101,7 @@ public void Can_find_path_to_cousin() var from = "x"; var to = "cousin-1"; var tree = new Tree("grandparent", new Tree("parent", new Tree("x", new Tree("kid-0"), new Tree("kid-1")), new Tree("sibling-0"), new Tree("sibling-1")), new Tree("uncle", new Tree("cousin-0"), new Tree("cousin-1"))); - var expected = new[] - { - "x", - "parent", - "grandparent", - "uncle", - "cousin-1" - }; + var expected = new[] { "x", "parent", "grandparent", "uncle", "cousin-1" }; Assert.Equal(expected, Pov.PathTo(from, to, tree)); } @@ -127,12 +111,7 @@ public void Can_find_path_not_involving_root() var from = "x"; var to = "sibling-1"; var tree = new Tree("grandparent", new Tree("parent", new Tree("x"), new Tree("sibling-0"), new Tree("sibling-1"))); - var expected = new[] - { - "x", - "parent", - "sibling-1" - }; + var expected = new[] { "x", "parent", "sibling-1" }; Assert.Equal(expected, Pov.PathTo(from, to, tree)); } @@ -142,12 +121,7 @@ public void Can_find_path_from_nodes_other_than_x() var from = "a"; var to = "c"; var tree = new Tree("parent", new Tree("a"), new Tree("x"), new Tree("b"), new Tree("c")); - var expected = new[] - { - "a", - "parent", - "c" - }; + var expected = new[] { "a", "parent", "c" }; Assert.Equal(expected, Pov.PathTo(from, to, tree)); } diff --git a/exercises/proverb/ProverbTest.cs b/exercises/proverb/ProverbTest.cs index af7371410e..c094d74e73 100644 --- a/exercises/proverb/ProverbTest.cs +++ b/exercises/proverb/ProverbTest.cs @@ -14,10 +14,7 @@ public void Zero_pieces() [Fact(Skip = "Remove to run test")] public void One_piece() { - var expected = new[] - { - "And all for the want of a nail." - }; + var expected = new[] { "And all for the want of a nail." }; Assert.Equal(expected, Proverb.Recite(new[] { "nail" })); } diff --git a/exercises/rectangles/RectanglesTest.cs b/exercises/rectangles/RectanglesTest.cs index d94f27fb90..c99186a6c7 100644 --- a/exercises/rectangles/RectanglesTest.cs +++ b/exercises/rectangles/RectanglesTest.cs @@ -15,108 +15,63 @@ public void No_rows() [Fact(Skip = "Remove to run test")] public void No_columns() { - var strings = new[] - { - "" - }; + var strings = new[] { "" }; Assert.Equal(0, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void No_rectangles() { - var strings = new[] - { - " " - }; + var strings = new[] { " " }; Assert.Equal(0, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void One_rectangle() { - var strings = new[] - { - "+-+", - "| |", - "+-+" - }; + var strings = new[] { "+-+", "| |", "+-+" }; Assert.Equal(1, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Two_rectangles_without_shared_parts() { - var strings = new[] - { - " +-+", - " | |", - "+-+-+", - "| | ", - "+-+ " - }; + var strings = new[] { " +-+", " | |", "+-+-+", "| | ", "+-+ " }; Assert.Equal(2, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Five_rectangles_with_shared_parts() { - var strings = new[] - { - " +-+", - " | |", - "+-+-+", - "| | |", - "+-+-+" - }; + var strings = new[] { " +-+", " | |", "+-+-+", "| | |", "+-+-+" }; Assert.Equal(5, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Rectangle_of_height_1_is_counted() { - var strings = new[] - { - "+--+", - "+--+" - }; + var strings = new[] { "+--+", "+--+" }; Assert.Equal(1, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Rectangle_of_width_1_is_counted() { - var strings = new[] - { - "++", - "||", - "++" - }; + var strings = new[] { "++", "||", "++" }; Assert.Equal(1, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Number_1x1_square_is_counted() { - var strings = new[] - { - "++", - "++" - }; + var strings = new[] { "++", "++" }; Assert.Equal(1, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Only_complete_rectangles_are_counted() { - var strings = new[] - { - " +-+", - " |", - "+-+-+", - "| | -", - "+-+-+" - }; + var strings = new[] { " +-+", " |", "+-+-+", "| | -", "+-+-+" }; Assert.Equal(1, Rectangles.Count(strings)); } diff --git a/exercises/saddle-points/SaddlePointsTest.cs b/exercises/saddle-points/SaddlePointsTest.cs index 10d2be2e99..49090f00e2 100644 --- a/exercises/saddle-points/SaddlePointsTest.cs +++ b/exercises/saddle-points/SaddlePointsTest.cs @@ -8,7 +8,12 @@ public class SaddlePointsTest [Fact] public void Can_identify_single_saddle_point() { - var matrix = new[,] { { 9, 8, 7 }, { 5, 3, 2 }, { 6, 6, 7 } }; + var matrix = new[,] + { + { 9, 8, 7 }, + { 5, 3, 2 }, + { 6, 6, 7 } + }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); var expected = new[] { (1, 0) }; @@ -27,7 +32,12 @@ public void Can_identify_that_empty_matrix_has_no_saddle_points() [Fact(Skip = "Remove to run test")] public void Can_identify_lack_of_saddle_points_when_there_are_none() { - var matrix = new[,] { { 1, 2, 3 }, { 3, 1, 2 }, { 2, 3, 1 } }; + var matrix = new[,] + { + { 1, 2, 3 }, + { 3, 1, 2 }, + { 2, 3, 1 } + }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); Assert.Empty(actual); @@ -36,7 +46,12 @@ public void Can_identify_lack_of_saddle_points_when_there_are_none() [Fact(Skip = "Remove to run test")] public void Can_identify_multiple_saddle_points() { - var matrix = new[,] { { 4, 5, 4 }, { 3, 5, 5 }, { 1, 5, 4 } }; + var matrix = new[,] + { + { 4, 5, 4 }, + { 3, 5, 5 }, + { 1, 5, 4 } + }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); var expected = new[] { (0, 1), (1, 1), (2, 1) }; @@ -46,7 +61,12 @@ public void Can_identify_multiple_saddle_points() [Fact(Skip = "Remove to run test")] public void Can_identify_saddle_point_in_bottom_right_corner() { - var matrix = new[,] { { 8, 7, 9 }, { 6, 7, 6 }, { 3, 2, 5 } }; + var matrix = new[,] + { + { 8, 7, 9 }, + { 6, 7, 6 }, + { 3, 2, 5 } + }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); var expected = new[] { (2, 2) }; diff --git a/exercises/scale-generator/ScaleGeneratorTest.cs b/exercises/scale-generator/ScaleGeneratorTest.cs index 20062b30bf..fa8f80a38c 100644 --- a/exercises/scale-generator/ScaleGeneratorTest.cs +++ b/exercises/scale-generator/ScaleGeneratorTest.cs @@ -49,238 +49,105 @@ public void Chromatic_scale_with_flats() [Fact(Skip = "Remove to run test")] public void Simple_major_scale() { - var expected = new[] - { - "C", - "D", - "E", - "F", - "G", - "A", - "B" - }; + var expected = new[] { "C", "D", "E", "F", "G", "A", "B" }; Assert.Equal(expected, ScaleGenerator.Pitches("C", "MMmMMMm")); } [Fact(Skip = "Remove to run test")] public void Major_scale_with_sharps() { - var expected = new[] - { - "G", - "A", - "B", - "C", - "D", - "E", - "F#" - }; + var expected = new[] { "G", "A", "B", "C", "D", "E", "F#" }; Assert.Equal(expected, ScaleGenerator.Pitches("G", "MMmMMMm")); } [Fact(Skip = "Remove to run test")] public void Major_scale_with_flats() { - var expected = new[] - { - "F", - "G", - "A", - "Bb", - "C", - "D", - "E" - }; + var expected = new[] { "F", "G", "A", "Bb", "C", "D", "E" }; Assert.Equal(expected, ScaleGenerator.Pitches("F", "MMmMMMm")); } [Fact(Skip = "Remove to run test")] public void Minor_scale_with_sharps() { - var expected = new[] - { - "F#", - "G#", - "A", - "B", - "C#", - "D", - "E" - }; + var expected = new[] { "F#", "G#", "A", "B", "C#", "D", "E" }; Assert.Equal(expected, ScaleGenerator.Pitches("f#", "MmMMmMM")); } [Fact(Skip = "Remove to run test")] public void Minor_scale_with_flats() { - var expected = new[] - { - "Bb", - "C", - "Db", - "Eb", - "F", - "Gb", - "Ab" - }; + var expected = new[] { "Bb", "C", "Db", "Eb", "F", "Gb", "Ab" }; Assert.Equal(expected, ScaleGenerator.Pitches("bb", "MmMMmMM")); } [Fact(Skip = "Remove to run test")] public void Dorian_mode() { - var expected = new[] - { - "D", - "E", - "F", - "G", - "A", - "B", - "C" - }; + var expected = new[] { "D", "E", "F", "G", "A", "B", "C" }; Assert.Equal(expected, ScaleGenerator.Pitches("d", "MmMMMmM")); } [Fact(Skip = "Remove to run test")] public void Mixolydian_mode() { - var expected = new[] - { - "Eb", - "F", - "G", - "Ab", - "Bb", - "C", - "Db" - }; + var expected = new[] { "Eb", "F", "G", "Ab", "Bb", "C", "Db" }; Assert.Equal(expected, ScaleGenerator.Pitches("Eb", "MMmMMmM")); } [Fact(Skip = "Remove to run test")] public void Lydian_mode() { - var expected = new[] - { - "A", - "B", - "C#", - "D#", - "E", - "F#", - "G#" - }; + var expected = new[] { "A", "B", "C#", "D#", "E", "F#", "G#" }; Assert.Equal(expected, ScaleGenerator.Pitches("a", "MMMmMMm")); } [Fact(Skip = "Remove to run test")] public void Phrygian_mode() { - var expected = new[] - { - "E", - "F", - "G", - "A", - "B", - "C", - "D" - }; + var expected = new[] { "E", "F", "G", "A", "B", "C", "D" }; Assert.Equal(expected, ScaleGenerator.Pitches("e", "mMMMmMM")); } [Fact(Skip = "Remove to run test")] public void Locrian_mode() { - var expected = new[] - { - "G", - "Ab", - "Bb", - "C", - "Db", - "Eb", - "F" - }; + var expected = new[] { "G", "Ab", "Bb", "C", "Db", "Eb", "F" }; Assert.Equal(expected, ScaleGenerator.Pitches("g", "mMMmMMM")); } [Fact(Skip = "Remove to run test")] public void Harmonic_minor() { - var expected = new[] - { - "D", - "E", - "F", - "G", - "A", - "Bb", - "Db" - }; + var expected = new[] { "D", "E", "F", "G", "A", "Bb", "Db" }; Assert.Equal(expected, ScaleGenerator.Pitches("d", "MmMMmAm")); } [Fact(Skip = "Remove to run test")] public void Octatonic() { - var expected = new[] - { - "C", - "D", - "D#", - "F", - "F#", - "G#", - "A", - "B" - }; + var expected = new[] { "C", "D", "D#", "F", "F#", "G#", "A", "B" }; Assert.Equal(expected, ScaleGenerator.Pitches("C", "MmMmMmMm")); } [Fact(Skip = "Remove to run test")] public void Hexatonic() { - var expected = new[] - { - "Db", - "Eb", - "F", - "G", - "A", - "B" - }; + var expected = new[] { "Db", "Eb", "F", "G", "A", "B" }; Assert.Equal(expected, ScaleGenerator.Pitches("Db", "MMMMMM")); } [Fact(Skip = "Remove to run test")] public void Pentatonic() { - var expected = new[] - { - "A", - "B", - "C#", - "E", - "F#" - }; + var expected = new[] { "A", "B", "C#", "E", "F#" }; Assert.Equal(expected, ScaleGenerator.Pitches("A", "MMAMA")); } [Fact(Skip = "Remove to run test")] public void Enigmatic() { - var expected = new[] - { - "G", - "G#", - "B", - "C#", - "D#", - "F", - "F#" - }; + var expected = new[] { "G", "G#", "B", "C#", "D#", "F", "F#" }; Assert.Equal(expected, ScaleGenerator.Pitches("G", "mAMMMmm")); } } \ No newline at end of file diff --git a/exercises/sieve/SieveTest.cs b/exercises/sieve/SieveTest.cs index f7e934c0f5..0289943cb8 100644 --- a/exercises/sieve/SieveTest.cs +++ b/exercises/sieve/SieveTest.cs @@ -35,7 +35,177 @@ public void Limit_is_prime() [Fact(Skip = "Remove to run test")] public void Find_primes_up_to_1000() { - var expected = new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 }; + var expected = new[] + { + 2, + 3, + 5, + 7, + 11, + 13, + 17, + 19, + 23, + 29, + 31, + 37, + 41, + 43, + 47, + 53, + 59, + 61, + 67, + 71, + 73, + 79, + 83, + 89, + 97, + 101, + 103, + 107, + 109, + 113, + 127, + 131, + 137, + 139, + 149, + 151, + 157, + 163, + 167, + 173, + 179, + 181, + 191, + 193, + 197, + 199, + 211, + 223, + 227, + 229, + 233, + 239, + 241, + 251, + 257, + 263, + 269, + 271, + 277, + 281, + 283, + 293, + 307, + 311, + 313, + 317, + 331, + 337, + 347, + 349, + 353, + 359, + 367, + 373, + 379, + 383, + 389, + 397, + 401, + 409, + 419, + 421, + 431, + 433, + 439, + 443, + 449, + 457, + 461, + 463, + 467, + 479, + 487, + 491, + 499, + 503, + 509, + 521, + 523, + 541, + 547, + 557, + 563, + 569, + 571, + 577, + 587, + 593, + 599, + 601, + 607, + 613, + 617, + 619, + 631, + 641, + 643, + 647, + 653, + 659, + 661, + 673, + 677, + 683, + 691, + 701, + 709, + 719, + 727, + 733, + 739, + 743, + 751, + 757, + 761, + 769, + 773, + 787, + 797, + 809, + 811, + 821, + 823, + 827, + 829, + 839, + 853, + 857, + 859, + 863, + 877, + 881, + 883, + 887, + 907, + 911, + 919, + 929, + 937, + 941, + 947, + 953, + 967, + 971, + 977, + 983, + 991, + 997 + }; Assert.Equal(expected, Sieve.Primes(1000)); } } \ No newline at end of file diff --git a/exercises/spiral-matrix/SpiralMatrixTest.cs b/exercises/spiral-matrix/SpiralMatrixTest.cs index b5be47a47d..f4622b5b39 100644 --- a/exercises/spiral-matrix/SpiralMatrixTest.cs +++ b/exercises/spiral-matrix/SpiralMatrixTest.cs @@ -13,35 +13,60 @@ public void Empty_spiral() [Fact(Skip = "Remove to run test")] public void Trivial_spiral() { - var expected = new[,] { { 1 } }; + var expected = new[,] + { + { 1 } + }; Assert.Equal(expected, SpiralMatrix.GetMatrix(1)); } [Fact(Skip = "Remove to run test")] public void Spiral_of_size_2() { - var expected = new[,] { { 1, 2 }, { 4, 3 } }; + var expected = new[,] + { + { 1, 2 }, + { 4, 3 } + }; Assert.Equal(expected, SpiralMatrix.GetMatrix(2)); } [Fact(Skip = "Remove to run test")] public void Spiral_of_size_3() { - var expected = new[,] { { 1, 2, 3 }, { 8, 9, 4 }, { 7, 6, 5 } }; + var expected = new[,] + { + { 1, 2, 3 }, + { 8, 9, 4 }, + { 7, 6, 5 } + }; Assert.Equal(expected, SpiralMatrix.GetMatrix(3)); } [Fact(Skip = "Remove to run test")] public void Spiral_of_size_4() { - var expected = new[,] { { 1, 2, 3, 4 }, { 12, 13, 14, 5 }, { 11, 16, 15, 6 }, { 10, 9, 8, 7 } }; + var expected = new[,] + { + { 1, 2, 3, 4 }, + { 12, 13, 14, 5 }, + { 11, 16, 15, 6 }, + { 10, 9, 8, 7 } + }; Assert.Equal(expected, SpiralMatrix.GetMatrix(4)); } [Fact(Skip = "Remove to run test")] public void Spiral_of_size_5() { - var expected = new[,] { { 1, 2, 3, 4, 5 }, { 16, 17, 18, 19, 6 }, { 15, 24, 25, 20, 7 }, { 14, 23, 22, 21, 8 }, { 13, 12, 11, 10, 9 } }; + var expected = new[,] + { + { 1, 2, 3, 4, 5 }, + { 16, 17, 18, 19, 6 }, + { 15, 24, 25, 20, 7 }, + { 14, 23, 22, 21, 8 }, + { 13, 12, 11, 10, 9 } + }; Assert.Equal(expected, SpiralMatrix.GetMatrix(5)); } } \ No newline at end of file diff --git a/exercises/variable-length-quantity/VariableLengthQuantityTest.cs b/exercises/variable-length-quantity/VariableLengthQuantityTest.cs index 891314b416..3807559502 100644 --- a/exercises/variable-length-quantity/VariableLengthQuantityTest.cs +++ b/exercises/variable-length-quantity/VariableLengthQuantityTest.cs @@ -145,7 +145,24 @@ public void Two_multi_byte_values() public void Many_multi_byte_values() { var integers = new[] { 0x2000u, 0x123456u, 0xFFFFFFFu, 0x0u, 0x3FFFu, 0x4000u }; - var expected = new[] { 0xC0u, 0x0u, 0xC8u, 0xE8u, 0x56u, 0xFFu, 0xFFu, 0xFFu, 0x7Fu, 0x0u, 0xFFu, 0x7Fu, 0x81u, 0x80u, 0x0u }; + var expected = new[] + { + 0xC0u, + 0x0u, + 0xC8u, + 0xE8u, + 0x56u, + 0xFFu, + 0xFFu, + 0xFFu, + 0x7Fu, + 0x0u, + 0xFFu, + 0x7Fu, + 0x81u, + 0x80u, + 0x0u + }; Assert.Equal(expected, VariableLengthQuantity.Encode(integers)); } @@ -206,7 +223,24 @@ public void Incomplete_sequence_causes_error_even_if_value_is_zero() [Fact(Skip = "Remove to run test")] public void Multiple_values() { - var integers = new[] { 0xC0u, 0x0u, 0xC8u, 0xE8u, 0x56u, 0xFFu, 0xFFu, 0xFFu, 0x7Fu, 0x0u, 0xFFu, 0x7Fu, 0x81u, 0x80u, 0x0u }; + var integers = new[] + { + 0xC0u, + 0x0u, + 0xC8u, + 0xE8u, + 0x56u, + 0xFFu, + 0xFFu, + 0xFFu, + 0x7Fu, + 0x0u, + 0xFFu, + 0x7Fu, + 0x81u, + 0x80u, + 0x0u + }; var expected = new[] { 0x2000u, 0x123456u, 0xFFFFFFFu, 0x0u, 0x3FFFu, 0x4000u }; Assert.Equal(expected, VariableLengthQuantity.Decode(integers)); } diff --git a/exercises/word-search/WordSearchTest.cs b/exercises/word-search/WordSearchTest.cs index eb7add4f35..1f98fd0a20 100644 --- a/exercises/word-search/WordSearchTest.cs +++ b/exercises/word-search/WordSearchTest.cs @@ -9,10 +9,7 @@ public class WordSearchTest [Fact] public void Should_accept_an_initial_game_grid_and_a_target_search_word() { - var wordsToSearchFor = new[] - { - "clojure" - }; + var wordsToSearchFor = new[] { "clojure" }; var grid = "jefblpepre"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); @@ -26,10 +23,7 @@ public void Should_accept_an_initial_game_grid_and_a_target_search_word() [Fact(Skip = "Remove to run test")] public void Should_locate_one_word_written_left_to_right() { - var wordsToSearchFor = new[] - { - "clojure" - }; + var wordsToSearchFor = new[] { "clojure" }; var grid = "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); @@ -43,10 +37,7 @@ public void Should_locate_one_word_written_left_to_right() [Fact(Skip = "Remove to run test")] public void Should_locate_the_same_word_written_left_to_right_in_a_different_position() { - var wordsToSearchFor = new[] - { - "clojure" - }; + var wordsToSearchFor = new[] { "clojure" }; var grid = "mtclojurer"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); @@ -60,10 +51,7 @@ public void Should_locate_the_same_word_written_left_to_right_in_a_different_pos [Fact(Skip = "Remove to run test")] public void Should_locate_a_different_left_to_right_word() { - var wordsToSearchFor = new[] - { - "coffee" - }; + var wordsToSearchFor = new[] { "coffee" }; var grid = "coffeelplx"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); @@ -77,10 +65,7 @@ public void Should_locate_a_different_left_to_right_word() [Fact(Skip = "Remove to run test")] public void Should_locate_that_different_left_to_right_word_in_a_different_position() { - var wordsToSearchFor = new[] - { - "coffee" - }; + var wordsToSearchFor = new[] { "coffee" }; var grid = "xcoffeezlp"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); @@ -94,10 +79,7 @@ public void Should_locate_that_different_left_to_right_word_in_a_different_posit [Fact(Skip = "Remove to run test")] public void Should_locate_a_left_to_right_word_in_two_line_grid() { - var wordsToSearchFor = new[] - { - "clojure" - }; + var wordsToSearchFor = new[] { "clojure" }; var grid = "jefblpepre\n" + "tclojurerm"; @@ -113,10 +95,7 @@ public void Should_locate_a_left_to_right_word_in_two_line_grid() [Fact(Skip = "Remove to run test")] public void Should_locate_a_left_to_right_word_in_three_line_grid() { - var wordsToSearchFor = new[] - { - "clojure" - }; + var wordsToSearchFor = new[] { "clojure" }; var grid = "camdcimgtc\n" + "jefblpepre\n" + @@ -133,10 +112,7 @@ public void Should_locate_a_left_to_right_word_in_three_line_grid() [Fact(Skip = "Remove to run test")] public void Should_locate_a_left_to_right_word_in_ten_line_grid() { - var wordsToSearchFor = new[] - { - "clojure" - }; + var wordsToSearchFor = new[] { "clojure" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -160,10 +136,7 @@ public void Should_locate_a_left_to_right_word_in_ten_line_grid() [Fact(Skip = "Remove to run test")] public void Should_locate_that_left_to_right_word_in_a_different_position_in_a_ten_line_grid() { - var wordsToSearchFor = new[] - { - "clojure" - }; + var wordsToSearchFor = new[] { "clojure" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -187,10 +160,7 @@ public void Should_locate_that_left_to_right_word_in_a_different_position_in_a_t [Fact(Skip = "Remove to run test")] public void Should_locate_a_different_left_to_right_word_in_a_ten_line_grid() { - var wordsToSearchFor = new[] - { - "fortran" - }; + var wordsToSearchFor = new[] { "fortran" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -214,11 +184,7 @@ public void Should_locate_a_different_left_to_right_word_in_a_ten_line_grid() [Fact(Skip = "Remove to run test")] public void Should_locate_multiple_words() { - var wordsToSearchFor = new[] - { - "fortran", - "clojure" - }; + var wordsToSearchFor = new[] { "fortran", "clojure" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -244,10 +210,7 @@ public void Should_locate_multiple_words() [Fact(Skip = "Remove to run test")] public void Should_locate_a_single_word_written_right_to_left() { - var wordsToSearchFor = new[] - { - "elixir" - }; + var wordsToSearchFor = new[] { "elixir" }; var grid = "rixilelhrs"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); @@ -261,11 +224,7 @@ public void Should_locate_a_single_word_written_right_to_left() [Fact(Skip = "Remove to run test")] public void Should_locate_multiple_words_written_in_different_horizontal_directions() { - var wordsToSearchFor = new[] - { - "elixir", - "clojure" - }; + var wordsToSearchFor = new[] { "elixir", "clojure" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -291,12 +250,7 @@ public void Should_locate_multiple_words_written_in_different_horizontal_directi [Fact(Skip = "Remove to run test")] public void Should_locate_words_written_top_to_bottom() { - var wordsToSearchFor = new[] - { - "clojure", - "elixir", - "ecmascript" - }; + var wordsToSearchFor = new[] { "clojure", "elixir", "ecmascript" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -324,13 +278,7 @@ public void Should_locate_words_written_top_to_bottom() [Fact(Skip = "Remove to run test")] public void Should_locate_words_written_bottom_to_top() { - var wordsToSearchFor = new[] - { - "clojure", - "elixir", - "ecmascript", - "rust" - }; + var wordsToSearchFor = new[] { "clojure", "elixir", "ecmascript", "rust" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -360,14 +308,7 @@ public void Should_locate_words_written_bottom_to_top() [Fact(Skip = "Remove to run test")] public void Should_locate_words_written_top_left_to_bottom_right() { - var wordsToSearchFor = new[] - { - "clojure", - "elixir", - "ecmascript", - "rust", - "java" - }; + var wordsToSearchFor = new[] { "clojure", "elixir", "ecmascript", "rust", "java" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -399,15 +340,7 @@ public void Should_locate_words_written_top_left_to_bottom_right() [Fact(Skip = "Remove to run test")] public void Should_locate_words_written_bottom_right_to_top_left() { - var wordsToSearchFor = new[] - { - "clojure", - "elixir", - "ecmascript", - "rust", - "java", - "lua" - }; + var wordsToSearchFor = new[] { "clojure", "elixir", "ecmascript", "rust", "java", "lua" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + diff --git a/generators/Exercises/Generators/Dominoes.cs b/generators/Exercises/Generators/Dominoes.cs index 7d2e6dc7fb..e55d96e483 100644 --- a/generators/Exercises/Generators/Dominoes.cs +++ b/generators/Exercises/Generators/Dominoes.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators diff --git a/generators/Exercises/Generators/OcrNumbers.cs b/generators/Exercises/Generators/OcrNumbers.cs index f7463e8ee3..1fae30e64e 100644 --- a/generators/Exercises/Generators/OcrNumbers.cs +++ b/generators/Exercises/Generators/OcrNumbers.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 4e4fcac80f..8cf8425798 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -31,6 +31,23 @@ public string Object(object val) } } + public string ObjectMultiLine(object val) + { + switch (val) + { + case MultiLineString multiLineValue: + return StringMultiLine(multiLineValue); + default: + if (IsDictionary(val)) + return DictionaryMultiLine((dynamic) val); + + if (IsArray(val)) + return ArrayMultiLine((dynamic) val); + + return Object(val); + } + } + private static bool IsList(object obj) => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(List<>); diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs index b9eaaae2c4..75c6a3fbef 100644 --- a/generators/Output/Rendering/RenderArray.cs +++ b/generators/Output/Rendering/RenderArray.cs @@ -1,17 +1,34 @@ -using System.Collections.Generic; +using System; using System.Linq; -using System.Text; using Exercism.CSharp.Helpers; +using Microsoft.VisualBasic.CompilerServices; namespace Exercism.CSharp.Output.Rendering { public partial class Render - { + { + private const int MaximumLengthForSingleLineValue = 68; + public string Array(T[] elements) => elements.Any() ? $"new[] {{ {string.Join(", ", elements.Cast().Select(Object))} }}" : $"Array.Empty<{typeof(T).ToFriendlyName()}>()"; - + + public string ArrayMultiLine(T[] elements) + { + if (elements.Length == 0) + return $"Array.Empty<{typeof(T).ToFriendlyName()}>()"; + + if (RenderAsSingleLine()) + return Array(elements); + + return $"new[]{Environment.NewLine}{{{Environment.NewLine}{string.Join($",{Environment.NewLine}", elements.Cast().Select(Object).Select(line => line.Indent()))}{Environment.NewLine}}}"; + + bool RenderAsSingleLine() => IsNotArrayOfArrays() && RenderedAsSingleLineDoesNotExceedMaximumLength(); + bool IsNotArrayOfArrays() => !elements.GetType().GetElementType().IsArray; + bool RenderedAsSingleLineDoesNotExceedMaximumLength() => Array(elements).Length <= MaximumLengthForSingleLineValue; + } + public string Array(T[,] elements) { return elements.Length == 0 @@ -21,8 +38,13 @@ public string Array(T[,] elements) string RenderRow(T[] row) => $"{{ {string.Join(", ", row.Cast().Select(Object))} }}"; } - public IEnumerable MultiLineEnumerable(IEnumerable enumerable, string name, - string constructor = null) - => MultiLineVariable(enumerable.Prepend("{").Append("}"), name, constructor); + public string ArrayMultiLine(T[,] elements) + { + return elements.Length == 0 + ? $"new {typeof(T).ToFriendlyName()}[,] {{ }}" + : $"new[,]{Environment.NewLine}{{{Environment.NewLine}{string.Join($",{Environment.NewLine}", elements.Rows().Select(RenderRow))}{Environment.NewLine}}}"; + + string RenderRow(T[] row) => $"{{ {string.Join(", ", row.Cast().Select(Object))} }}".Indent(); + } } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderVariable.cs b/generators/Output/Rendering/RenderVariable.cs index a4e9a65c7e..f5ba768c31 100644 --- a/generators/Output/Rendering/RenderVariable.cs +++ b/generators/Output/Rendering/RenderVariable.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Helpers; @@ -13,29 +12,6 @@ public IEnumerable Variables(IDictionary dict) private string Variable(KeyValuePair kv) => Variable(kv.Key.ToVariableName(), kv.Value); - public string Variable(string name, object val) - { - switch (val) - { - case MultiLineString multiLineValue: - return $"var {name} = {StringMultiLine(multiLineValue)};"; - case IEnumerable strings: - if (!strings.Any()) - { - return $"var {name} = Array.Empty();"; - } - - return string.Join(Environment.NewLine, MultiLineEnumerable( - strings.Select((str, i) => String(str) + (i < strings.Count() - 1 ? "," : "")), name, "new[]")); - default: - if (IsDictionary(val)) - return $"var {name} = {DictionaryMultiLine((dynamic)val)};"; - - return $"var {name} = {Object(val)};"; - } - } - - public IEnumerable MultiLineVariable(IEnumerable enumerable, string name, string constructor = null) - => enumerable.Select(line => line == "{" || line == "}" ? line : line.Indent()).AddTrailingSemicolon().Prepend($"var {name} = {constructor}").ToArray(); + public string Variable(string name, object val) => $"var {name} = {ObjectMultiLine(val)};"; } } \ No newline at end of file From 0c722ced35d36212ae46428db84a0c3c5e07641a Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 14:33:17 +0200 Subject: [PATCH 71/97] generators: Remove unused methods --- generators/Output/Rendering/RenderArray.cs | 6 +----- generators/Output/Rendering/RenderExtensions.cs | 12 +----------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs index 75c6a3fbef..70c9c84be7 100644 --- a/generators/Output/Rendering/RenderArray.cs +++ b/generators/Output/Rendering/RenderArray.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using Exercism.CSharp.Helpers; -using Microsoft.VisualBasic.CompilerServices; namespace Exercism.CSharp.Output.Rendering { @@ -16,15 +15,12 @@ public string Array(T[] elements) => public string ArrayMultiLine(T[] elements) { - if (elements.Length == 0) - return $"Array.Empty<{typeof(T).ToFriendlyName()}>()"; - if (RenderAsSingleLine()) return Array(elements); return $"new[]{Environment.NewLine}{{{Environment.NewLine}{string.Join($",{Environment.NewLine}", elements.Cast().Select(Object).Select(line => line.Indent()))}{Environment.NewLine}}}"; - bool RenderAsSingleLine() => IsNotArrayOfArrays() && RenderedAsSingleLineDoesNotExceedMaximumLength(); + bool RenderAsSingleLine() => !elements.Any() || IsNotArrayOfArrays() && RenderedAsSingleLineDoesNotExceedMaximumLength(); bool IsNotArrayOfArrays() => !elements.GetType().GetElementType().IsArray; bool RenderedAsSingleLineDoesNotExceedMaximumLength() => Array(elements).Length <= MaximumLengthForSingleLineValue; } diff --git a/generators/Output/Rendering/RenderExtensions.cs b/generators/Output/Rendering/RenderExtensions.cs index 4edb689631..00a4740d7c 100644 --- a/generators/Output/Rendering/RenderExtensions.cs +++ b/generators/Output/Rendering/RenderExtensions.cs @@ -1,7 +1,4 @@ -using System.Collections.Generic; -using System.Linq; - -namespace Exercism.CSharp.Output.Rendering +namespace Exercism.CSharp.Output.Rendering { public static class RenderExtensions { @@ -14,12 +11,5 @@ public static string EscapeSpecialCharacters(this string s) .Replace("\"", "\\\""); public static string Quote(this string s) => $"\"{s}\""; - - public static IEnumerable AddTrailingSemicolon(this IEnumerable enumerable) - { - var array = enumerable.ToArray(); - array[array.Length - 1] += ";"; - return array; - } } } From 653bff36a5d83b4b5f662dcd4f3ba8a68de19d50 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 14:37:24 +0200 Subject: [PATCH 72/97] generators: Simplify string/char escaping code --- generators/Output/Rendering/RenderExtensions.cs | 12 ++++++++---- generators/Output/Rendering/RenderString.cs | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/generators/Output/Rendering/RenderExtensions.cs b/generators/Output/Rendering/RenderExtensions.cs index 00a4740d7c..dd001363d9 100644 --- a/generators/Output/Rendering/RenderExtensions.cs +++ b/generators/Output/Rendering/RenderExtensions.cs @@ -2,14 +2,18 @@ { public static class RenderExtensions { - public static string Indent(this string str, int level = 1) => $"{new string(' ', 4 * level)}{str}"; + private const int IndentSize = 4; - public static string EscapeSpecialCharacters(this string s) - => s.Replace("\n", "\\n") + public static string Indent(this string str) => $"{new string(' ', IndentSize)}{str}"; + + public static string EscapeSpecialCharacters(this string str) + => str.Replace("\n", "\\n") .Replace("\t", "\\t") .Replace("\r", "\\r") .Replace("\"", "\\\""); - public static string Quote(this string s) => $"\"{s}\""; + public static string Quote(this string str) => $"\"{str}\""; + + public static string Quote(this char c) => $"'{c}'"; } } diff --git a/generators/Output/Rendering/RenderString.cs b/generators/Output/Rendering/RenderString.cs index d80cbe8c4e..b5c2744268 100644 --- a/generators/Output/Rendering/RenderString.cs +++ b/generators/Output/Rendering/RenderString.cs @@ -10,7 +10,7 @@ public partial class Render public UnescapedValue Enum(string enumType, string enumCase) => new UnescapedValue($"{enumType}.{enumCase.ToLower().Dehumanize()}"); - public string Char(char c) => $"'{c}'"; + public string Char(char c) => c.Quote(); public string String(string s) => s.EscapeSpecialCharacters().Quote(); From c94750417c6863c92d79a49a00b3121774a1da73 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 15:00:42 +0200 Subject: [PATCH 73/97] generators: Add collection initialization renderer --- exercises/saddle-points/SaddlePointsTest.cs | 24 +++++----- exercises/spiral-matrix/SpiralMatrixTest.cs | 30 ++++++------ generators/Output/Rendering/RenderArray.cs | 48 ++++++++----------- .../Output/Rendering/RenderCollection.cs | 24 ++++++++++ .../Output/Rendering/RenderDictionary.cs | 8 ++-- generators/Output/Rendering/RenderList.cs | 2 +- 6 files changed, 76 insertions(+), 60 deletions(-) create mode 100644 generators/Output/Rendering/RenderCollection.cs diff --git a/exercises/saddle-points/SaddlePointsTest.cs b/exercises/saddle-points/SaddlePointsTest.cs index 49090f00e2..2419bfa828 100644 --- a/exercises/saddle-points/SaddlePointsTest.cs +++ b/exercises/saddle-points/SaddlePointsTest.cs @@ -10,9 +10,9 @@ public void Can_identify_single_saddle_point() { var matrix = new[,] { - { 9, 8, 7 }, - { 5, 3, 2 }, - { 6, 6, 7 } + { 9, 8, 7 }, + { 5, 3, 2 }, + { 6, 6, 7 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); @@ -34,9 +34,9 @@ public void Can_identify_lack_of_saddle_points_when_there_are_none() { var matrix = new[,] { - { 1, 2, 3 }, - { 3, 1, 2 }, - { 2, 3, 1 } + { 1, 2, 3 }, + { 3, 1, 2 }, + { 2, 3, 1 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); @@ -48,9 +48,9 @@ public void Can_identify_multiple_saddle_points() { var matrix = new[,] { - { 4, 5, 4 }, - { 3, 5, 5 }, - { 1, 5, 4 } + { 4, 5, 4 }, + { 3, 5, 5 }, + { 1, 5, 4 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); @@ -63,9 +63,9 @@ public void Can_identify_saddle_point_in_bottom_right_corner() { var matrix = new[,] { - { 8, 7, 9 }, - { 6, 7, 6 }, - { 3, 2, 5 } + { 8, 7, 9 }, + { 6, 7, 6 }, + { 3, 2, 5 } }; var sut = new SaddlePoints(matrix); var actual = sut.Calculate(); diff --git a/exercises/spiral-matrix/SpiralMatrixTest.cs b/exercises/spiral-matrix/SpiralMatrixTest.cs index f4622b5b39..97b827632d 100644 --- a/exercises/spiral-matrix/SpiralMatrixTest.cs +++ b/exercises/spiral-matrix/SpiralMatrixTest.cs @@ -15,7 +15,7 @@ public void Trivial_spiral() { var expected = new[,] { - { 1 } + { 1 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(1)); } @@ -25,8 +25,8 @@ public void Spiral_of_size_2() { var expected = new[,] { - { 1, 2 }, - { 4, 3 } + { 1, 2 }, + { 4, 3 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(2)); } @@ -36,9 +36,9 @@ public void Spiral_of_size_3() { var expected = new[,] { - { 1, 2, 3 }, - { 8, 9, 4 }, - { 7, 6, 5 } + { 1, 2, 3 }, + { 8, 9, 4 }, + { 7, 6, 5 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(3)); } @@ -48,10 +48,10 @@ public void Spiral_of_size_4() { var expected = new[,] { - { 1, 2, 3, 4 }, - { 12, 13, 14, 5 }, - { 11, 16, 15, 6 }, - { 10, 9, 8, 7 } + { 1, 2, 3, 4 }, + { 12, 13, 14, 5 }, + { 11, 16, 15, 6 }, + { 10, 9, 8, 7 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(4)); } @@ -61,11 +61,11 @@ public void Spiral_of_size_5() { var expected = new[,] { - { 1, 2, 3, 4, 5 }, - { 16, 17, 18, 19, 6 }, - { 15, 24, 25, 20, 7 }, - { 14, 23, 22, 21, 8 }, - { 13, 12, 11, 10, 9 } + { 1, 2, 3, 4, 5 }, + { 16, 17, 18, 19, 6 }, + { 15, 24, 25, 20, 7 }, + { 14, 23, 22, 21, 8 }, + { 13, 12, 11, 10, 9 } }; Assert.Equal(expected, SpiralMatrix.GetMatrix(5)); } diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs index 70c9c84be7..1248177741 100644 --- a/generators/Output/Rendering/RenderArray.cs +++ b/generators/Output/Rendering/RenderArray.cs @@ -9,38 +9,32 @@ public partial class Render private const int MaximumLengthForSingleLineValue = 68; public string Array(T[] elements) => - elements.Any() - ? $"new[] {{ {string.Join(", ", elements.Cast().Select(Object))} }}" - : $"Array.Empty<{typeof(T).ToFriendlyName()}>()"; + elements.Length == 0 + ? $"Array.Empty<{typeof(T).ToFriendlyName()}>()" + : $"new[]{CollectionInitializer(elements)}"; - public string ArrayMultiLine(T[] elements) - { - if (RenderAsSingleLine()) - return Array(elements); + public string ArrayMultiLine(T[] elements) + => RenderAsSingleLine(elements) + ? Array(elements) + : $"new[]{MultiLineCollectionInitializer(elements)}"; - return $"new[]{Environment.NewLine}{{{Environment.NewLine}{string.Join($",{Environment.NewLine}", elements.Cast().Select(Object).Select(line => line.Indent()))}{Environment.NewLine}}}"; - - bool RenderAsSingleLine() => !elements.Any() || IsNotArrayOfArrays() && RenderedAsSingleLineDoesNotExceedMaximumLength(); - bool IsNotArrayOfArrays() => !elements.GetType().GetElementType().IsArray; - bool RenderedAsSingleLineDoesNotExceedMaximumLength() => Array(elements).Length <= MaximumLengthForSingleLineValue; - } - - public string Array(T[,] elements) - { - return elements.Length == 0 + public string Array(T[,] elements) + => elements.Length == 0 ? $"new {typeof(T).ToFriendlyName()}[,] {{ }}" - : $"new[,] {{ {string.Join(", ", elements.Rows().Select(RenderRow))} }}"; - - string RenderRow(T[] row) => $"{{ {string.Join(", ", row.Cast().Select(Object))} }}"; - } + : $"new[,]{CollectionInitializer(elements.Rows())}"; - public string ArrayMultiLine(T[,] elements) - { - return elements.Length == 0 + public string ArrayMultiLine(T[,] elements) + => elements.Length == 0 ? $"new {typeof(T).ToFriendlyName()}[,] {{ }}" - : $"new[,]{Environment.NewLine}{{{Environment.NewLine}{string.Join($",{Environment.NewLine}", elements.Rows().Select(RenderRow))}{Environment.NewLine}}}"; + : $"new[,]{MultiLineCollectionInitializer(elements.Rows(), CollectionInitializer)}"; + + private bool RenderAsSingleLine(T[] elements) + => !elements.Any() || IsNotArrayOfArrays(elements) && RenderedAsSingleLineDoesNotExceedMaximumLength(elements); + + private bool IsNotArrayOfArrays(T[] elements) + => !elements.GetType().GetElementType().IsArray; - string RenderRow(T[] row) => $"{{ {string.Join(", ", row.Cast().Select(Object))} }}".Indent(); - } + private bool RenderedAsSingleLineDoesNotExceedMaximumLength(T[] elements) + => Array(elements).Length <= MaximumLengthForSingleLineValue; } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderCollection.cs b/generators/Output/Rendering/RenderCollection.cs new file mode 100644 index 0000000000..d0786eb4fb --- /dev/null +++ b/generators/Output/Rendering/RenderCollection.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Exercism.CSharp.Output.Rendering +{ + public partial class Render + { + public string CollectionInitializer(IEnumerable elements) + => CollectionInitializer(elements, line => Object(line), " "); + + public string CollectionInitializer(IEnumerable elements, Func render) + => CollectionInitializer(elements, render, " "); + + public string MultiLineCollectionInitializer(IEnumerable elements) + => CollectionInitializer(elements, line => Object(line).Indent(), Environment.NewLine); + + public string MultiLineCollectionInitializer(IEnumerable elements, Func render) + => CollectionInitializer(elements, line => render(line).Indent(), Environment.NewLine); + + private string CollectionInitializer(IEnumerable elements, Func render, string separator) + => $"{separator}{{{separator}{string.Join($",{separator}", elements.Select(render))}{separator}}}"; + } +} \ No newline at end of file diff --git a/generators/Output/Rendering/RenderDictionary.cs b/generators/Output/Rendering/RenderDictionary.cs index be250ddf3d..81a315214a 100644 --- a/generators/Output/Rendering/RenderDictionary.cs +++ b/generators/Output/Rendering/RenderDictionary.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using System.Collections.Generic; using Exercism.CSharp.Helpers; namespace Exercism.CSharp.Output.Rendering @@ -10,12 +8,12 @@ public partial class Render public string Dictionary(IDictionary dict) => dict.Count == 0 ? $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>()" - : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}> {{ {string.Join(", ", dict.Select(KeyValueAssignment))} }}"; + : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>{CollectionInitializer(dict, KeyValueAssignment)}"; public string DictionaryMultiLine(IDictionary dict) => dict.Count == 0 ? $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>()" - : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>{Environment.NewLine}{{{Environment.NewLine}{string.Join($",{Environment.NewLine}", dict.Select(KeyValueAssignment).Select(assignment => assignment.Indent()))}{Environment.NewLine}}}"; + : $"new Dictionary<{typeof(TKey).ToFriendlyName()}, {typeof(TValue).ToFriendlyName()}>{MultiLineCollectionInitializer(dict, KeyValueAssignment)}"; private string KeyValueAssignment(KeyValuePair kv) => $"[{Object(kv.Key)}] = {Object(kv.Value)}"; } diff --git a/generators/Output/Rendering/RenderList.cs b/generators/Output/Rendering/RenderList.cs index 3dd350bd4e..2243eb5ec3 100644 --- a/generators/Output/Rendering/RenderList.cs +++ b/generators/Output/Rendering/RenderList.cs @@ -8,7 +8,7 @@ public partial class Render { public string List(List elements) => elements.Any() - ? $"new List<{typeof(T).ToFriendlyName()}> {{ {string.Join(", ", elements.Cast().Select(Object))} }}" + ? $"new List<{typeof(T).ToFriendlyName()}>{CollectionInitializer(elements)}" : $"new List<{typeof(T).ToFriendlyName()}>()"; } } \ No newline at end of file From 7fc5ea47e1592bd5c26159996cc622205e3f6ef8 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 15:52:24 +0200 Subject: [PATCH 74/97] generators: Use variable render helper to render variables --- exercises/bowling/BowlingTest.cs | 326 ++++++++++++++++-- .../Exercises/Generators/BinarySearchTree.cs | 4 +- generators/Exercises/Generators/Bowling.cs | 22 +- .../Exercises/Generators/CircularBuffer.cs | 4 +- .../Exercises/Generators/QueenAttack.cs | 4 +- generators/Exercises/Generators/React.cs | 23 +- generators/Exercises/Generators/TwoBucket.cs | 2 +- generators/Exercises/Generators/Zipper.cs | 10 +- generators/Output/Rendering/RenderVariable.cs | 4 +- generators/Output/TestMethod.cs | 7 +- 10 files changed, 336 insertions(+), 70 deletions(-) diff --git a/exercises/bowling/BowlingTest.cs b/exercises/bowling/BowlingTest.cs index 20f928787f..708d19b3ad 100644 --- a/exercises/bowling/BowlingTest.cs +++ b/exercises/bowling/BowlingTest.cs @@ -10,7 +10,7 @@ public class BowlingTest public void Should_be_able_to_score_a_game_with_all_zeros() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(0, actual); @@ -20,7 +20,7 @@ public void Should_be_able_to_score_a_game_with_all_zeros() public void Should_be_able_to_score_a_game_with_no_strikes_or_spares() { var sut = new BowlingGame(); - var previousRolls = new [] { 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6 }; + var previousRolls = new[] { 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(90, actual); @@ -30,7 +30,7 @@ public void Should_be_able_to_score_a_game_with_no_strikes_or_spares() public void A_spare_followed_by_zeros_is_worth_ten_points() { var sut = new BowlingGame(); - var previousRolls = new [] { 6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var previousRolls = new[] { 6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(10, actual); @@ -40,7 +40,7 @@ public void A_spare_followed_by_zeros_is_worth_ten_points() public void Points_scored_in_the_roll_after_a_spare_are_counted_twice() { var sut = new BowlingGame(); - var previousRolls = new [] { 6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var previousRolls = new[] { 6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(16, actual); @@ -50,7 +50,7 @@ public void Points_scored_in_the_roll_after_a_spare_are_counted_twice() public void Consecutive_spares_each_get_a_one_roll_bonus() { var sut = new BowlingGame(); - var previousRolls = new [] { 5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var previousRolls = new[] { 5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(31, actual); @@ -60,7 +60,30 @@ public void Consecutive_spares_each_get_a_one_roll_bonus() public void A_spare_in_the_last_frame_gets_a_one_roll_bonus_that_is_counted_once() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 3, + 7 + }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(17, actual); @@ -70,7 +93,7 @@ public void A_spare_in_the_last_frame_gets_a_one_roll_bonus_that_is_counted_once public void A_strike_earns_ten_points_in_a_frame_with_a_single_roll() { var sut = new BowlingGame(); - var previousRolls = new [] { 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var previousRolls = new[] { 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(10, actual); @@ -80,7 +103,7 @@ public void A_strike_earns_ten_points_in_a_frame_with_a_single_roll() public void Points_scored_in_the_two_rolls_after_a_strike_are_counted_twice_as_a_bonus() { var sut = new BowlingGame(); - var previousRolls = new [] { 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var previousRolls = new[] { 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(26, actual); @@ -90,7 +113,7 @@ public void Points_scored_in_the_two_rolls_after_a_strike_are_counted_twice_as_a public void Consecutive_strikes_each_get_the_two_roll_bonus() { var sut = new BowlingGame(); - var previousRolls = new [] { 10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var previousRolls = new[] { 10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(81, actual); @@ -100,7 +123,30 @@ public void Consecutive_strikes_each_get_the_two_roll_bonus() public void A_strike_in_the_last_frame_gets_a_two_roll_bonus_that_is_counted_once() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 7, + 1 + }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(18, actual); @@ -110,7 +156,30 @@ public void A_strike_in_the_last_frame_gets_a_two_roll_bonus_that_is_counted_onc public void Rolling_a_spare_with_the_two_roll_bonus_does_not_get_a_bonus_roll() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 7, + 3 + }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(20, actual); @@ -120,7 +189,30 @@ public void Rolling_a_spare_with_the_two_roll_bonus_does_not_get_a_bonus_roll() public void Strikes_with_the_two_roll_bonus_do_not_get_bonus_rolls() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 10, + 10 + }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(30, actual); @@ -130,7 +222,30 @@ public void Strikes_with_the_two_roll_bonus_do_not_get_bonus_rolls() public void A_strike_with_the_one_roll_bonus_after_a_spare_in_the_last_frame_does_not_get_a_bonus() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 3, + 10 + }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(20, actual); @@ -140,7 +255,7 @@ public void A_strike_with_the_one_roll_bonus_after_a_spare_in_the_last_frame_doe public void All_strikes_is_a_perfect_game() { var sut = new BowlingGame(); - var previousRolls = new [] { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }; + var previousRolls = new[] { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(300, actual); @@ -168,7 +283,7 @@ public void A_roll_cannot_score_more_than_10_points() public void Two_rolls_in_a_frame_cannot_score_more_than_10_points() { var sut = new BowlingGame(); - var previousRolls = new [] { 5 }; + var previousRolls = new[] { 5 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(6)); } @@ -177,7 +292,7 @@ public void Two_rolls_in_a_frame_cannot_score_more_than_10_points() public void Bonus_roll_after_a_strike_in_the_last_frame_cannot_score_more_than_10_points() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10 }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(11)); } @@ -186,7 +301,29 @@ public void Bonus_roll_after_a_strike_in_the_last_frame_cannot_score_more_than_1 public void Two_bonus_rolls_after_a_strike_in_the_last_frame_cannot_score_more_than_10_points() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 5 + }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(6)); } @@ -195,7 +332,30 @@ public void Two_bonus_rolls_after_a_strike_in_the_last_frame_cannot_score_more_t public void Two_bonus_rolls_after_a_strike_in_the_last_frame_can_score_more_than_10_points_if_one_is_a_strike() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 10, + 6 + }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(26, actual); @@ -205,7 +365,29 @@ public void Two_bonus_rolls_after_a_strike_in_the_last_frame_can_score_more_than public void The_second_bonus_rolls_after_a_strike_in_the_last_frame_cannot_be_a_strike_if_the_first_one_is_not_a_strike() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 6 + }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(10)); } @@ -214,7 +396,29 @@ public void The_second_bonus_rolls_after_a_strike_in_the_last_frame_cannot_be_a_ public void Second_bonus_roll_after_a_strike_in_the_last_frame_cannot_score_more_than_10_points() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 10 + }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(11)); } @@ -232,7 +436,7 @@ public void An_unstarted_game_cannot_be_scored() public void An_incomplete_game_cannot_be_scored() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0 }; + var previousRolls = new[] { 0, 0 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Score()); } @@ -241,7 +445,7 @@ public void An_incomplete_game_cannot_be_scored() public void Cannot_roll_if_game_already_has_ten_frames() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(0)); } @@ -250,7 +454,7 @@ public void Cannot_roll_if_game_already_has_ten_frames() public void Bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_before_score_can_be_calculated() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10 }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Score()); } @@ -259,7 +463,29 @@ public void Bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_before_sco public void Both_bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_before_score_can_be_calculated() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 10 + }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Score()); } @@ -268,7 +494,7 @@ public void Both_bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_befor public void Bonus_roll_for_a_spare_in_the_last_frame_must_be_rolled_before_score_can_be_calculated() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3 }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Score()); } @@ -277,7 +503,30 @@ public void Bonus_roll_for_a_spare_in_the_last_frame_must_be_rolled_before_score public void Cannot_roll_after_bonus_roll_for_spare() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 2 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 3, + 2 + }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(2)); } @@ -286,7 +535,30 @@ public void Cannot_roll_after_bonus_roll_for_spare() public void Cannot_roll_after_bonus_rolls_for_strike() { var sut = new BowlingGame(); - var previousRolls = new [] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 3, 2 }; + var previousRolls = new[] + { + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 10, + 3, + 2 + }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(2)); } diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 0288fdb9ee..9d7670d78a 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -38,11 +38,11 @@ private string RenderAssert(TestMethod method) var input = canonicalDataCase.Input as Dictionary; var constructorData = input["treeData"] as string[]; - if (constructorData.Length == 1) assert.AppendLine($"var tree = new BinarySearchTree({constructorData[0]});"); + if (constructorData.Length == 1) assert.AppendLine(Render.Variable("tree", $"new BinarySearchTree({constructorData[0]})")); else { var constructorDataString = string.Join(", ", constructorData); - assert.AppendLine($"var tree = new BinarySearchTree(new[] {{ {constructorDataString} }});"); + assert.AppendLine(Render.Variable("tree", $"new BinarySearchTree(new[] {{ {constructorDataString} }})")); } if (canonicalDataCase.Expected is Dictionary expected) diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index f495c2ae45..ffdaf009e1 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -30,24 +30,16 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderArrange(TestMethod method) + private string RenderArrange(TestMethod method) { var builder = new StringBuilder(); - builder.AppendLine("var sut = new BowlingGame();"); + builder.AppendLine(Render.Variable("sut", "new BowlingGame()")); if (!method.Data.Input.ContainsKey(PreviousRolls)) return builder.ToString(); - if (method.Data.Input[PreviousRolls] is int[] array) - { - builder.Append("var previousRolls = new [] { "); - builder.AppendJoin(", ", array); - builder.AppendLine(" };"); - } - else - { - builder.Append("var previousRolls = Array.Empty();"); - } + var previousRolls = method.Data.Input[PreviousRolls] as int[] ?? Array.Empty(); + builder.Append(Render.Variable("previousRolls", Render.ObjectMultiLine(previousRolls))); return builder.ToString(); } @@ -67,7 +59,7 @@ private string RenderAssert(TestMethod method) return Render.AssertThrows(method.Data.ExceptionThrown, "sut.Score()"); } - private static string RenderAct(TestMethod method) + private string RenderAct(TestMethod method) { var act = new StringBuilder(); act.AppendLine("DoRoll(previousRolls, sut);"); @@ -80,11 +72,11 @@ private static string RenderAct(TestMethod method) if (method.Data.Input.ContainsKey("roll")) { act.AppendLine($"sut.Roll({method.Data.Input["roll"]});"); - act.AppendLine("var actual = sut.Score();"); + act.AppendLine(Render.Variable("actual", "sut.Score()")); return act.ToString(); } - act.AppendLine("var actual = sut.Score();"); + act.AppendLine(Render.Variable("actual", "sut.Score()")); return act.ToString(); } diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index a72ad1b8e3..e8c0de408a 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -23,10 +23,10 @@ private string RenderAssert(TestMethod method) return assert.ToString(); } - private static string RenderSut(TestData canonicalDataCase) + private string RenderSut(TestData canonicalDataCase) { var capacity = canonicalDataCase.Input["capacity"]; - return $"var buffer = new CircularBuffer(capacity: {capacity});"; + return Render.Variable("buffer", $"new CircularBuffer(capacity: {capacity})"); } private string RenderOperation(dynamic operation) diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index 0ffe7862e0..ec54d057b3 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -35,8 +35,8 @@ private string RenderCanAttackAssert(TestMethod method) var (whiteQueenX, whiteQueenY) = GetCoordinatesFromPosition((IDictionary)method.Data.Input["white_queen"]); var (blackQueenX, blackQueenY) = GetCoordinatesFromPosition((IDictionary)method.Data.Input["black_queen"]); - assert.AppendLine($"var whiteQueen = QueenAttack.Create({whiteQueenX},{whiteQueenY});"); - assert.AppendLine($"var blackQueen = QueenAttack.Create({blackQueenX},{blackQueenY});"); + assert.AppendLine(Render.Variable("whiteQueen", $"QueenAttack.Create({whiteQueenX},{whiteQueenY})")); + assert.AppendLine(Render.Variable("blackQueen", $"QueenAttack.Create({blackQueenX},{blackQueenY})")); assert.AppendLine(Render.AssertBoolean((bool)method.Data.Expected, "QueenAttack.CanAttack(whiteQueen, blackQueen)")); return assert.ToString(); diff --git a/generators/Exercises/Generators/React.cs b/generators/Exercises/Generators/React.cs index 4c733452db..dbdfdc8d1b 100644 --- a/generators/Exercises/Generators/React.cs +++ b/generators/Exercises/Generators/React.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; +using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; using Humanizer; @@ -16,10 +17,10 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(); } - private static string RenderArrange(TestMethod method) + private string RenderArrange(TestMethod method) { var arrange = new StringBuilder(); - arrange.AppendLine("var sut = new Reactor();"); + arrange.AppendLine(Render.Variable("sut", "new Reactor()")); var cells = RenderCells(method.Data.Input["cells"]); arrange.AppendLine(cells); @@ -30,7 +31,7 @@ private static string RenderArrange(TestMethod method) return arrange.ToString(); } - private static string RenderCells(dynamic cells) + private string RenderCells(dynamic cells) { if (cells.Length == 0) { @@ -41,7 +42,7 @@ private static string RenderCells(dynamic cells) return string.Join(Environment.NewLine, renderedCells); } - private static string RenderCell(dynamic cell) + private string RenderCell(dynamic cell) { var cellType = (string)cell["type"]; var cellName = ToVariableName(cell["name"]); @@ -49,11 +50,11 @@ private static string RenderCell(dynamic cell) switch (cellType) { case "input": - return $"var {cellName} = sut.CreateInputCell({cell["initial_value"]});"; + return Render.Variable(cellName, $"sut.CreateInputCell({cell["initial_value"]})"); case "compute": var inputs = string.Join(", ", ((string[])cell["inputs"]).Select(ToVariableName)); var computeFunction = RenderComputeFunction(cell["compute_function"]); - return $"var {cellName} = sut.CreateComputeCell(new[] {{ {inputs} }}, inputs => {computeFunction});"; + return Render.Variable(cellName, $"sut.CreateComputeCell(new[] {{ {inputs} }}, inputs => {computeFunction})"); default: throw new InvalidOperationException($"Unknown cell type: {cellType}"); } @@ -68,7 +69,7 @@ private static string RenderComputeFunction(dynamic computeFunction) : (string)computeFunction; } - private static string RenderOperations(dynamic operations) + private string RenderOperations(dynamic operations) { if (operations.Length == 0) { @@ -79,7 +80,7 @@ private static string RenderOperations(dynamic operations) return string.Join(Environment.NewLine, renderedOperations); } - private static string RenderOperation(dynamic operation) + private string RenderOperation(dynamic operation) { var operationType = (string)operation["type"]; @@ -115,13 +116,13 @@ private static string RenderOperation(dynamic operation) return $"Assert.Equal({operation["value"]}, {ToVariableName(operation["cell"])}.Value);"; case "add_callback": var addCallbackName = ToVariableName(operation["name"]); - return $"var {addCallbackName} = A.Fake>();{Environment.NewLine}" + + return Render.Variable(addCallbackName, $"A.Fake>()") + Environment.NewLine + $"{ToVariableName(operation["cell"])}.Changed += {addCallbackName};"; case "remove_callback": var removeCallbackName = ToVariableName(operation["name"]); return $"{ToVariableName(operation["cell"])}.Changed -= {removeCallbackName};"; default: - return "qweqwe"; + throw new ArgumentOutOfRangeException(); } } @@ -133,6 +134,6 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add("FakeItEasy"); } - private static string ToVariableName(dynamic value) => ((string)value).Camelize(); + private static string ToVariableName(dynamic value) => ((string)value).ToVariableName(); } } \ No newline at end of file diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index 9019186f56..8688bd0746 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -18,7 +18,7 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderAct(TestMethod method) => $"var result = {method.TestedMethodInvocation};"; + private string RenderAct(TestMethod method) => Render.Variable("result", method.TestedMethodInvocation); private string RenderAssert(TestMethod method) { diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index b8721eade9..f5827cb3c0 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -14,15 +14,15 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private static string RenderArrange(TestMethod method) + private string RenderArrange(TestMethod method) { var arrange = new StringBuilder(); var tree = RenderTree(method.Data.Input["initialTree"]); - arrange.AppendLine($"var tree = {tree};"); - arrange.AppendLine("var sut = Zipper.FromTree(tree);"); + arrange.AppendLine(Render.Variable("tree", $"{tree}")); + arrange.AppendLine(Render.Variable("sut", $"Zipper.FromTree(tree)")); var operations = RenderOperations(method.Data.Input["operations"]); - arrange.AppendLine($"var actual = sut{operations};"); + arrange.AppendLine(Render.Variable("actual", $"sut{operations}")); return arrange.ToString(); } @@ -35,7 +35,7 @@ private string RenderAssert(TestMethod method) } var assert = new StringBuilder(); - assert.AppendLine($"var expected = {expected};"); + assert.AppendLine(Render.Variable("expected", expected)); assert.AppendLine(Render.AssertEqual("expected", "actual")); return assert.ToString(); } diff --git a/generators/Output/Rendering/RenderVariable.cs b/generators/Output/Rendering/RenderVariable.cs index f5ba768c31..ff00206e52 100644 --- a/generators/Output/Rendering/RenderVariable.cs +++ b/generators/Output/Rendering/RenderVariable.cs @@ -10,8 +10,8 @@ public IEnumerable Variables(IDictionary dict) => dict.Select(Variable).ToArray(); private string Variable(KeyValuePair kv) - => Variable(kv.Key.ToVariableName(), kv.Value); + => Variable(kv.Key.ToVariableName(), ObjectMultiLine(kv.Value)); - public string Variable(string name, object val) => $"var {name} = {ObjectMultiLine(val)};"; + public string Variable(string name, string value) => $"var {name} = {value};"; } } \ No newline at end of file diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index 6f3148910c..befa452d37 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -44,6 +44,7 @@ public string Render() return Template.Render(TemplateName, new { Name = Data.TestMethod, Data.Skip, Arrange, Act, Assert }); } + public string SutValue => $"new {Data.TestedClass}({ConstructorParameters})"; public string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : Renderer.Object(Data.Expected); @@ -53,11 +54,11 @@ public string Render() private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); - private string ExpectedVariableDeclaration => Renderer.Variable(ExpectedVariableName, Data.Expected); + private string ExpectedVariableDeclaration => Renderer.Variable(ExpectedVariableName, Renderer.ObjectMultiLine(Data.Expected)); private IEnumerable InputVariablesDeclaration => Renderer.Variables(Input); private IEnumerable ConstructorVariablesDeclaration => Renderer.Variables(ConstructorInput); - private IEnumerable SutVariableDeclaration => new[] { $"var {SutVariableName} = new {Data.TestedClass}({ConstructorParameters});" }; - private IEnumerable ActualVariableDeclaration => new[] { $"var {TestedVariableName} = {TestedMethodInvocation};" }; + private IEnumerable SutVariableDeclaration => new[] { Renderer.Variable(SutVariableName, SutValue) }; + private IEnumerable ActualVariableDeclaration => new[] { Renderer.Variable(TestedVariableName, TestedMethodInvocation) }; public IEnumerable Variables { From f70d7c46bf82f61b075bbd56a3fc617269582eb3 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 3 Jul 2018 19:35:47 +0200 Subject: [PATCH 75/97] generators: Refactor generators --- exercises/grep/GrepTest.cs | 45 +++++------- exercises/list-ops/ListOpsTest.cs | 4 +- exercises/queen-attack/QueenAttackTest.cs | 2 +- .../rational-numbers/RationalNumbersTest.cs | 66 ++++++++--------- .../RunLengthEncodingTest.cs | 26 +++---- exercises/sublist/SublistTest.cs | 34 ++++----- exercises/word-search/WordSearchTest.cs | 44 +++++------ .../Exercises/Generators/AllYourBase.cs | 4 +- generators/Exercises/Generators/Allergies.cs | 10 +-- .../Exercises/Generators/Alphametics.cs | 2 +- .../Exercises/Generators/BinarySearch.cs | 2 +- .../Exercises/Generators/BinarySearchTree.cs | 21 ++---- generators/Exercises/Generators/Bowling.cs | 13 +--- .../Exercises/Generators/CircularBuffer.cs | 17 ++--- generators/Exercises/Generators/Clock.cs | 6 +- .../Exercises/Generators/CollatzConjecture.cs | 3 +- .../Exercises/Generators/ComplexNumbers.cs | 14 ++-- generators/Exercises/Generators/CustomSet.cs | 5 +- .../Generators/DifferenceOfSquares.cs | 13 +--- generators/Exercises/Generators/Dominoes.cs | 6 +- generators/Exercises/Generators/Etl.cs | 7 +- .../Exercises/Generators/FlattenArray.cs | 4 +- generators/Exercises/Generators/Gigasecond.cs | 10 +-- generators/Exercises/Generators/GoCounting.cs | 2 +- generators/Exercises/Generators/Grains.cs | 4 +- generators/Exercises/Generators/Grep.cs | 14 +--- generators/Exercises/Generators/Hamming.cs | 3 +- .../Generators/KindergartenGarden.cs | 9 ++- .../Generators/LargestSeriesProduct.cs | 4 +- generators/Exercises/Generators/ListOps.cs | 73 +++++++------------ generators/Exercises/Generators/NthPrime.cs | 3 +- .../Exercises/Generators/NucleotideCount.cs | 4 +- generators/Exercises/Generators/OcrNumbers.cs | 4 +- .../Generators/PalindromeProducts.cs | 4 +- .../Exercises/Generators/PhoneNumber.cs | 4 +- generators/Exercises/Generators/Pov.cs | 19 ++--- .../Exercises/Generators/QueenAttack.cs | 32 ++++---- .../Exercises/Generators/RationalNumbers.cs | 63 ++++------------ generators/Exercises/Generators/React.cs | 26 +------ generators/Exercises/Generators/Rectangles.cs | 7 +- .../Exercises/Generators/RnaTranscription.cs | 3 +- .../Exercises/Generators/RobotSimulator.cs | 57 +++++---------- .../Exercises/Generators/RunLengthEncoding.cs | 8 +- .../Exercises/Generators/SaddlePoints.cs | 11 +-- generators/Exercises/Generators/Say.cs | 4 +- generators/Exercises/Generators/Sieve.cs | 4 +- .../Exercises/Generators/SpiralMatrix.cs | 6 +- generators/Exercises/Generators/Sublist.cs | 16 ++-- generators/Exercises/Generators/Triangle.cs | 4 +- .../Generators/VariableLengthQuantity.cs | 20 ++--- generators/Exercises/Generators/WordCount.cs | 5 +- generators/Exercises/Generators/WordSearch.cs | 50 ++++++------- generators/Exercises/Generators/Wordy.cs | 3 +- generators/Exercises/Generators/Zipper.cs | 27 +++---- generators/Helpers/NameExtensions.cs | 4 +- generators/Input/JTokenHelper.cs | 12 +-- generators/Output/Rendering/Render.cs | 1 + generators/Output/Rendering/RenderArray.cs | 5 +- .../Output/Rendering/RenderCollection.cs | 2 +- generators/Output/Rendering/RenderNumber.cs | 2 + generators/Output/Rendering/RenderString.cs | 18 +++-- 61 files changed, 367 insertions(+), 528 deletions(-) diff --git a/exercises/grep/GrepTest.cs b/exercises/grep/GrepTest.cs index 5576c9f93d..2c6f0c1e77 100644 --- a/exercises/grep/GrepTest.cs +++ b/exercises/grep/GrepTest.cs @@ -12,8 +12,7 @@ public void One_file_one_match_no_flags() var pattern = "Agamemnon"; var flags = ""; var files = new[] { "iliad.txt" }; - var expected = - "Of Atreus, Agamemnon, King of men.\n"; + var expected = "Of Atreus, Agamemnon, King of men."; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -23,8 +22,7 @@ public void One_file_one_match_print_line_numbers_flag() var pattern = "Forbidden"; var flags = "-n"; var files = new[] { "paradise-lost.txt" }; - var expected = - "2:Of that Forbidden Tree, whose mortal tast\n"; + var expected = "2:Of that Forbidden Tree, whose mortal tast"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -34,8 +32,7 @@ public void One_file_one_match_case_insensitive_flag() var pattern = "FORBIDDEN"; var flags = "-i"; var files = new[] { "paradise-lost.txt" }; - var expected = - "Of that Forbidden Tree, whose mortal tast\n"; + var expected = "Of that Forbidden Tree, whose mortal tast"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -45,8 +42,7 @@ public void One_file_one_match_print_file_names_flag() var pattern = "Forbidden"; var flags = "-l"; var files = new[] { "paradise-lost.txt" }; - var expected = - "paradise-lost.txt\n"; + var expected = "paradise-lost.txt"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -56,8 +52,7 @@ public void One_file_one_match_match_entire_lines_flag() var pattern = "With loss of Eden, till one greater Man"; var flags = "-x"; var files = new[] { "paradise-lost.txt" }; - var expected = - "With loss of Eden, till one greater Man\n"; + var expected = "With loss of Eden, till one greater Man"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -67,8 +62,7 @@ public void One_file_one_match_multiple_flags() var pattern = "OF ATREUS, Agamemnon, KIng of MEN."; var flags = "-n -i -x"; var files = new[] { "iliad.txt" }; - var expected = - "9:Of Atreus, Agamemnon, King of men.\n"; + var expected = "9:Of Atreus, Agamemnon, King of men."; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -81,7 +75,7 @@ public void One_file_several_matches_no_flags() var expected = "Nor how it may concern my modesty,\n" + "But I beseech your grace that I may know\n" + - "The worst that may befall me in this case,\n"; + "The worst that may befall me in this case,"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -94,7 +88,7 @@ public void One_file_several_matches_print_line_numbers_flag() var expected = "3:Nor how it may concern my modesty,\n" + "5:But I beseech your grace that I may know\n" + - "6:The worst that may befall me in this case,\n"; + "6:The worst that may befall me in this case,"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -116,7 +110,7 @@ public void One_file_several_matches_case_insensitive_flag() var files = new[] { "iliad.txt" }; var expected = "Achilles sing, O Goddess! Peleus' son;\n" + - "The noble Chief Achilles from the son\n"; + "The noble Chief Achilles from the son"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -131,7 +125,7 @@ public void One_file_several_matches_inverted_flag() "With loss of Eden, till one greater Man\n" + "Restore us, and regain the blissful Seat,\n" + "Sing Heav'nly Muse, that on the secret top\n" + - "That Shepherd, who first taught the chosen Seed\n"; + "That Shepherd, who first taught the chosen Seed"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -151,8 +145,7 @@ public void Multiple_files_one_match_no_flags() var pattern = "Agamemnon"; var flags = ""; var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; - var expected = - "iliad.txt:Of Atreus, Agamemnon, King of men.\n"; + var expected = "iliad.txt:Of Atreus, Agamemnon, King of men."; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -165,7 +158,7 @@ public void Multiple_files_several_matches_no_flags() var expected = "midsummer-night.txt:Nor how it may concern my modesty,\n" + "midsummer-night.txt:But I beseech your grace that I may know\n" + - "midsummer-night.txt:The worst that may befall me in this case,\n"; + "midsummer-night.txt:The worst that may befall me in this case,"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -179,7 +172,7 @@ public void Multiple_files_several_matches_print_line_numbers_flag() "midsummer-night.txt:5:But I beseech your grace that I may know\n" + "midsummer-night.txt:6:The worst that may befall me in this case,\n" + "paradise-lost.txt:2:Of that Forbidden Tree, whose mortal tast\n" + - "paradise-lost.txt:6:Sing Heav'nly Muse, that on the secret top\n"; + "paradise-lost.txt:6:Sing Heav'nly Muse, that on the secret top"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -191,7 +184,7 @@ public void Multiple_files_one_match_print_file_names_flag() var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; var expected = "iliad.txt\n" + - "paradise-lost.txt\n"; + "paradise-lost.txt"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -211,7 +204,7 @@ public void Multiple_files_several_matches_case_insensitive_flag() "midsummer-night.txt:If I refuse to wed Demetrius.\n" + "paradise-lost.txt:Brought Death into the World, and all our woe,\n" + "paradise-lost.txt:Restore us, and regain the blissful Seat,\n" + - "paradise-lost.txt:Sing Heav'nly Muse, that on the secret top\n"; + "paradise-lost.txt:Sing Heav'nly Muse, that on the secret top"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -224,7 +217,7 @@ public void Multiple_files_several_matches_inverted_flag() var expected = "iliad.txt:Achilles sing, O Goddess! Peleus' son;\n" + "iliad.txt:The noble Chief Achilles from the son\n" + - "midsummer-night.txt:If I refuse to wed Demetrius.\n"; + "midsummer-night.txt:If I refuse to wed Demetrius."; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -234,8 +227,7 @@ public void Multiple_files_one_match_match_entire_lines_flag() var pattern = "But I beseech your grace that I may know"; var flags = "-x"; var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; - var expected = - "midsummer-night.txt:But I beseech your grace that I may know\n"; + var expected = "midsummer-night.txt:But I beseech your grace that I may know"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } @@ -245,8 +237,7 @@ public void Multiple_files_one_match_multiple_flags() var pattern = "WITH LOSS OF EDEN, TILL ONE GREATER MAN"; var flags = "-n -i -x"; var files = new[] { "iliad.txt", "midsummer-night.txt", "paradise-lost.txt" }; - var expected = - "paradise-lost.txt:4:With loss of Eden, till one greater Man\n"; + var expected = "paradise-lost.txt:4:With loss of Eden, till one greater Man"; Assert.Equal(expected, Grep.Match(pattern, flags, files)); } diff --git a/exercises/list-ops/ListOpsTest.cs b/exercises/list-ops/ListOpsTest.cs index cd86fcec64..99c5cbcf81 100644 --- a/exercises/list-ops/ListOpsTest.cs +++ b/exercises/list-ops/ListOpsTest.cs @@ -35,7 +35,7 @@ public void Append_entries_to_a_list_and_return_the_new_list_non_empty_lists() [Fact(Skip = "Remove to run test")] public void Concatenate_a_list_of_lists_empty_list() { - var lists = new List>(); + var lists = new List(); Assert.Empty(ListOps.Concat(lists)); } @@ -50,7 +50,7 @@ public void Concatenate_a_list_of_lists_list_of_lists() [Fact(Skip = "Remove to run test")] public void Concatenate_a_list_of_lists_list_of_nested_lists() { - var lists = new List { new List { new List { 1 }, new List { 2 } }, new List { new List { 3 } }, new List { new List() }, new List { new List { 4, 5, 6 } } }; + var lists = new List>> { new List> { new List { 1 }, new List { 2 } }, new List> { new List { 3 } }, new List> { new List() }, new List> { new List { 4, 5, 6 } } }; var expected = new List> { new List { 1 }, new List { 2 }, new List { 3 }, new List(), new List { 4, 5, 6 } }; Assert.Equal(expected, ListOps.Concat(lists)); } diff --git a/exercises/queen-attack/QueenAttackTest.cs b/exercises/queen-attack/QueenAttackTest.cs index cda7d9298d..288b173516 100644 --- a/exercises/queen-attack/QueenAttackTest.cs +++ b/exercises/queen-attack/QueenAttackTest.cs @@ -6,7 +6,7 @@ public class QueenAttackTest { [Fact] - public void Queen_with_a_valid_position_does_not_throw_exception() + public void Queen_with_a_valid_position() { var actual = QueenAttack.Create(2, 2); } diff --git a/exercises/rational-numbers/RationalNumbersTest.cs b/exercises/rational-numbers/RationalNumbersTest.cs index 94ec6118f0..b7325b11b2 100644 --- a/exercises/rational-numbers/RationalNumbersTest.cs +++ b/exercises/rational-numbers/RationalNumbersTest.cs @@ -7,163 +7,163 @@ public class RationalNumbersTest [Fact] public void Add_two_positive_rational_numbers() { - Assert.Equal(new RationalNumber (7, 6), new RationalNumber(1, 2) + (new RationalNumber(2, 3))); + Assert.Equal(new RationalNumber(7, 6), new RationalNumber(1, 2) + (new RationalNumber(2, 3))); } [Fact(Skip = "Remove to run test")] public void Add_a_positive_rational_number_and_a_negative_rational_number() { - Assert.Equal(new RationalNumber (-1, 6), new RationalNumber(1, 2) + (new RationalNumber(-2, 3))); + Assert.Equal(new RationalNumber(-1, 6), new RationalNumber(1, 2) + (new RationalNumber(-2, 3))); } [Fact(Skip = "Remove to run test")] public void Add_two_negative_rational_numbers() { - Assert.Equal(new RationalNumber (-7, 6), new RationalNumber(-1, 2) + (new RationalNumber(-2, 3))); + Assert.Equal(new RationalNumber(-7, 6), new RationalNumber(-1, 2) + (new RationalNumber(-2, 3))); } [Fact(Skip = "Remove to run test")] public void Add_a_rational_number_to_its_additive_inverse() { - Assert.Equal(new RationalNumber (0, 1), new RationalNumber(1, 2) + (new RationalNumber(-1, 2))); + Assert.Equal(new RationalNumber(0, 1), new RationalNumber(1, 2) + (new RationalNumber(-1, 2))); } [Fact(Skip = "Remove to run test")] public void Subtract_two_positive_rational_numbers() { - Assert.Equal(new RationalNumber (-1, 6), new RationalNumber(1, 2) - (new RationalNumber(2, 3))); + Assert.Equal(new RationalNumber(-1, 6), new RationalNumber(1, 2) - (new RationalNumber(2, 3))); } [Fact(Skip = "Remove to run test")] public void Subtract_a_positive_rational_number_and_a_negative_rational_number() { - Assert.Equal(new RationalNumber (7, 6), new RationalNumber(1, 2) - (new RationalNumber(-2, 3))); + Assert.Equal(new RationalNumber(7, 6), new RationalNumber(1, 2) - (new RationalNumber(-2, 3))); } [Fact(Skip = "Remove to run test")] public void Subtract_two_negative_rational_numbers() { - Assert.Equal(new RationalNumber (1, 6), new RationalNumber(-1, 2) - (new RationalNumber(-2, 3))); + Assert.Equal(new RationalNumber(1, 6), new RationalNumber(-1, 2) - (new RationalNumber(-2, 3))); } [Fact(Skip = "Remove to run test")] public void Subtract_a_rational_number_from_itself() { - Assert.Equal(new RationalNumber (0, 1), new RationalNumber(1, 2) - (new RationalNumber(1, 2))); + Assert.Equal(new RationalNumber(0, 1), new RationalNumber(1, 2) - (new RationalNumber(1, 2))); } [Fact(Skip = "Remove to run test")] public void Multiply_two_positive_rational_numbers() { - Assert.Equal(new RationalNumber (1, 3), new RationalNumber(1, 2) * (new RationalNumber(2, 3))); + Assert.Equal(new RationalNumber(1, 3), new RationalNumber(1, 2) * (new RationalNumber(2, 3))); } [Fact(Skip = "Remove to run test")] public void Multiply_a_negative_rational_number_by_a_positive_rational_number() { - Assert.Equal(new RationalNumber (-1, 3), new RationalNumber(-1, 2) * (new RationalNumber(2, 3))); + Assert.Equal(new RationalNumber(-1, 3), new RationalNumber(-1, 2) * (new RationalNumber(2, 3))); } [Fact(Skip = "Remove to run test")] public void Multiply_two_negative_rational_numbers() { - Assert.Equal(new RationalNumber (1, 3), new RationalNumber(-1, 2) * (new RationalNumber(-2, 3))); + Assert.Equal(new RationalNumber(1, 3), new RationalNumber(-1, 2) * (new RationalNumber(-2, 3))); } [Fact(Skip = "Remove to run test")] public void Multiply_a_rational_number_by_its_reciprocal() { - Assert.Equal(new RationalNumber (1, 1), new RationalNumber(1, 2) * (new RationalNumber(2, 1))); + Assert.Equal(new RationalNumber(1, 1), new RationalNumber(1, 2) * (new RationalNumber(2, 1))); } [Fact(Skip = "Remove to run test")] public void Multiply_a_rational_number_by_1() { - Assert.Equal(new RationalNumber (1, 2), new RationalNumber(1, 2) * (new RationalNumber(1, 1))); + Assert.Equal(new RationalNumber(1, 2), new RationalNumber(1, 2) * (new RationalNumber(1, 1))); } [Fact(Skip = "Remove to run test")] public void Multiply_a_rational_number_by_0() { - Assert.Equal(new RationalNumber (0, 1), new RationalNumber(1, 2) * (new RationalNumber(0, 1))); + Assert.Equal(new RationalNumber(0, 1), new RationalNumber(1, 2) * (new RationalNumber(0, 1))); } [Fact(Skip = "Remove to run test")] public void Divide_two_positive_rational_numbers() { - Assert.Equal(new RationalNumber (3, 4), new RationalNumber(1, 2) / (new RationalNumber(2, 3))); + Assert.Equal(new RationalNumber(3, 4), new RationalNumber(1, 2) / (new RationalNumber(2, 3))); } [Fact(Skip = "Remove to run test")] public void Divide_a_positive_rational_number_by_a_negative_rational_number() { - Assert.Equal(new RationalNumber (-3, 4), new RationalNumber(1, 2) / (new RationalNumber(-2, 3))); + Assert.Equal(new RationalNumber(-3, 4), new RationalNumber(1, 2) / (new RationalNumber(-2, 3))); } [Fact(Skip = "Remove to run test")] public void Divide_two_negative_rational_numbers() { - Assert.Equal(new RationalNumber (3, 4), new RationalNumber(-1, 2) / (new RationalNumber(-2, 3))); + Assert.Equal(new RationalNumber(3, 4), new RationalNumber(-1, 2) / (new RationalNumber(-2, 3))); } [Fact(Skip = "Remove to run test")] public void Divide_a_rational_number_by_1() { - Assert.Equal(new RationalNumber (1, 2), new RationalNumber(1, 2) / (new RationalNumber(1, 1))); + Assert.Equal(new RationalNumber(1, 2), new RationalNumber(1, 2) / (new RationalNumber(1, 1))); } [Fact(Skip = "Remove to run test")] public void Absolute_value_of_a_positive_rational_number() { - Assert.Equal(new RationalNumber (1, 2), new RationalNumber(1, 2).Abs()); + Assert.Equal(new RationalNumber(1, 2), new RationalNumber(1, 2).Abs()); } [Fact(Skip = "Remove to run test")] public void Absolute_value_of_a_negative_rational_number() { - Assert.Equal(new RationalNumber (1, 2), new RationalNumber(-1, 2).Abs()); + Assert.Equal(new RationalNumber(1, 2), new RationalNumber(-1, 2).Abs()); } [Fact(Skip = "Remove to run test")] public void Absolute_value_of_zero() { - Assert.Equal(new RationalNumber (0, 1), new RationalNumber(0, 1).Abs()); + Assert.Equal(new RationalNumber(0, 1), new RationalNumber(0, 1).Abs()); } [Fact(Skip = "Remove to run test")] public void Raise_a_positive_rational_number_to_a_positive_integer_power() { - Assert.Equal(new RationalNumber (1, 8), new RationalNumber(1, 2).Exprational(3)); + Assert.Equal(new RationalNumber(1, 8), new RationalNumber(1, 2).Exprational(3)); } [Fact(Skip = "Remove to run test")] public void Raise_a_negative_rational_number_to_a_positive_integer_power() { - Assert.Equal(new RationalNumber (-1, 8), new RationalNumber(-1, 2).Exprational(3)); + Assert.Equal(new RationalNumber(-1, 8), new RationalNumber(-1, 2).Exprational(3)); } [Fact(Skip = "Remove to run test")] public void Raise_zero_to_an_integer_power() { - Assert.Equal(new RationalNumber (0, 1), new RationalNumber(0, 1).Exprational(5)); + Assert.Equal(new RationalNumber(0, 1), new RationalNumber(0, 1).Exprational(5)); } [Fact(Skip = "Remove to run test")] public void Raise_one_to_an_integer_power() { - Assert.Equal(new RationalNumber (1, 1), new RationalNumber(1, 1).Exprational(4)); + Assert.Equal(new RationalNumber(1, 1), new RationalNumber(1, 1).Exprational(4)); } [Fact(Skip = "Remove to run test")] public void Raise_a_positive_rational_number_to_the_power_of_zero() { - Assert.Equal(new RationalNumber (1, 1), new RationalNumber(1, 2).Exprational(0)); + Assert.Equal(new RationalNumber(1, 1), new RationalNumber(1, 2).Exprational(0)); } [Fact(Skip = "Remove to run test")] public void Raise_a_negative_rational_number_to_the_power_of_zero() { - Assert.Equal(new RationalNumber (1, 1), new RationalNumber(-1, 2).Exprational(0)); + Assert.Equal(new RationalNumber(1, 1), new RationalNumber(-1, 2).Exprational(0)); } [Fact(Skip = "Remove to run test")] @@ -187,36 +187,36 @@ public void Raise_a_real_number_to_a_zero_rational_number() [Fact(Skip = "Remove to run test")] public void Reduce_a_positive_rational_number_to_lowest_terms() { - Assert.Equal(new RationalNumber (1, 2), new RationalNumber(2, 4).Reduce()); + Assert.Equal(new RationalNumber(1, 2), new RationalNumber(2, 4).Reduce()); } [Fact(Skip = "Remove to run test")] public void Reduce_a_negative_rational_number_to_lowest_terms() { - Assert.Equal(new RationalNumber (-2, 3), new RationalNumber(-4, 6).Reduce()); + Assert.Equal(new RationalNumber(-2, 3), new RationalNumber(-4, 6).Reduce()); } [Fact(Skip = "Remove to run test")] public void Reduce_a_rational_number_with_a_negative_denominator_to_lowest_terms() { - Assert.Equal(new RationalNumber (-1, 3), new RationalNumber(3, -9).Reduce()); + Assert.Equal(new RationalNumber(-1, 3), new RationalNumber(3, -9).Reduce()); } [Fact(Skip = "Remove to run test")] public void Reduce_zero_to_lowest_terms() { - Assert.Equal(new RationalNumber (0, 1), new RationalNumber(0, 6).Reduce()); + Assert.Equal(new RationalNumber(0, 1), new RationalNumber(0, 6).Reduce()); } [Fact(Skip = "Remove to run test")] public void Reduce_an_integer_to_lowest_terms() { - Assert.Equal(new RationalNumber (-2, 1), new RationalNumber(-14, 7).Reduce()); + Assert.Equal(new RationalNumber(-2, 1), new RationalNumber(-14, 7).Reduce()); } [Fact(Skip = "Remove to run test")] public void Reduce_one_to_lowest_terms() { - Assert.Equal(new RationalNumber (1, 1), new RationalNumber(13, 13).Reduce()); + Assert.Equal(new RationalNumber(1, 1), new RationalNumber(13, 13).Reduce()); } } \ No newline at end of file diff --git a/exercises/run-length-encoding/RunLengthEncodingTest.cs b/exercises/run-length-encoding/RunLengthEncodingTest.cs index f840783774..ee21c7421e 100644 --- a/exercises/run-length-encoding/RunLengthEncodingTest.cs +++ b/exercises/run-length-encoding/RunLengthEncodingTest.cs @@ -5,79 +5,79 @@ public class RunLengthEncodingTest { [Fact] - public void Encode_empty_string() + public void Run_length_encode_a_string_empty_string() { Assert.Equal("", RunLengthEncoding.Encode("")); } [Fact(Skip = "Remove to run test")] - public void Encode_single_characters_only_are_encoded_without_count() + public void Run_length_encode_a_string_single_characters_only_are_encoded_without_count() { Assert.Equal("XYZ", RunLengthEncoding.Encode("XYZ")); } [Fact(Skip = "Remove to run test")] - public void Encode_string_with_no_single_characters() + public void Run_length_encode_a_string_string_with_no_single_characters() { Assert.Equal("2A3B4C", RunLengthEncoding.Encode("AABBBCCCC")); } [Fact(Skip = "Remove to run test")] - public void Encode_single_characters_mixed_with_repeated_characters() + public void Run_length_encode_a_string_single_characters_mixed_with_repeated_characters() { Assert.Equal("12WB12W3B24WB", RunLengthEncoding.Encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB")); } [Fact(Skip = "Remove to run test")] - public void Encode_multiple_whitespace_mixed_in_string() + public void Run_length_encode_a_string_multiple_whitespace_mixed_in_string() { Assert.Equal("2 hs2q q2w2 ", RunLengthEncoding.Encode(" hsqq qww ")); } [Fact(Skip = "Remove to run test")] - public void Encode_lowercase_characters() + public void Run_length_encode_a_string_lowercase_characters() { Assert.Equal("2a3b4c", RunLengthEncoding.Encode("aabbbcccc")); } [Fact(Skip = "Remove to run test")] - public void Decode_empty_string() + public void Run_length_decode_a_string_empty_string() { Assert.Equal("", RunLengthEncoding.Decode("")); } [Fact(Skip = "Remove to run test")] - public void Decode_single_characters_only() + public void Run_length_decode_a_string_single_characters_only() { Assert.Equal("XYZ", RunLengthEncoding.Decode("XYZ")); } [Fact(Skip = "Remove to run test")] - public void Decode_string_with_no_single_characters() + public void Run_length_decode_a_string_string_with_no_single_characters() { Assert.Equal("AABBBCCCC", RunLengthEncoding.Decode("2A3B4C")); } [Fact(Skip = "Remove to run test")] - public void Decode_single_characters_with_repeated_characters() + public void Run_length_decode_a_string_single_characters_with_repeated_characters() { Assert.Equal("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB", RunLengthEncoding.Decode("12WB12W3B24WB")); } [Fact(Skip = "Remove to run test")] - public void Decode_multiple_whitespace_mixed_in_string() + public void Run_length_decode_a_string_multiple_whitespace_mixed_in_string() { Assert.Equal(" hsqq qww ", RunLengthEncoding.Decode("2 hs2q q2w2 ")); } [Fact(Skip = "Remove to run test")] - public void Decode_lower_case_string() + public void Run_length_decode_a_string_lower_case_string() { Assert.Equal("aabbbcccc", RunLengthEncoding.Decode("2a3b4c")); } [Fact(Skip = "Remove to run test")] - public void Consistency_encode_followed_by_decode_gives_original_string() + public void Encode_and_then_decode_encode_followed_by_decode_gives_original_string() { Assert.Equal("zzz ZZ zZ", RunLengthEncoding.Decode(RunLengthEncoding.Encode("zzz ZZ zZ"))); } diff --git a/exercises/sublist/SublistTest.cs b/exercises/sublist/SublistTest.cs index 1a8005f6e9..b40e94a316 100644 --- a/exercises/sublist/SublistTest.cs +++ b/exercises/sublist/SublistTest.cs @@ -8,102 +8,102 @@ public class SublistTest [Fact] public void Empty_lists() { - Assert.Equal(SublistType.Equal, Sublist.Classify(new List() { }, new List() { })); + Assert.Equal(SublistType.Equal, Sublist.Classify(new List(), new List())); } [Fact(Skip = "Remove to run test")] public void Empty_list_within_non_empty_list() { - Assert.Equal(SublistType.Sublist, Sublist.Classify(new List() { }, new List() { 1, 2, 3 })); + Assert.Equal(SublistType.Sublist, Sublist.Classify(new List(), new List { 1, 2, 3 })); } [Fact(Skip = "Remove to run test")] public void Non_empty_list_contains_empty_list() { - Assert.Equal(SublistType.Superlist, Sublist.Classify(new List() { 1, 2, 3 }, new List() { })); + Assert.Equal(SublistType.Superlist, Sublist.Classify(new List { 1, 2, 3 }, new List())); } [Fact(Skip = "Remove to run test")] public void List_equals_itself() { - Assert.Equal(SublistType.Equal, Sublist.Classify(new List() { 1, 2, 3 }, new List() { 1, 2, 3 })); + Assert.Equal(SublistType.Equal, Sublist.Classify(new List { 1, 2, 3 }, new List { 1, 2, 3 })); } [Fact(Skip = "Remove to run test")] public void Different_lists() { - Assert.Equal(SublistType.Unequal, Sublist.Classify(new List() { 1, 2, 3 }, new List() { 2, 3, 4 })); + Assert.Equal(SublistType.Unequal, Sublist.Classify(new List { 1, 2, 3 }, new List { 2, 3, 4 })); } [Fact(Skip = "Remove to run test")] public void False_start() { - Assert.Equal(SublistType.Sublist, Sublist.Classify(new List() { 1, 2, 5 }, new List() { 0, 1, 2, 3, 1, 2, 5, 6 })); + Assert.Equal(SublistType.Sublist, Sublist.Classify(new List { 1, 2, 5 }, new List { 0, 1, 2, 3, 1, 2, 5, 6 })); } [Fact(Skip = "Remove to run test")] public void Consecutive() { - Assert.Equal(SublistType.Sublist, Sublist.Classify(new List() { 1, 1, 2 }, new List() { 0, 1, 1, 1, 2, 1, 2 })); + Assert.Equal(SublistType.Sublist, Sublist.Classify(new List { 1, 1, 2 }, new List { 0, 1, 1, 1, 2, 1, 2 })); } [Fact(Skip = "Remove to run test")] public void Sublist_at_start() { - Assert.Equal(SublistType.Sublist, Sublist.Classify(new List() { 0, 1, 2 }, new List() { 0, 1, 2, 3, 4, 5 })); + Assert.Equal(SublistType.Sublist, Sublist.Classify(new List { 0, 1, 2 }, new List { 0, 1, 2, 3, 4, 5 })); } [Fact(Skip = "Remove to run test")] public void Sublist_in_middle() { - Assert.Equal(SublistType.Sublist, Sublist.Classify(new List() { 2, 3, 4 }, new List() { 0, 1, 2, 3, 4, 5 })); + Assert.Equal(SublistType.Sublist, Sublist.Classify(new List { 2, 3, 4 }, new List { 0, 1, 2, 3, 4, 5 })); } [Fact(Skip = "Remove to run test")] public void Sublist_at_end() { - Assert.Equal(SublistType.Sublist, Sublist.Classify(new List() { 3, 4, 5 }, new List() { 0, 1, 2, 3, 4, 5 })); + Assert.Equal(SublistType.Sublist, Sublist.Classify(new List { 3, 4, 5 }, new List { 0, 1, 2, 3, 4, 5 })); } [Fact(Skip = "Remove to run test")] public void At_start_of_superlist() { - Assert.Equal(SublistType.Superlist, Sublist.Classify(new List() { 0, 1, 2, 3, 4, 5 }, new List() { 0, 1, 2 })); + Assert.Equal(SublistType.Superlist, Sublist.Classify(new List { 0, 1, 2, 3, 4, 5 }, new List { 0, 1, 2 })); } [Fact(Skip = "Remove to run test")] public void In_middle_of_superlist() { - Assert.Equal(SublistType.Superlist, Sublist.Classify(new List() { 0, 1, 2, 3, 4, 5 }, new List() { 2, 3 })); + Assert.Equal(SublistType.Superlist, Sublist.Classify(new List { 0, 1, 2, 3, 4, 5 }, new List { 2, 3 })); } [Fact(Skip = "Remove to run test")] public void At_end_of_superlist() { - Assert.Equal(SublistType.Superlist, Sublist.Classify(new List() { 0, 1, 2, 3, 4, 5 }, new List() { 3, 4, 5 })); + Assert.Equal(SublistType.Superlist, Sublist.Classify(new List { 0, 1, 2, 3, 4, 5 }, new List { 3, 4, 5 })); } [Fact(Skip = "Remove to run test")] public void First_list_missing_element_from_second_list() { - Assert.Equal(SublistType.Unequal, Sublist.Classify(new List() { 1, 3 }, new List() { 1, 2, 3 })); + Assert.Equal(SublistType.Unequal, Sublist.Classify(new List { 1, 3 }, new List { 1, 2, 3 })); } [Fact(Skip = "Remove to run test")] public void Second_list_missing_element_from_first_list() { - Assert.Equal(SublistType.Unequal, Sublist.Classify(new List() { 1, 2, 3 }, new List() { 1, 3 })); + Assert.Equal(SublistType.Unequal, Sublist.Classify(new List { 1, 2, 3 }, new List { 1, 3 })); } [Fact(Skip = "Remove to run test")] public void Order_matters_to_a_list() { - Assert.Equal(SublistType.Unequal, Sublist.Classify(new List() { 1, 2, 3 }, new List() { 3, 2, 1 })); + Assert.Equal(SublistType.Unequal, Sublist.Classify(new List { 1, 2, 3 }, new List { 3, 2, 1 })); } [Fact(Skip = "Remove to run test")] public void Same_digits_but_different_numbers() { - Assert.Equal(SublistType.Unequal, Sublist.Classify(new List() { 1, 0, 1 }, new List() { 10, 1 })); + Assert.Equal(SublistType.Unequal, Sublist.Classify(new List { 1, 0, 1 }, new List { 10, 1 })); } } \ No newline at end of file diff --git a/exercises/word-search/WordSearchTest.cs b/exercises/word-search/WordSearchTest.cs index 1f98fd0a20..8247c664a0 100644 --- a/exercises/word-search/WordSearchTest.cs +++ b/exercises/word-search/WordSearchTest.cs @@ -13,9 +13,9 @@ public void Should_accept_an_initial_game_grid_and_a_target_search_word() var grid = "jefblpepre"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { - ["clojure"] = null + ["clojure"] = }; Assert.Null(expected["clojure"]); } @@ -27,7 +27,7 @@ public void Should_locate_one_word_written_left_to_right() var grid = "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 1), (7, 1)) }; @@ -41,7 +41,7 @@ public void Should_locate_the_same_word_written_left_to_right_in_a_different_pos var grid = "mtclojurer"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((3, 1), (9, 1)) }; @@ -55,7 +55,7 @@ public void Should_locate_a_different_left_to_right_word() var grid = "coffeelplx"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["coffee"] = ((1, 1), (6, 1)) }; @@ -69,7 +69,7 @@ public void Should_locate_that_different_left_to_right_word_in_a_different_posit var grid = "xcoffeezlp"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["coffee"] = ((2, 1), (7, 1)) }; @@ -85,7 +85,7 @@ public void Should_locate_a_left_to_right_word_in_two_line_grid() "tclojurerm"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((2, 2), (8, 2)) }; @@ -102,7 +102,7 @@ public void Should_locate_a_left_to_right_word_in_three_line_grid() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 3), (7, 3)) }; @@ -126,7 +126,7 @@ public void Should_locate_a_left_to_right_word_in_ten_line_grid() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)) }; @@ -150,7 +150,7 @@ public void Should_locate_that_left_to_right_word_in_a_different_position_in_a_t "jalaycalmp"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 9), (7, 9)) }; @@ -174,7 +174,7 @@ public void Should_locate_a_different_left_to_right_word_in_a_ten_line_grid() "jalaycalmp"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["fortran"] = ((1, 7), (7, 7)) }; @@ -198,7 +198,7 @@ public void Should_locate_multiple_words() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["fortran"] = ((1, 7), (7, 7)) @@ -214,7 +214,7 @@ public void Should_locate_a_single_word_written_right_to_left() var grid = "rixilelhrs"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["elixir"] = ((6, 1), (1, 1)) }; @@ -238,7 +238,7 @@ public void Should_locate_multiple_words_written_in_different_horizontal_directi "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)) @@ -264,7 +264,7 @@ public void Should_locate_words_written_top_to_bottom() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -292,7 +292,7 @@ public void Should_locate_words_written_bottom_to_top() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -322,7 +322,7 @@ public void Should_locate_words_written_top_left_to_bottom_right() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -354,7 +354,7 @@ public void Should_locate_words_written_bottom_right_to_top_left() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -397,7 +397,7 @@ public void Should_locate_words_written_bottom_left_to_top_right() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -443,7 +443,7 @@ public void Should_locate_words_written_top_right_to_bottom_left() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -492,7 +492,7 @@ public void Should_fail_to_locate_a_word_that_is_not_in_the_puzzle() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -502,7 +502,7 @@ public void Should_fail_to_locate_a_word_that_is_not_in_the_puzzle() ["lua"] = ((8, 9), (6, 7)), ["lisp"] = ((3, 6), (6, 3)), ["ruby"] = ((8, 6), (5, 9)), - ["haskell"] = null + ["haskell"] = }; Assert.Equal(expected["clojure"], actual["clojure"]); Assert.Equal(expected["elixir"], actual["elixir"]); diff --git a/generators/Exercises/Generators/AllYourBase.cs b/generators/Exercises/Generators/AllYourBase.cs index 5289f102e3..bc1b23ac26 100644 --- a/generators/Exercises/Generators/AllYourBase.cs +++ b/generators/Exercises/Generators/AllYourBase.cs @@ -12,7 +12,9 @@ protected override void UpdateTestData(TestData data) if (data.Input["digits"] is JArray) data.Input["digits"] = Array.Empty(); - data.ExceptionThrown = data.Expected is Dictionary ? typeof(ArgumentException) : null; + if (data.Expected is Dictionary) + data.ExceptionThrown = typeof(ArgumentException); + data.UseVariablesForInput = true; data.UseVariableForExpected = true; } diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index 633bcd3d9e..b25d8e6c82 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -8,7 +8,7 @@ public class Allergies : GeneratorExercise protected override void UpdateTestData(TestData data) { if (data.Property == "allergicTo") - data.TestedMethod = "IsAllergicTo"; + data.TestedMethod = $"Is{data.TestedMethod}"; else if (data.Property == "list") data.UseVariableForExpected = true; @@ -20,19 +20,17 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private string RenderAssert(TestMethod method) - { - return method.Data.Property == "allergicTo" + private string RenderAssert(TestMethod method) + => method.Data.Property == "allergicTo" ? RenderIsAllergicToAssert(method) : method.Assert; - } private string RenderIsAllergicToAssert(TestMethod method) { var assert = new StringBuilder(); foreach (var allergy in method.Data.Expected) - assert.AppendLine(Render.AssertBoolean(allergy["result"], $"sut.IsAllergicTo({Render.Object(allergy["substance"])})")); + assert.AppendLine(Render.AssertBoolean(allergy["result"], $"sut.{method.Data.TestedMethod}({Render.Object(allergy["substance"])})")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/Alphametics.cs b/generators/Exercises/Generators/Alphametics.cs index ed6918ee7f..ec0300b2e7 100644 --- a/generators/Exercises/Generators/Alphametics.cs +++ b/generators/Exercises/Generators/Alphametics.cs @@ -21,7 +21,7 @@ protected override void UpdateTestData(TestData data) private static dynamic ConvertExpected(TestData canonicalDataCase) { Dictionary expected = canonicalDataCase.Expected; - return expected.ToDictionary(kv => kv.Key[0], kv => int.Parse(kv.Value.ToString())); + return expected.ToDictionary(kv => kv.Key[0], kv => Convert.ToInt32(kv.Value)); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/BinarySearch.cs b/generators/Exercises/Generators/BinarySearch.cs index ca40582920..0149a28f3d 100644 --- a/generators/Exercises/Generators/BinarySearch.cs +++ b/generators/Exercises/Generators/BinarySearch.cs @@ -12,8 +12,8 @@ protected override void UpdateTestData(TestData data) if (data.Input["array"] is JArray) data.Input["array"] = Array.Empty(); - data.UseVariablesForConstructorParameters = true; data.SetConstructorInputParameters("array"); + data.UseVariablesForConstructorParameters = true; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 9d7670d78a..0bb72f17b0 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -34,18 +34,12 @@ protected override void UpdateTestMethod(TestMethod method) private string RenderAssert(TestMethod method) { var assert = new StringBuilder(); - var canonicalDataCase = method.Data; - var input = canonicalDataCase.Input as Dictionary; - var constructorData = input["treeData"] as string[]; - if (constructorData.Length == 1) assert.AppendLine(Render.Variable("tree", $"new BinarySearchTree({constructorData[0]})")); - else - { - var constructorDataString = string.Join(", ", constructorData); - assert.AppendLine(Render.Variable("tree", $"new BinarySearchTree(new[] {{ {constructorDataString} }})")); - } + var treeData = ConvertToIntegers(method.Data.Input["treeData"]); + var constructorParameters = Render.Object(treeData.Length == 1 ? treeData[0] : treeData); + assert.AppendLine(Render.Variable("tree", $"new BinarySearchTree({constructorParameters})")); - if (canonicalDataCase.Expected is Dictionary expected) + if (method.Data.Expected is Dictionary expected) { var tree = new ExpectedDataBinaryTree(expected); foreach (var testAssert in TestAsserts(tree)) @@ -53,14 +47,15 @@ private string RenderAssert(TestMethod method) } else { - var expectedNumbers = ((string[]) canonicalDataCase.Expected).Select(int.Parse).ToArray(); - var expectedRendered = Render.Object(expectedNumbers); - assert.AppendLine(Render.AssertEqual(expectedRendered, "tree.AsEnumerable()")); + var renderedExpected = Render.Object(ConvertToIntegers(method.Data.Expected)); + assert.AppendLine(Render.AssertEqual(renderedExpected, "tree.AsEnumerable()")); } return assert.ToString(); } + private static int[] ConvertToIntegers(dynamic data) => ((string[]) data).Select(int.Parse).ToArray(); + private IEnumerable TestAsserts(ExpectedDataBinaryTree tree, string traverse = "") { yield return Render.AssertEqual(tree.Value, $"tree{traverse}.Value"); diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index ffdaf009e1..5a2e870669 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -11,14 +11,10 @@ public class Bowling : GeneratorExercise protected override void UpdateTestData(TestData data) { - if (!(data.Expected is int)) - { - data.ExceptionThrown = typeof(ArgumentException); - } - else - { + if (data.Expected is int) data.UseVariableForTested = true; - } + else + data.ExceptionThrown = typeof(ArgumentException); data.SetInputParameters(); } @@ -52,8 +48,7 @@ private string RenderAssert(TestMethod method) return Render.AssertThrows(method.Data.ExceptionThrown, $"sut.Roll({actual})"); } - if (method.Data.ExceptionThrown == null || - method.Data.Property != "score") + if (method.Data.ExceptionThrown == null || method.Data.Property != "score") return method.Assert; return Render.AssertThrows(method.Data.ExceptionThrown, "sut.Score()"); diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index e8c0de408a..1d13e445f8 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -24,10 +24,7 @@ private string RenderAssert(TestMethod method) } private string RenderSut(TestData canonicalDataCase) - { - var capacity = canonicalDataCase.Input["capacity"]; - return Render.Variable("buffer", $"new CircularBuffer(capacity: {capacity})"); - } + => Render.Variable("buffer", $"new CircularBuffer(capacity: {canonicalDataCase.Input["capacity"]})"); private string RenderOperation(dynamic operation) { @@ -46,19 +43,15 @@ private string RenderOperation(dynamic operation) } } - private string RenderReadOperation(dynamic operation) - { - return operation["should_succeed"] + private string RenderReadOperation(dynamic operation) + => operation["should_succeed"] ? Render.AssertEqual(operation["expected"].ToString(), "buffer.Read()") : Render.AssertThrows("buffer.Read()"); - } - private string RenderWriteOperation(dynamic operation) - { - return operation["should_succeed"] + private string RenderWriteOperation(dynamic operation) + => operation["should_succeed"] ? $"buffer.Write({operation["item"]});" : Render.AssertThrows($"buffer.Write({operation["item"]})"); - } private static string RenderOverwriteOperation(dynamic operation) => $"buffer.Overwrite({operation["item"]});"; diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 2edcbfa1fa..890ffd1f80 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -49,9 +49,9 @@ private string RenderAssert(TestMethod method) return RenderEqualToAssert(method); } - return method.Data.Property != PropertyCreate - ? RenderConsistencyToAssert(method) - : method.Assert; + return method.Data.Property == PropertyCreate + ? method.Assert + : RenderConsistencyToAssert(method); } private string RenderConsistencyToAssert(TestMethod method) diff --git a/generators/Exercises/Generators/CollatzConjecture.cs b/generators/Exercises/Generators/CollatzConjecture.cs index 14bf6ee4ae..7d5dcc8cb7 100644 --- a/generators/Exercises/Generators/CollatzConjecture.cs +++ b/generators/Exercises/Generators/CollatzConjecture.cs @@ -7,7 +7,8 @@ public class CollatzConjecture : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.ExceptionThrown = data.Input["number"] <= 0 ? typeof(ArgumentException) : null; + if (data.Input["number"] <= 0) + data.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index d0b9ec633b..df615c8c23 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -17,8 +17,8 @@ protected override void UpdateTestData(TestData data) data.Expected = ConvertToType(data.Expected); var constructorParamName = data.Input.ContainsKey("z") ? "z" : "z1"; - data.Input["real"] = ConvertMathDouble(data.Input[constructorParamName][0]); - data.Input["imaginary"] = ConvertMathDouble(data.Input[constructorParamName][1]); + data.Input["real"] = ConvertToDouble(data.Input[constructorParamName][0]); + data.Input["imaginary"] = ConvertToDouble(data.Input[constructorParamName][1]); data.SetInputParameters(GetInputParameters(data, constructorParamName)); data.SetConstructorInputParameters("real", "imaginary"); @@ -37,12 +37,10 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private string RenderAssert(TestMethod method) - { - return method.Data.UseVariableForExpected + private string RenderAssert(TestMethod method) + => method.Data.UseVariableForExpected ? RenderComplexNumberAssert(method) : method.Assert; - } private string RenderComplexNumberAssert(TestMethod method) { @@ -60,12 +58,12 @@ protected override void UpdateNamespaces(ISet namespaces) private object ConvertToType(dynamic rawValue) => IsComplexNumber(rawValue) - ? new UnescapedValue($"new ComplexNumber({Render.Object(ConvertMathDouble(rawValue[0]))}, {Render.Object(ConvertMathDouble(rawValue[1]))})") + ? new UnescapedValue($"new ComplexNumber({Render.Object(ConvertToDouble(rawValue[0]))}, {Render.Object(ConvertToDouble(rawValue[1]))})") : rawValue; private static bool IsComplexNumber(object rawValue) => rawValue is int[] || rawValue is double[] || rawValue is float[] || rawValue is JArray; - private static object ConvertMathDouble(dynamic value) + private static object ConvertToDouble(dynamic value) { switch (value.ToString()) { diff --git a/generators/Exercises/Generators/CustomSet.cs b/generators/Exercises/Generators/CustomSet.cs index 966937419b..58079ad437 100644 --- a/generators/Exercises/Generators/CustomSet.cs +++ b/generators/Exercises/Generators/CustomSet.cs @@ -1,5 +1,6 @@ using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; +using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { @@ -11,7 +12,7 @@ protected override void UpdateTestData(TestData data) if (data.Input.ContainsKey("set")) { - if (!(data.Input["set"] is int[])) + if (data.Input["set"] is JArray) { data.Input["set"] = new UnescapedValue(""); } @@ -20,7 +21,7 @@ protected override void UpdateTestData(TestData data) } else { - if (!(data.Input["set1"] is int[])) + if (data.Input["set1"] is JArray) { data.Input["set1"] = new UnescapedValue(""); } diff --git a/generators/Exercises/Generators/DifferenceOfSquares.cs b/generators/Exercises/Generators/DifferenceOfSquares.cs index a3d43b36c8..1434168b7c 100644 --- a/generators/Exercises/Generators/DifferenceOfSquares.cs +++ b/generators/Exercises/Generators/DifferenceOfSquares.cs @@ -6,18 +6,7 @@ public class DifferenceOfSquares : GeneratorExercise { protected override void UpdateTestData(TestData data) { - switch (data.Property) - { - case "squareOfSum": - data.TestedMethod = "CalculateSquareOfSum"; - break; - case "sumOfSquares": - data.TestedMethod = "CalculateSumOfSquares"; - break; - case "differenceOfSquares": - data.TestedMethod = "CalculateDifferenceOfSquares"; - break; - } + data.TestedMethod = $"Calculate{data.TestedMethod}"; } } } diff --git a/generators/Exercises/Generators/Dominoes.cs b/generators/Exercises/Generators/Dominoes.cs index e55d96e483..d983be42aa 100644 --- a/generators/Exercises/Generators/Dominoes.cs +++ b/generators/Exercises/Generators/Dominoes.cs @@ -14,12 +14,12 @@ protected override void UpdateTestData(TestData data) data.Input["dominoes"] = ConvertDominoes(data.Input["dominoes"]); } + private static ValueTuple[] ConvertDominoes(JToken input) + => input.ToObject().Select(x => (x[0], x[1])).ToArray(); + protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(ValueTuple).Namespace); } - - private static ValueTuple[] ConvertDominoes(dynamic input) - => ((JToken)input).ToObject().Select(x => (x[0], x[1])).ToArray(); } } diff --git a/generators/Exercises/Generators/Etl.cs b/generators/Exercises/Generators/Etl.cs index caab37b717..2456fab05c 100644 --- a/generators/Exercises/Generators/Etl.cs +++ b/generators/Exercises/Generators/Etl.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; @@ -16,12 +17,12 @@ protected override void UpdateTestData(TestData data) } private static dynamic ConvertExpected(dynamic expected) - => ((Dictionary)expected).ToDictionary(kv => kv.Key, kv => int.Parse($"{kv.Value}")); + => ((Dictionary)expected).ToDictionary(kv => kv.Key, kv => Convert.ToInt32(kv.Value)); private static IDictionary ConvertInput(IDictionary input) => new Dictionary { - ["input"] = input.ToDictionary(kv => int.Parse(kv.Key), kv => (string[])kv.Value) + ["input"] = input.ToDictionary(kv => Convert.ToInt32(kv.Key), kv => (string[])kv.Value) }; protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/FlattenArray.cs b/generators/Exercises/Generators/FlattenArray.cs index ed8df0fab8..f67a75f556 100644 --- a/generators/Exercises/Generators/FlattenArray.cs +++ b/generators/Exercises/Generators/FlattenArray.cs @@ -16,10 +16,10 @@ protected override void UpdateTestData(TestData data) if (stringInput.Contains("System.Int32")) return; - data.Input["array"] = new UnescapedValue(ToProperObjArray(stringInput)); + data.Input["array"] = new UnescapedValue(ConvertToObjectArray(stringInput)); } - private static string ToProperObjArray(string input) + private static string ConvertToObjectArray(string input) => input .Replace("System.Int32", "") .Replace("]", "}") diff --git a/generators/Exercises/Generators/Gigasecond.cs b/generators/Exercises/Generators/Gigasecond.cs index abe6319d39..fb91af342d 100644 --- a/generators/Exercises/Generators/Gigasecond.cs +++ b/generators/Exercises/Generators/Gigasecond.cs @@ -14,16 +14,16 @@ protected override void UpdateTestData(TestData data) data.Expected = new UnescapedValue(RenderDateTime((DateTime)data.Expected)); } - protected override void UpdateNamespaces(ISet namespaces) - { - namespaces.Add(typeof(DateTime).Namespace); - } - private static string RenderDateTime(DateTime dateTime) { return dateTime.Hour == 0 && dateTime.Minute == 0 && dateTime.Second == 0 ? $"new DateTime({dateTime.Year}, {dateTime.Month}, {dateTime.Day})" : $"new DateTime({dateTime.Year}, {dateTime.Month}, {dateTime.Day}, {dateTime.Hour}, {dateTime.Minute}, {dateTime.Second})"; } + + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(DateTime).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index f0e07d5dbe..4c5714a7e7 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -83,7 +83,7 @@ private string RenderAssert(TestMethod method) private UnescapedValue RenderOwner(dynamic owner) => Render.Enum("Owner", owner); private string RenderTerritory(dynamic territory) - => Render.Object((territory as JArray).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); + => Render.Object(((JArray)territory).Select(coordinate => (coordinate[0].ToObject(), coordinate[1].ToObject())).ToArray()); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/Grains.cs b/generators/Exercises/Generators/Grains.cs index 88dff4cb07..758ba2f3ce 100644 --- a/generators/Exercises/Generators/Grains.cs +++ b/generators/Exercises/Generators/Grains.cs @@ -7,12 +7,10 @@ public class Grains : GeneratorExercise { protected override void UpdateTestData(TestData data) { - if (ShouldThrowException(data.Expected)) + if (data.Expected is int i && i == -1) data.ExceptionThrown = typeof(ArgumentOutOfRangeException); else data.Expected = (ulong)data.Expected; } - - private static bool ShouldThrowException(dynamic value) => value is int i && i == -1; } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Grep.cs b/generators/Exercises/Generators/Grep.cs index 819be02f29..641852f107 100644 --- a/generators/Exercises/Generators/Grep.cs +++ b/generators/Exercises/Generators/Grep.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; @@ -18,17 +19,8 @@ protected override void UpdateTestData(TestData data) data.UseVariableForExpected = true; } - private static dynamic ConvertExpected(dynamic expected) - { - if (expected is object[] arr && arr.Length != 0) - return new UnescapedValue( - Environment.NewLine + - string.Join( - Environment.NewLine, - arr.Select((x, i) => $" \"{x}\\n\"{(i < arr.Length - 1 ? " +" : "")}"))); - - return ""; - } + private static MultiLineString ConvertExpected(dynamic expected) + => new MultiLineString(expected as string[] ?? Array.Empty()); protected override void UpdateTestClass(TestClass @class) { diff --git a/generators/Exercises/Generators/Hamming.cs b/generators/Exercises/Generators/Hamming.cs index c6adb5efda..4d896e31a8 100644 --- a/generators/Exercises/Generators/Hamming.cs +++ b/generators/Exercises/Generators/Hamming.cs @@ -7,7 +7,8 @@ public class Hamming : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.ExceptionThrown = data.Expected is int ? null : typeof(ArgumentException); + if (!(data.Expected is int)) + data.ExceptionThrown = typeof(ArgumentException); } } } diff --git a/generators/Exercises/Generators/KindergartenGarden.cs b/generators/Exercises/Generators/KindergartenGarden.cs index e93b7c094c..d48c59b7fe 100644 --- a/generators/Exercises/Generators/KindergartenGarden.cs +++ b/generators/Exercises/Generators/KindergartenGarden.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -16,10 +17,12 @@ protected override void UpdateTestData(TestData data) else data.SetConstructorInputParameters("diagram"); - var plants = (IEnumerable)data.Expected; - data.Expected = plants + data.Expected = ConvertExpected(data.Expected); + } + + private UnescapedValue[] ConvertExpected(IEnumerable plants) + => plants .Select(plant => Render.Enum("Plant", plant)) .ToArray(); - } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/LargestSeriesProduct.cs b/generators/Exercises/Generators/LargestSeriesProduct.cs index 9d906181ba..ee46158d5f 100644 --- a/generators/Exercises/Generators/LargestSeriesProduct.cs +++ b/generators/Exercises/Generators/LargestSeriesProduct.cs @@ -9,8 +9,8 @@ protected override void UpdateTestData(TestData data) { data.TestedMethod = "GetLargestProduct"; - var caseInputLessThanZero = (long)data.Expected == -1; - data.ExceptionThrown = caseInputLessThanZero ? typeof(ArgumentException) : null; + if (data.Expected == -1) + data.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ListOps.cs b/generators/Exercises/Generators/ListOps.cs index cced7d955b..81bf088384 100644 --- a/generators/Exercises/Generators/ListOps.cs +++ b/generators/Exercises/Generators/ListOps.cs @@ -26,16 +26,14 @@ protected override void UpdateTestData(TestData data) data.Input["list2"] = ConvertToList(list2); if (data.Input.TryGetValue("lists", out var lists)) - data.Input["lists"] = ConvertToNestedList(lists, true); + data.Input["lists"] = ConvertToList(lists); if (data.Input.TryGetValue("function", out var function)) data.Input["function"] = ConvertToFunction(data.Property, function); if (data.Expected is IEnumerable) { - data.Expected = data.Input.ContainsKey("lists") - ? ConvertToNestedList(data.Expected, false) - : ConvertToList(data.Expected); + data.Expected = ConvertToList(data.Expected); } } @@ -55,54 +53,33 @@ private static UnescapedValue ConvertToFunction(string property, dynamic functio private static dynamic ConvertToList(dynamic value) { - switch (value) - { - case JArray jArray when jArray.Count == 0: - return new List(); - case JArray jArray when jArray.Any(jToken => jToken.Type == JTokenType.Array): - return jArray.Select(ConvertToList).ToList(); - case JArray jArray: - return jArray.ToObject().ToList(); - case IEnumerable ints: - return ints.ToList(); - } - - return value; + if (IsArrayOfIntegers(value)) + return new List(value); + + if (IsListOfIntegers(value)) + return value.ToObject>(); + + if (IsListOfListOfIntegers(value)) + return value.ToObject>>(); + + if (IsListOfListOfListOfIntegers(value)) + return value.ToObject>>>(); + + throw new ArgumentException("Unsupported list type"); } + + private static bool IsArrayOfIntegers(dynamic value) + => value is int []; + + private static bool IsListOfIntegers(dynamic value) + => value is JArray jArray && jArray.All(child => child.Type == JTokenType.Integer); - private dynamic ConvertToNestedList(dynamic value, bool unescapeEmpty) - { - switch (value) - { - case JArray jArray when jArray.Count == 0: - if (unescapeEmpty) - { - return new UnescapedValue("new List>()"); - } - - return new List(); - case JArray jArray: - var nestedList = jArray - .Children() - .Select(ConvertToList) - .Select(Render.Object) - .Select(renderedValue => new UnescapedValue(renderedValue)) - .ToList(); + private static bool IsListOfListOfIntegers(dynamic value) + => value is JArray jArray && jArray.All(IsListOfIntegers); - return new UnescapedValue(Render.Object(nestedList) - .Replace("", "") - .Replace("new List { new List", "new List> { new List") - .Replace("new[] { new List>", "new List>> { new List>") - .Replace("new[] { new List", "new List> { new List") - .Replace("new List { new List>", "new List>> { new List>") - .Replace("new List { new List", "new List> { new List")); - case IEnumerable ints: - return new UnescapedValue(Render.Object(ints.ToList())); - } + private static bool IsListOfListOfListOfIntegers(dynamic value) + => value is JArray jArray && jArray.All(IsListOfListOfIntegers); - return value; - } - protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(Func).Namespace); diff --git a/generators/Exercises/Generators/NthPrime.cs b/generators/Exercises/Generators/NthPrime.cs index 1a7f678c2c..6295abd340 100644 --- a/generators/Exercises/Generators/NthPrime.cs +++ b/generators/Exercises/Generators/NthPrime.cs @@ -8,7 +8,8 @@ public class NthPrime : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.ExceptionThrown = data.Expected is Dictionary ? typeof(ArgumentOutOfRangeException) : null; + if (data.Expected is Dictionary) + data.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index 63a72d2cf7..1497cc6072 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -9,7 +9,7 @@ public class NucleotideCount : GeneratorExercise { protected override void UpdateTestData(TestData data) { - if (((Dictionary)data.Expected).ContainsKey("error")) + if (data.Expected.ContainsKey("error")) return; data.UseVariableForExpected = true; @@ -18,7 +18,7 @@ protected override void UpdateTestData(TestData data) } private static dynamic ConvertExpected(dynamic expected) - => ((Dictionary)expected).ToDictionary(kv => kv.Key[0], kv => int.Parse($"{kv.Value}")); + => ((Dictionary)expected).ToDictionary(kv => kv.Key[0], kv => Convert.ToInt32(kv.Value)); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/OcrNumbers.cs b/generators/Exercises/Generators/OcrNumbers.cs index 1fae30e64e..1aeee6603e 100644 --- a/generators/Exercises/Generators/OcrNumbers.cs +++ b/generators/Exercises/Generators/OcrNumbers.cs @@ -9,7 +9,9 @@ public class OcrNumbers : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.ExceptionThrown = data.Expected is int i && i <= 0 ? typeof(ArgumentException) : null; + if (data.Expected is int i && i <= 0) + data.ExceptionThrown = typeof(ArgumentException); + data.Input["rows"] = new MultiLineString(data.Input["rows"]); data.Expected = data.Expected.ToString(); data.UseVariableForTested = true; diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index bc7b2a1d9f..60d617d530 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -40,8 +40,8 @@ private string RenderAssert(TestMethod method) return assert.ToString(); } - private string RenderCoordinates(dynamic coordinates) - => Render.Object((coordinates as JArray) + private string RenderCoordinates(JArray coordinates) + => Render.Object(coordinates .Select(RenderCoordinate) .ToArray()); diff --git a/generators/Exercises/Generators/PhoneNumber.cs b/generators/Exercises/Generators/PhoneNumber.cs index 9542f8468d..de1cc4d747 100644 --- a/generators/Exercises/Generators/PhoneNumber.cs +++ b/generators/Exercises/Generators/PhoneNumber.cs @@ -8,7 +8,9 @@ public class PhoneNumber : GeneratorExercise protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; - data.ExceptionThrown = data.Expected is null ? typeof(ArgumentException) : null; + + if (data.Expected is null) + data.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Pov.cs b/generators/Exercises/Generators/Pov.cs index 61b187dff0..d2b8533789 100644 --- a/generators/Exercises/Generators/Pov.cs +++ b/generators/Exercises/Generators/Pov.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; @@ -12,8 +11,10 @@ protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; data.UseVariableForExpected = true; - data.ExceptionThrown = data.Expected is null ? typeof(ArgumentException) : null; - + + if (data.Expected is null) + data.ExceptionThrown = typeof(ArgumentException); + data.Input["tree"] = RenderTree(data.Input["tree"]); if (data.Property == "fromPov") @@ -29,21 +30,15 @@ private UnescapedValue RenderTree(dynamic tree) return null; } - var sb = new StringBuilder(); - var label = Render.Object(tree["label"]); if (tree.ContainsKey("children")) { var children = string.Join(", ", ((object[])tree["children"]).Select(RenderTree)); - sb.Append($"new Tree({label}, {children})"); + return new UnescapedValue($"new Tree({label}, {children})"); } - else - { - sb.Append($"new Tree({label})"); - } - - return new UnescapedValue(sb.ToString()); + + return new UnescapedValue($"new Tree({label})"); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index ec54d057b3..c5e9a0a253 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -9,8 +9,19 @@ public class QueenAttack : GeneratorExercise { protected override void UpdateTestData(TestData data) { - if (data.Property == "create") - SetCreatePropertyData(data); + if (data.Property != "create") + return; + + if (data.Expected < 0) + data.ExceptionThrown = typeof(ArgumentOutOfRangeException); + + data.UseVariableForTested = true; + + var coordinates = GetCoordinatesFromPosition(data.Input["queen"]); + data.Input["X"] = coordinates.Item1; + data.Input["Y"] = coordinates.Item2; + + data.SetInputParameters("X", "Y"); } protected override void UpdateTestMethod(TestMethod method) @@ -31,7 +42,7 @@ private string RenderAssert(TestMethod method) private string RenderCanAttackAssert(TestMethod method) { var assert = new StringBuilder(); - + var (whiteQueenX, whiteQueenY) = GetCoordinatesFromPosition((IDictionary)method.Data.Input["white_queen"]); var (blackQueenX, blackQueenY) = GetCoordinatesFromPosition((IDictionary)method.Data.Input["black_queen"]); @@ -50,20 +61,5 @@ private static ValueTuple GetCoordinatesFromPosition(IDictionary= 0; - - canonicalDataCase.UseVariableForTested = validExpected; - canonicalDataCase.ExceptionThrown = validExpected ? null : typeof(ArgumentOutOfRangeException); - canonicalDataCase.Description = validExpected ? canonicalDataCase.Description + " does not throw exception" : canonicalDataCase.Description; - - var coordinates = GetCoordinatesFromPosition(canonicalDataCase.Input["queen"]); - canonicalDataCase.Input["X"] = coordinates.Item1; - canonicalDataCase.Input["Y"] = coordinates.Item2; - - canonicalDataCase.SetInputParameters("X", "Y"); - } } } diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index 59f6693a6d..9a399014a6 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -1,20 +1,9 @@ -using System.Collections.Generic; +using System; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { - public struct RationalNumber - { - public RationalNumber(IReadOnlyList n) - { - Numerator = n[0]; - Denominator = n[1]; - } - - public int Numerator { get; } - public int Denominator { get; } - } - public class RationalNumbers : GeneratorExercise { protected override void UpdateTestMethod(TestMethod method) @@ -24,55 +13,29 @@ protected override void UpdateTestMethod(TestMethod method) private string RenderAssert(TestMethod method) { - var input = (Dictionary)method.Data.Input; - var operationName = char.ToUpper(method.Data.Property[0]) + method.Data.Property.Substring(1); - var assertCodeLine = ""; - const string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; - var operationCode = operationsWithOverloading.Substring(operationsWithOverloading.IndexOf(method.Data.Property.ToLower()) + 4, 1); - - switch (method.Data.Property.ToLower()) + switch (method.Data.Property) { case "add": case "sub": case "mul": case "div": - { - var r1 = new RationalNumber((int[])input["r1"]); - var r2 = new RationalNumber((int[])input["r2"]); - var e = new RationalNumber((int[])method.Data.Expected); - assertCodeLine = "Assert.Equal(" + $"new RationalNumber ({e.Numerator}, {e.Denominator}), new RationalNumber({r1.Numerator}, {r1.Denominator}) {operationCode} (new RationalNumber({r2.Numerator}, {r2.Denominator})));"; - } - break; + const string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; + var operationCode = operationsWithOverloading.Substring(operationsWithOverloading.IndexOf(method.Data.Property, StringComparison.OrdinalIgnoreCase) + 4, 1); + return Render.AssertEqual(RenderRationalNumber(method.Data.Expected), $"{RenderRationalNumber(method.Data.Input["r1"])} {operationCode} ({RenderRationalNumber(method.Data.Input["r2"])})"); case "abs": case "reduce": - { - var r = new RationalNumber((int[])input["r"]); - var e = new RationalNumber((int[])method.Data.Expected); - assertCodeLine = "Assert.Equal(" + $"new RationalNumber ({e.Numerator}, {e.Denominator}), new RationalNumber({r.Numerator}, {r.Denominator}).{operationName}());"; - } - break; + return Render.AssertEqual(RenderRationalNumber(method.Data.Expected), $"{RenderRationalNumber(method.Data.Input["r"])}.{method.Data.TestedMethod}()"); case "exprational": - { - var r = new RationalNumber((int[])input["r"]); - var n = input["n"]; - var e = new RationalNumber((int[])method.Data.Expected); - assertCodeLine = "Assert.Equal(" + $"new RationalNumber ({e.Numerator}, {e.Denominator}), new RationalNumber({r.Numerator}, {r.Denominator}).{operationName}({n}));"; - } - break; + return Render.AssertEqual(RenderRationalNumber(method.Data.Expected), $"{RenderRationalNumber(method.Data.Input["r"])}.{method.Data.TestedMethod}({method.Data.Input["n"]})"); case "expreal": - { - var x = input["x"].ToString(); - var r = new RationalNumber((int[])input["r"]); - var e = Render.Object(method.Data.Expected); - var p = Precision(e); - assertCodeLine = "Assert.Equal(" + $"{e}, {x}.{operationName}(new RationalNumber({r.Numerator}, {r.Denominator})), {p});"; - } - break; + return Render.AssertEqual(method.ExpectedParameter, $"{method.Data.Input["x"]}.{method.Data.TestedMethod}({RenderRationalNumber(method.Data.Input["r"])}), {Precision(method.Data.Expected)}"); + default: + throw new ArgumentOutOfRangeException(); } - - return assertCodeLine; } + private static string RenderRationalNumber(dynamic input) => $"new RationalNumber({input[0]}, {input[1]})"; + private static int Precision(object rawValue) => rawValue.ToString().Split(new[] { '.' }).Length <= 1 ? 0 diff --git a/generators/Exercises/Generators/React.cs b/generators/Exercises/Generators/React.cs index dbdfdc8d1b..0041680882 100644 --- a/generators/Exercises/Generators/React.cs +++ b/generators/Exercises/Generators/React.cs @@ -5,7 +5,6 @@ using System.Text.RegularExpressions; using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -31,16 +30,7 @@ private string RenderArrange(TestMethod method) return arrange.ToString(); } - private string RenderCells(dynamic cells) - { - if (cells.Length == 0) - { - return ""; - } - - var renderedCells = ((object[])cells).Select(RenderCell); - return string.Join(Environment.NewLine, renderedCells); - } + private string RenderCells(object[] cells) => string.Join(Environment.NewLine, cells.Select(RenderCell)); private string RenderCell(dynamic cell) { @@ -69,16 +59,8 @@ private static string RenderComputeFunction(dynamic computeFunction) : (string)computeFunction; } - private string RenderOperations(dynamic operations) - { - if (operations.Length == 0) - { - return ""; - } - - var renderedOperations = ((object[])operations).Select(RenderOperation); - return string.Join(Environment.NewLine, renderedOperations); - } + private string RenderOperations(object[] operations) + => string.Join(Environment.NewLine, operations.Select(RenderOperation)); private string RenderOperation(dynamic operation) { @@ -116,7 +98,7 @@ private string RenderOperation(dynamic operation) return $"Assert.Equal({operation["value"]}, {ToVariableName(operation["cell"])}.Value);"; case "add_callback": var addCallbackName = ToVariableName(operation["name"]); - return Render.Variable(addCallbackName, $"A.Fake>()") + Environment.NewLine + + return Render.Variable(addCallbackName, "A.Fake>()") + Environment.NewLine + $"{ToVariableName(operation["cell"])}.Changed += {addCallbackName};"; case "remove_callback": var removeCallbackName = ToVariableName(operation["name"]); diff --git a/generators/Exercises/Generators/Rectangles.cs b/generators/Exercises/Generators/Rectangles.cs index 951c171514..e935e5d878 100644 --- a/generators/Exercises/Generators/Rectangles.cs +++ b/generators/Exercises/Generators/Rectangles.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Exercism.CSharp.Output; +using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { @@ -8,9 +9,11 @@ public class Rectangles : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.TestedMethod = "Count"; - data.Input["strings"] = data.Input["strings"] as string[] ?? Array.Empty(); data.UseVariablesForInput = true; + data.TestedMethod = "Count"; + + if (data.Input["strings"] is JArray) + data.Input["strings"] = Array.Empty(); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/RnaTranscription.cs b/generators/Exercises/Generators/RnaTranscription.cs index eb1a44c367..f150293ede 100644 --- a/generators/Exercises/Generators/RnaTranscription.cs +++ b/generators/Exercises/Generators/RnaTranscription.cs @@ -7,7 +7,8 @@ public class RnaTranscription : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.ExceptionThrown = data.Expected is null ? typeof(ArgumentException) : null; + if (data.Expected is null) + data.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs index b498e68ec0..0575bb1fe4 100644 --- a/generators/Exercises/Generators/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; @@ -10,17 +9,10 @@ public class RobotSimulator : GeneratorExercise { protected override void UpdateTestData(TestData data) { - const string direction = "direction"; - const string position = "position"; - const string coordinate = "coordinate"; + data.Input["direction"] = RenderDirection(data.Input["direction"]); + data.Input["coordinate"] = RenderCreateCoordinate(data.Input["position"]); - var positionVal = new UnescapedValue(GetCoordinateInstance(data.Input[position])); - var directionVal = new UnescapedValue(GetDirectionEnum(data.Input[direction])); - - data.Input[direction] = directionVal; - data.Input[coordinate] = positionVal; - - data.SetConstructorInputParameters(direction, coordinate); + data.SetConstructorInputParameters("direction", "coordinate"); data.UseFullDescriptionPath = true; } @@ -51,7 +43,7 @@ private string RenderInstructionsAct(TestMethod method) private string RenderAssert(TestMethod method) { - var expected = method.Data.Expected as Dictionary; + var expected = (Dictionary)method.Data.Expected; expected.TryGetValue("position", out var position); expected.TryGetValue("direction", out var direction); @@ -59,35 +51,26 @@ private string RenderAssert(TestMethod method) if (direction != null) { - var expectedDirection = GetDirectionEnum(direction); - assert.AppendLine(Render.AssertEqual(expectedDirection, "sut.Direction")); - } + var expectedDirection = RenderDirection(direction); + assert.AppendLine(Render.AssertEqual(Render.Object(expectedDirection), "sut.Direction")); + } - if (position != null) - { - var x = Render.Object(position["x"]); - var y = Render.Object(position["y"]); + if (position == null) + return assert.ToString(); + + var x = Render.Object(position["x"]); + var y = Render.Object(position["y"]); - assert.AppendLine(Render.AssertEqual(x, "sut.Coordinate.X")); - assert.AppendLine(Render.AssertEqual(y, "sut.Coordinate.Y")); - } - + assert.AppendLine(Render.AssertEqual(x, "sut.Coordinate.X")); + assert.AppendLine(Render.AssertEqual(y, "sut.Coordinate.Y")); + return assert.ToString(); } - private static string GetDirectionEnum(string direction) - { - switch (direction) - { - case "north": return "Direction.North"; - case "east": return "Direction.East"; - case "south": return "Direction.South"; - case "west": return "Direction.West"; - - default: throw new ArgumentException("Unrecognized 'Direction' enum value"); - } - } + private UnescapedValue RenderDirection(string direction) + => Render.Enum("Direction", direction); - private static string GetCoordinateInstance(dynamic coordinates) => $"new Coordinate({coordinates["x"]}, {coordinates["y"]})"; + private static UnescapedValue RenderCreateCoordinate(dynamic coordinates) + => new UnescapedValue($"new Coordinate({coordinates["x"]}, {coordinates["y"]})"); } } diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index cc723571b4..bbe8ead094 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -6,7 +6,7 @@ public class RunLengthEncoding : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Description = $"{data.Property} {data.Description}"; + data.UseFullDescriptionPath = true; } protected override void UpdateTestMethod(TestMethod method) @@ -14,12 +14,10 @@ protected override void UpdateTestMethod(TestMethod method) method.Assert = RenderAssert(method); } - private string RenderAssert(TestMethod method) - { - return method.Data.Property == "consistency" + private string RenderAssert(TestMethod method) + => method.Data.Property == "consistency" ? RenderConsistencyToAssert(method) : method.Assert; - } private string RenderConsistencyToAssert(TestMethod method) { diff --git a/generators/Exercises/Generators/SaddlePoints.cs b/generators/Exercises/Generators/SaddlePoints.cs index f7eab38c68..69f7e01c9e 100644 --- a/generators/Exercises/Generators/SaddlePoints.cs +++ b/generators/Exercises/Generators/SaddlePoints.cs @@ -30,14 +30,7 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(string).Namespace); } - private static dynamic ToMultiDimensionalArray(dynamic array) - { - var jArray = (JArray)array; - if (jArray.Count == 1 && ((JArray)jArray[0]).Count == 0) - return new int[0, 0]; - - return jArray.ToObject(); - } + private static dynamic ToMultiDimensionalArray(JArray jArray) => jArray.ToObject(); private static ValueTuple[] ToTupleCollection(Array array) { @@ -45,7 +38,7 @@ private static ValueTuple[] ToTupleCollection(Array array) for (var x = 0; x < array.GetLength(0); x++) { - var current = array.GetValue(x) as Dictionary; + var current = (Dictionary)array.GetValue(x); tuples.Add(new ValueTuple(current["row"].ToString(), current["column"].ToString())); } diff --git a/generators/Exercises/Generators/Say.cs b/generators/Exercises/Generators/Say.cs index b5dab4cb01..2d44ceb57f 100644 --- a/generators/Exercises/Generators/Say.cs +++ b/generators/Exercises/Generators/Say.cs @@ -8,7 +8,9 @@ public class Say : GeneratorExercise protected override void UpdateTestData(TestData data) { data.TestedMethod = "InEnglish"; - data.ExceptionThrown = data.Expected is int ? typeof(ArgumentOutOfRangeException) : null; + + if (data.Expected is int) + data.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Sieve.cs b/generators/Exercises/Generators/Sieve.cs index 734d7b94ce..6acbc8bca9 100644 --- a/generators/Exercises/Generators/Sieve.cs +++ b/generators/Exercises/Generators/Sieve.cs @@ -8,7 +8,9 @@ public class Sieve : GeneratorExercise protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; - data.ExceptionThrown = data.Input["limit"] < 2 ? typeof(ArgumentOutOfRangeException) : null; + + if (data.Input["limit"] < 2) + data.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/SpiralMatrix.cs b/generators/Exercises/Generators/SpiralMatrix.cs index e38c496110..7d0aa3a5de 100644 --- a/generators/Exercises/Generators/SpiralMatrix.cs +++ b/generators/Exercises/Generators/SpiralMatrix.cs @@ -12,10 +12,6 @@ protected override void UpdateTestData(TestData data) data.Expected = ConvertExpected(data.Expected); } - private static dynamic ConvertExpected(dynamic expected) - { - var jArray = (JArray)expected; - return jArray.Count == 0 ? new int[0, 0] : jArray.ToObject(); - } + private static int[,] ConvertExpected(JArray jArray) => jArray.ToObject(); } } diff --git a/generators/Exercises/Generators/Sublist.cs b/generators/Exercises/Generators/Sublist.cs index 65cc3247ba..d4f3e10143 100644 --- a/generators/Exercises/Generators/Sublist.cs +++ b/generators/Exercises/Generators/Sublist.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; -using System.Linq; +using System; +using System.Collections.Generic; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; @@ -9,23 +9,19 @@ public class Sublist : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.Input["listOne"] = InputValues(data.Input["listOne"] as int[]); - data.Input["listTwo"] = InputValues(data.Input["listTwo"] as int[]); + data.Input["listOne"] = ConvertToList(data.Input["listOne"]); + data.Input["listTwo"] = ConvertToList(data.Input["listTwo"]); data.TestedMethod = "Classify"; data.Expected = Render.Enum("SublistType", data.Expected); } + private static List ConvertToList(dynamic value) => new List(value as int[] ?? Array.Empty()); + protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(IList).Namespace); } - - private static UnescapedValue InputValues(int[] list) - { - var template = list != null ? string.Join(", ", list.Select(x => x.ToString())) : ""; - return new UnescapedValue($"new List() {{ {template} }}".Replace(" ", " ")); - } } } diff --git a/generators/Exercises/Generators/Triangle.cs b/generators/Exercises/Generators/Triangle.cs index 0ed3d56640..53f2c3bc5f 100644 --- a/generators/Exercises/Generators/Triangle.cs +++ b/generators/Exercises/Generators/Triangle.cs @@ -1,5 +1,5 @@ +using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { @@ -7,7 +7,7 @@ public class Triangle : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.TestedMethod = $"Is{data.Property.Humanize()}"; + data.TestedMethod = $"Is{data.TestedMethod}".ToTestedMethodName(); data.Input["x"] = data.Input["sides"][0]; data.Input["y"] = data.Input["sides"][1]; diff --git a/generators/Exercises/Generators/VariableLengthQuantity.cs b/generators/Exercises/Generators/VariableLengthQuantity.cs index 0c63c62bd2..906d2ef9d8 100644 --- a/generators/Exercises/Generators/VariableLengthQuantity.cs +++ b/generators/Exercises/Generators/VariableLengthQuantity.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -13,29 +12,20 @@ protected override void UpdateTestData(TestData data) { data.UseVariableForExpected = true; data.UseVariablesForInput = true; - data.Input["integers"] = RenderUInt32Array(data.Input["integers"]); + data.Input["integers"] = ConvertToUInt32Array(data.Input["integers"]); if (data.Expected == null) data.ExceptionThrown = typeof(InvalidOperationException); else - data.Expected = RenderUInt32Array(data.Expected); + data.Expected = ConvertToUInt32Array(data.Expected); } + private static uint[] ConvertToUInt32Array(IEnumerable input) + => input.Cast().Select(number => Convert.ToUInt32(number.ToString())).ToArray(); + protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(Array).Namespace); } - - private static dynamic RenderUInt32Array(dynamic input) - { - var numbers = ToUInt32Array(input as IEnumerable); - return numbers.Select(RenderUInt32Number).ToArray(); - } - - private static UnescapedValue RenderUInt32Number(uint number) - => new UnescapedValue(string.Format("0x{0:X}u", number)); - - private static IEnumerable ToUInt32Array(IEnumerable input) - => input.Cast().Select(number => Convert.ToUInt32(number.ToString())); } } \ No newline at end of file diff --git a/generators/Exercises/Generators/WordCount.cs b/generators/Exercises/Generators/WordCount.cs index c52423ba0f..9f9c795f3f 100644 --- a/generators/Exercises/Generators/WordCount.cs +++ b/generators/Exercises/Generators/WordCount.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; @@ -14,7 +15,7 @@ protected override void UpdateTestData(TestData data) } private static dynamic ConvertExpected(dynamic expected) - => ((Dictionary)expected).ToDictionary(kv => kv.Key, kv => int.Parse(kv.Value.ToString())); + => ((Dictionary)expected).ToDictionary(kv => kv.Key, kv => Convert.ToInt32(kv.Value)); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 2c334234ab..135cadae44 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; +using DotLiquid.Tags; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; @@ -8,8 +10,6 @@ namespace Exercism.CSharp.Exercises.Generators { public class WordSearch : GeneratorExercise { - private IDictionary _expectedDictionary; - protected override void UpdateTestData(TestData data) { data.UseVariablesForInput = true; @@ -20,43 +20,39 @@ protected override void UpdateTestData(TestData data) data.SetConstructorInputParameters("grid"); data.Input["grid"] = new MultiLineString(data.Input["grid"]); - - _expectedDictionary = (IDictionary)data.Expected; - - var expected = new List - { - "new Dictionary", - "{" - }; - - expected.AddRange(_expectedDictionary.Select((kv, i) => $" [\"{kv.Key}\"] = {RenderPosition(kv.Value)}{(i < _expectedDictionary.Count - 1 ? "," : "")}")); - expected.Add("}"); - - data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); + data.Expected = ((IDictionary)data.Expected).ToDictionary(kv => kv.Key, kv => ConvertToPosition(kv.Value)); } protected override void UpdateTestMethod(TestMethod method) { - method.Assert = RenderAssert(); + method.Assert = RenderAssert(method); } - private string RenderAssert() - => string.Join(Environment.NewLine, _expectedDictionary - .Select(kv => RenderAssertForSearchWord(kv.Key, kv.Value)) - .Cast()); + private string RenderAssert(TestMethod method) + { + var assert = new StringBuilder(); + + foreach (var kv in (Dictionary) method.Data.Expected) + assert.AppendLine(RenderAssertForSearchWord(kv.Key, kv.Value)); + + return assert.ToString(); + } private string RenderAssertForSearchWord(string word, dynamic expected) - => expected == null + => expected is null ? Render.AssertNull($"expected[\"{word}\"]") : Render.AssertEqual($"expected[\"{word}\"]", $"actual[\"{word}\"]"); - private string RenderPosition(dynamic position) - => position == null - ? "null" : - Render.Object((RenderCoordinate(position["start"]), RenderCoordinate(position["end"]))); + private static ((int, int), (int, int))? ConvertToPosition(dynamic position) + { + if (position == null) + return null; + + return (ConvertToCoordinate(position["start"]), ConvertToCoordinate(position["end"])); + } - private string RenderCoordinate(dynamic coordinate) - => Render.Object((coordinate["column"], coordinate["row"])); + private static (int, int) ConvertToCoordinate(dynamic coordinate) + => (Convert.ToInt32(coordinate["column"]), Convert.ToInt32(coordinate["row"])); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/Wordy.cs b/generators/Exercises/Generators/Wordy.cs index c4af612289..b20c76ea8f 100644 --- a/generators/Exercises/Generators/Wordy.cs +++ b/generators/Exercises/Generators/Wordy.cs @@ -7,7 +7,8 @@ public class Wordy : GeneratorExercise { protected override void UpdateTestData(TestData data) { - data.ExceptionThrown = data.Expected is bool ? typeof(ArgumentException) : null; + if (data.Expected is bool) + data.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index f5827cb3c0..cb48057353 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Text; +using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; using Humanizer; @@ -18,8 +19,8 @@ private string RenderArrange(TestMethod method) { var arrange = new StringBuilder(); var tree = RenderTree(method.Data.Input["initialTree"]); - arrange.AppendLine(Render.Variable("tree", $"{tree}")); - arrange.AppendLine(Render.Variable("sut", $"Zipper.FromTree(tree)")); + arrange.AppendLine(Render.Variable("tree", tree)); + arrange.AppendLine(Render.Variable("sut", "Zipper.FromTree(tree)")); var operations = RenderOperations(method.Data.Input["operations"]); arrange.AppendLine(Render.Variable("actual", $"sut{operations}")); @@ -43,23 +44,15 @@ private string RenderAssert(TestMethod method) private static string RenderTree(dynamic tree) { if (tree == null) - { return "null"; - } - - var value = tree["value"]; - var left = tree["left"] == null ? "null" : RenderTree(tree["left"]); - var right = tree["right"] == null ? "null" : RenderTree(tree["right"]); - return $"new BinTree({value}, {left}, {right})"; + return $"new BinTree({tree["value"]}, {RenderTree(tree["left"])}, {RenderTree(tree["right"])})"; } private static string RenderOperations(dynamic operations) { if (operations.Length == 0) - { return ""; - } return "." + string.Join(".", ((object[])operations).Select(RenderOperation)); } @@ -67,26 +60,26 @@ private static string RenderOperations(dynamic operations) private static string RenderOperation(dynamic operation) { var operationType = (string)operation["operation"]; + var operationMethod = operationType.ToMethodName(); switch (operationType) { case "set_value": - return $"SetValue({operation["item"]})"; + return $"{operationMethod}({operation["item"]})"; case "set_left": - return $"SetLeft({RenderTree(operation["item"])})"; case "set_right": - return $"SetRight({RenderTree(operation["item"])})"; + return $"{operationMethod}({RenderTree(operation["item"])})"; default: - return $"{operationType.Pascalize()}()"; + return $"{operationMethod}()"; } } - private static string RenderExpected(dynamic expected) + private string RenderExpected(dynamic expected) { switch (expected["type"]) { case "int": - return expected["value"].ToString(); + return Render.Object(expected["value"]); case "zipper": if (expected.TryGetValue("value", out dynamic value) && value == null) { diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index 8e7b7590b4..678505da54 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -30,7 +30,9 @@ public static string ToTestMethodName(this string input) return !char.IsLetter(methodName[0]) ? "Test_" : methodName; } - public static string ToTestedMethodName(this string input) => input.Dehumanize(); + public static string ToTestedMethodName(this string input) => input.ToMethodName(); + + public static string ToMethodName(this string input) => input.Dehumanize(); public static string ToVariableName(this string input) => input.Camelize(); diff --git a/generators/Input/JTokenHelper.cs b/generators/Input/JTokenHelper.cs index 73a7c1c4b7..967943afd9 100644 --- a/generators/Input/JTokenHelper.cs +++ b/generators/Input/JTokenHelper.cs @@ -18,11 +18,13 @@ public static IEnumerable ParentsAndSelf(this JToken jToken) public static dynamic ConvertJToken(JToken jToken) { - if (jToken is JObject jObject) - return ConvertJObject(jObject); - - if (jToken is JArray jArray) - return ConvertJArray(jArray); + switch (jToken) + { + case JObject jObject: + return ConvertJObject(jObject); + case JArray jArray: + return ConvertJArray(jArray); + } switch (jToken.Type) { diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 8cf8425798..ac6558f697 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -14,6 +14,7 @@ public string Object(object val) case string str: return String(str); case double dbl: return Double(dbl); case int i: return Int(i); + case uint ui: return Uint(ui); case float flt: return Float(flt); case ulong ulng: return Ulong(ulng); case char c: return Char(c); diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs index 1248177741..4148442498 100644 --- a/generators/Output/Rendering/RenderArray.cs +++ b/generators/Output/Rendering/RenderArray.cs @@ -1,5 +1,4 @@ -using System; -using System.Linq; +using System.Linq; using Exercism.CSharp.Helpers; namespace Exercism.CSharp.Output.Rendering @@ -31,7 +30,7 @@ public string ArrayMultiLine(T[,] elements) private bool RenderAsSingleLine(T[] elements) => !elements.Any() || IsNotArrayOfArrays(elements) && RenderedAsSingleLineDoesNotExceedMaximumLength(elements); - private bool IsNotArrayOfArrays(T[] elements) + private static bool IsNotArrayOfArrays(T[] elements) => !elements.GetType().GetElementType().IsArray; private bool RenderedAsSingleLineDoesNotExceedMaximumLength(T[] elements) diff --git a/generators/Output/Rendering/RenderCollection.cs b/generators/Output/Rendering/RenderCollection.cs index d0786eb4fb..a014bdd4d6 100644 --- a/generators/Output/Rendering/RenderCollection.cs +++ b/generators/Output/Rendering/RenderCollection.cs @@ -18,7 +18,7 @@ public string MultiLineCollectionInitializer(IEnumerable elements) public string MultiLineCollectionInitializer(IEnumerable elements, Func render) => CollectionInitializer(elements, line => render(line).Indent(), Environment.NewLine); - private string CollectionInitializer(IEnumerable elements, Func render, string separator) + private static string CollectionInitializer(IEnumerable elements, Func render, string separator) => $"{separator}{{{separator}{string.Join($",{separator}", elements.Select(render))}{separator}}}"; } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderNumber.cs b/generators/Output/Rendering/RenderNumber.cs index ff49ed84c0..e6a17eab31 100644 --- a/generators/Output/Rendering/RenderNumber.cs +++ b/generators/Output/Rendering/RenderNumber.cs @@ -11,5 +11,7 @@ public partial class Render public string Int(int i) => i.ToString(CultureInfo.InvariantCulture); public string Ulong(ulong ulng) => $"{ulng}UL"; + + public string Uint(uint ui) => string.Format("0x{0:X}u", ui); } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderString.cs b/generators/Output/Rendering/RenderString.cs index b5c2744268..fd09196839 100644 --- a/generators/Output/Rendering/RenderString.cs +++ b/generators/Output/Rendering/RenderString.cs @@ -16,17 +16,19 @@ public UnescapedValue Enum(string enumType, string enumCase) public string StringMultiLine(MultiLineString multiLineString) { - if (multiLineString.Lines.Length == 0) - return String(string.Empty); - - if (multiLineString.Lines.Length == 1) - return String(multiLineString.Lines[0]); - - return $"{Environment.NewLine}{string.Join(Environment.NewLine, RenderLines())}"; + switch (multiLineString.Lines.Length) + { + case 0: + return String(string.Empty); + case 1: + return String(multiLineString.Lines[0]); + default: + return $"{Environment.NewLine}{string.Join(Environment.NewLine, RenderLines())}"; + } IEnumerable RenderLines() => multiLineString.Lines.Select((t, i) => i < multiLineString.Lines.Length - 1 - ? $"{String($"{t}{Environment.NewLine}").Indent()} +" + ? $"{String($"{t}\n").Indent()} +" : $"{String(t).Indent()}"); } } From 643b124b2a3ec3463c43fc80a98a8a99ecfae802 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Wed, 4 Jul 2018 20:27:02 +0200 Subject: [PATCH 76/97] generators: Fix simple-cipher generator --- exercises/simple-cipher/SimpleCipherTest.cs | 4 ++-- .../Exercises/Generators/SimpleCipher.cs | 21 +++++++++---------- 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/exercises/simple-cipher/SimpleCipherTest.cs b/exercises/simple-cipher/SimpleCipherTest.cs index 5dd3b8ac85..f37284d626 100644 --- a/exercises/simple-cipher/SimpleCipherTest.cs +++ b/exercises/simple-cipher/SimpleCipherTest.cs @@ -9,14 +9,14 @@ public class SimpleCipherTest public void Random_key_cipher_can_encode() { var sut = new SimpleCipher(); - Assert.Equal("cipher.key.substring(0, plaintext.length)", sut.Encode("aaaaaaaaaa")); + Assert.Equal(sut.Key.Substring(0, 10), sut.Encode("aaaaaaaaaa")); } [Fact(Skip = "Remove to run test")] public void Random_key_cipher_can_decode() { var sut = new SimpleCipher(); - Assert.Equal("aaaaaaaaaa", sut.Decode("cipher.key.substring(0, expected.length)")); + Assert.Equal("aaaaaaaaaa", sut.Decode(sut.Key.Substring(0, 10))); } [Fact(Skip = "Remove to run test")] diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index e9cfa1929b..31197aefb5 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -25,22 +25,21 @@ protected override void UpdateTestData(TestData data) if (data.Input.TryGetValue("ciphertext", out var cipherText)) { - switch (cipherText) + if (cipherText.StartsWith("cipher.key.substring")) { - case "cipher.key": - data.Input["ciphertext"] = new UnescapedValue("sut.Key.Substring(0, 10)"); - break; - case "cipher.encode": - var plaintext = Render.Object(data.Input["plaintext"]); - data.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); - data.SetInputParameters("ciphertext"); - break; + data.Input["ciphertext"] = new UnescapedValue($"sut.Key.Substring(0, {data.Expected.Length})"); + } + else if (cipherText == "cipher.encode") + { + var plaintext = Render.Object(data.Input["plaintext"]); + data.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); + data.SetInputParameters("ciphertext"); } } - if (data.Expected is string s && s == "cipher.key") + if (data.Expected is string s && s.StartsWith("cipher.key.substring")) { - data.Expected = new UnescapedValue("sut.Key.Substring(0, 10)"); + data.Expected = new UnescapedValue($"sut.Key.Substring(0, {data.Input["plaintext"].Length})"); } } From 4894680fe5f56b6fdafe58fa80087a348504b024 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 5 Jul 2018 19:22:23 +0200 Subject: [PATCH 77/97] generators: Correctly render null value --- generators/Exercises/Generators/TwoFer.cs | 3 +++ generators/Output/Rendering/Render.cs | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/generators/Exercises/Generators/TwoFer.cs b/generators/Exercises/Generators/TwoFer.cs index cd9dd7c807..85e9eaf807 100644 --- a/generators/Exercises/Generators/TwoFer.cs +++ b/generators/Exercises/Generators/TwoFer.cs @@ -7,6 +7,9 @@ public class TwoFer : GeneratorExercise protected override void UpdateTestData(TestData data) { data.TestedMethod = "Name"; + + if (data.Input["name"] is null) + data.SetInputParameters(); } } } \ No newline at end of file diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index ac6558f697..c29482bb7e 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -7,7 +7,7 @@ public partial class Render public string Object(object val) { if (val == null) - return null; + return "null"; switch (val) { From 7a987215b3a427c6badc1cf794a479b028db65f9 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 5 Jul 2018 19:31:51 +0200 Subject: [PATCH 78/97] generators: Return correct friendly name for Nullable and ValueTuple types --- exercises/dominoes/DominoesTest.cs | 2 +- exercises/go-counting/GoCountingTest.cs | 12 ++--- exercises/word-search/WordSearchTest.cs | 44 +++++++++---------- generators/Exercises/Generators/WordSearch.cs | 4 +- generators/Helpers/NameExtensions.cs | 20 ++++++++- 5 files changed, 50 insertions(+), 32 deletions(-) diff --git a/exercises/dominoes/DominoesTest.cs b/exercises/dominoes/DominoesTest.cs index b1b0bc70f4..9adc50ea6e 100644 --- a/exercises/dominoes/DominoesTest.cs +++ b/exercises/dominoes/DominoesTest.cs @@ -8,7 +8,7 @@ public class DominoesTest [Fact] public void Empty_input_empty_output() { - var dominoes = Array.Empty>(); + var dominoes = Array.Empty<(int, int)>(); Assert.True(Dominoes.CanChain(dominoes)); } diff --git a/exercises/go-counting/GoCountingTest.cs b/exercises/go-counting/GoCountingTest.cs index 518a7c8722..0fd45fec50 100644 --- a/exercises/go-counting/GoCountingTest.cs +++ b/exercises/go-counting/GoCountingTest.cs @@ -69,7 +69,7 @@ public void A_stone_and_not_a_territory_on_5x5_board() " W "; var sut = new GoCounting(board); var actual = sut.Territory(coordinate); - var expected = (Owner.None, Array.Empty>()); + var expected = (Owner.None, Array.Empty<(int, int)>()); Assert.Equal(expected.Item1, actual.Item1); Assert.Equal(expected.Item2, actual.Item2); } @@ -138,8 +138,8 @@ public void One_territory_is_the_whole_board() var actual = sut.Territories(); var expected = new Dictionary[]> { - [Owner.Black] = Array.Empty>(), - [Owner.White] = Array.Empty>(), + [Owner.Black] = Array.Empty<(int, int)>(), + [Owner.White] = Array.Empty<(int, int)>(), [Owner.None] = new[] { (0, 0) } }; Assert.Equal(expected.Keys, actual.Keys); @@ -160,7 +160,7 @@ public void Two_territory_rectangular_board() { [Owner.Black] = new[] { (0, 0), (0, 1) }, [Owner.White] = new[] { (3, 0), (3, 1) }, - [Owner.None] = Array.Empty>() + [Owner.None] = Array.Empty<(int, int)>() }; Assert.Equal(expected.Keys, actual.Keys); Assert.Equal(expected[Owner.Black], actual[Owner.Black]); @@ -177,8 +177,8 @@ public void Two_region_rectangular_board() var expected = new Dictionary[]> { [Owner.Black] = new[] { (0, 0), (2, 0) }, - [Owner.White] = Array.Empty>(), - [Owner.None] = Array.Empty>() + [Owner.White] = Array.Empty<(int, int)>(), + [Owner.None] = Array.Empty<(int, int)>() }; Assert.Equal(expected.Keys, actual.Keys); Assert.Equal(expected[Owner.Black], actual[Owner.Black]); diff --git a/exercises/word-search/WordSearchTest.cs b/exercises/word-search/WordSearchTest.cs index 8247c664a0..1f98fd0a20 100644 --- a/exercises/word-search/WordSearchTest.cs +++ b/exercises/word-search/WordSearchTest.cs @@ -13,9 +13,9 @@ public void Should_accept_an_initial_game_grid_and_a_target_search_word() var grid = "jefblpepre"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { - ["clojure"] = + ["clojure"] = null }; Assert.Null(expected["clojure"]); } @@ -27,7 +27,7 @@ public void Should_locate_one_word_written_left_to_right() var grid = "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 1), (7, 1)) }; @@ -41,7 +41,7 @@ public void Should_locate_the_same_word_written_left_to_right_in_a_different_pos var grid = "mtclojurer"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((3, 1), (9, 1)) }; @@ -55,7 +55,7 @@ public void Should_locate_a_different_left_to_right_word() var grid = "coffeelplx"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["coffee"] = ((1, 1), (6, 1)) }; @@ -69,7 +69,7 @@ public void Should_locate_that_different_left_to_right_word_in_a_different_posit var grid = "xcoffeezlp"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["coffee"] = ((2, 1), (7, 1)) }; @@ -85,7 +85,7 @@ public void Should_locate_a_left_to_right_word_in_two_line_grid() "tclojurerm"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((2, 2), (8, 2)) }; @@ -102,7 +102,7 @@ public void Should_locate_a_left_to_right_word_in_three_line_grid() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 3), (7, 3)) }; @@ -126,7 +126,7 @@ public void Should_locate_a_left_to_right_word_in_ten_line_grid() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)) }; @@ -150,7 +150,7 @@ public void Should_locate_that_left_to_right_word_in_a_different_position_in_a_t "jalaycalmp"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 9), (7, 9)) }; @@ -174,7 +174,7 @@ public void Should_locate_a_different_left_to_right_word_in_a_ten_line_grid() "jalaycalmp"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["fortran"] = ((1, 7), (7, 7)) }; @@ -198,7 +198,7 @@ public void Should_locate_multiple_words() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["fortran"] = ((1, 7), (7, 7)) @@ -214,7 +214,7 @@ public void Should_locate_a_single_word_written_right_to_left() var grid = "rixilelhrs"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["elixir"] = ((6, 1), (1, 1)) }; @@ -238,7 +238,7 @@ public void Should_locate_multiple_words_written_in_different_horizontal_directi "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)) @@ -264,7 +264,7 @@ public void Should_locate_words_written_top_to_bottom() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -292,7 +292,7 @@ public void Should_locate_words_written_bottom_to_top() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -322,7 +322,7 @@ public void Should_locate_words_written_top_left_to_bottom_right() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -354,7 +354,7 @@ public void Should_locate_words_written_bottom_right_to_top_left() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -397,7 +397,7 @@ public void Should_locate_words_written_bottom_left_to_top_right() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -443,7 +443,7 @@ public void Should_locate_words_written_top_right_to_bottom_left() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -492,7 +492,7 @@ public void Should_fail_to_locate_a_word_that_is_not_in_the_puzzle() "clojurermt"; var sut = new WordSearch(grid); var actual = sut.Search(wordsToSearchFor); - var expected = new Dictionary + var expected = new Dictionary { ["clojure"] = ((1, 10), (7, 10)), ["elixir"] = ((6, 5), (1, 5)), @@ -502,7 +502,7 @@ public void Should_fail_to_locate_a_word_that_is_not_in_the_puzzle() ["lua"] = ((8, 9), (6, 7)), ["lisp"] = ((3, 6), (6, 3)), ["ruby"] = ((8, 6), (5, 9)), - ["haskell"] = + ["haskell"] = null }; Assert.Equal(expected["clojure"], actual["clojure"]); Assert.Equal(expected["elixir"], actual["elixir"]); diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 135cadae44..4805473b89 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -20,7 +20,7 @@ protected override void UpdateTestData(TestData data) data.SetConstructorInputParameters("grid"); data.Input["grid"] = new MultiLineString(data.Input["grid"]); - data.Expected = ((IDictionary)data.Expected).ToDictionary(kv => kv.Key, kv => ConvertToPosition(kv.Value)); + data.Expected = ((IDictionary)data.Expected).ToDictionary(kv => kv.Key, kv => (((int, int), (int, int))?)ConvertToPosition(kv.Value)); } protected override void UpdateTestMethod(TestMethod method) @@ -32,7 +32,7 @@ private string RenderAssert(TestMethod method) { var assert = new StringBuilder(); - foreach (var kv in (Dictionary) method.Data.Expected) + foreach (var kv in method.Data.Expected) assert.AppendLine(RenderAssertForSearchWord(kv.Key, kv.Value)); return assert.ToString(); diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index 678505da54..d8aaabcb1e 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.Linq; +using System.Reflection; using System.Text.RegularExpressions; using Humanizer; @@ -7,6 +9,18 @@ namespace Exercism.CSharp.Helpers { public static class NameExtensions { + private static readonly HashSet ValueTupleTypes = new HashSet(new[] + { + typeof(ValueTuple<>), + typeof(ValueTuple<,>), + typeof(ValueTuple<,,>), + typeof(ValueTuple<,,,>), + typeof(ValueTuple<,,,,>), + typeof(ValueTuple<,,,,,>), + typeof(ValueTuple<,,,,,,>), + typeof(ValueTuple<,,,,,,,>) + }); + public static string ToExerciseName(this Type exerciseType) => exerciseType.Name.ToExerciseName(); public static string ToExerciseName(this string input) => input.Kebaberize(); @@ -58,8 +72,12 @@ public static string ToFriendlyName(this Type type) return "string"; if (type == typeof(char)) return "char"; + if (type.IsGenericType && ValueTupleTypes.Contains(type.GetGenericTypeDefinition())) + return $"({string.Join(", ", type.GetGenericArguments().Select(ToFriendlyName))})"; + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + return $"{type.GetGenericArguments()[0].ToFriendlyName()}?"; if (type.IsGenericType) - return $"{type.Name.Split('`')[0]}<{string.Join(", ", type.GetGenericArguments().Select(ToFriendlyName).ToArray())}>"; + return $"{type.Name.Split('`')[0]}<{string.Join(", ", type.GetGenericArguments().Select(ToFriendlyName))}>"; if (type.IsArray) return $"{type.GetElementType().ToFriendlyName()}[]"; return type.Name; From 6b8c7f8829cd24c56a74758361b51fecfedc4591 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 5 Jul 2018 19:45:05 +0200 Subject: [PATCH 79/97] generators: Allow forced formatting of multi-line array --- exercises/connect/ConnectTest.cs | 18 ++++- exercises/minesweeper/MinesweeperTest.cs | 80 ++++++++++++++++--- exercises/rectangles/RectanglesTest.cs | 63 ++++++++++++--- generators/Exercises/Generators/Connect.cs | 3 + .../Exercises/Generators/Minesweeper.cs | 3 + generators/Exercises/Generators/Rectangles.cs | 3 + generators/Output/Rendering/Render.cs | 20 ++++- generators/Output/Rendering/RenderArray.cs | 20 +---- 8 files changed, 169 insertions(+), 41 deletions(-) diff --git a/exercises/connect/ConnectTest.cs b/exercises/connect/ConnectTest.cs index 969b1ab6ba..6e0da7f075 100644 --- a/exercises/connect/ConnectTest.cs +++ b/exercises/connect/ConnectTest.cs @@ -22,7 +22,10 @@ public void An_empty_board_has_no_winner() [Fact(Skip = "Remove to run test")] public void X_can_win_on_a_1x1_board() { - var board = new[] { "X" }; + var board = new[] + { + "X" + }; var sut = new Connect(board); Assert.Equal(ConnectWinner.Black, sut.Result()); } @@ -30,7 +33,10 @@ public void X_can_win_on_a_1x1_board() [Fact(Skip = "Remove to run test")] public void O_can_win_on_a_1x1_board() { - var board = new[] { "O" }; + var board = new[] + { + "O" + }; var sut = new Connect(board); Assert.Equal(ConnectWinner.White, sut.Result()); } @@ -38,7 +44,13 @@ public void O_can_win_on_a_1x1_board() [Fact(Skip = "Remove to run test")] public void Only_edges_does_not_make_a_winner() { - var board = new[] { "O O O X", " X . . X", " X . . X", " X O O O" }; + var board = new[] + { + "O O O X", + " X . . X", + " X . . X", + " X O O O" + }; var sut = new Connect(board); Assert.Equal(ConnectWinner.None, sut.Result()); } diff --git a/exercises/minesweeper/MinesweeperTest.cs b/exercises/minesweeper/MinesweeperTest.cs index ea37117527..1f6ee9b320 100644 --- a/exercises/minesweeper/MinesweeperTest.cs +++ b/exercises/minesweeper/MinesweeperTest.cs @@ -15,7 +15,10 @@ public void No_rows() [Fact(Skip = "Remove to run test")] public void No_columns() { - var minefield = new[] { "" }; + var minefield = new[] + { + "" + }; var expected = new[] { "" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -23,7 +26,12 @@ public void No_columns() [Fact(Skip = "Remove to run test")] public void No_mines() { - var minefield = new[] { " ", " ", " " }; + var minefield = new[] + { + " ", + " ", + " " + }; var expected = new[] { " ", " ", " " }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -31,7 +39,12 @@ public void No_mines() [Fact(Skip = "Remove to run test")] public void Minefield_with_only_mines() { - var minefield = new[] { "***", "***", "***" }; + var minefield = new[] + { + "***", + "***", + "***" + }; var expected = new[] { "***", "***", "***" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -39,7 +52,12 @@ public void Minefield_with_only_mines() [Fact(Skip = "Remove to run test")] public void Mine_surrounded_by_spaces() { - var minefield = new[] { " ", " * ", " " }; + var minefield = new[] + { + " ", + " * ", + " " + }; var expected = new[] { "111", "1*1", "111" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -47,7 +65,12 @@ public void Mine_surrounded_by_spaces() [Fact(Skip = "Remove to run test")] public void Space_surrounded_by_mines() { - var minefield = new[] { "***", "* *", "***" }; + var minefield = new[] + { + "***", + "* *", + "***" + }; var expected = new[] { "***", "*8*", "***" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -55,7 +78,10 @@ public void Space_surrounded_by_mines() [Fact(Skip = "Remove to run test")] public void Horizontal_line() { - var minefield = new[] { " * * " }; + var minefield = new[] + { + " * * " + }; var expected = new[] { "1*2*1" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -63,7 +89,10 @@ public void Horizontal_line() [Fact(Skip = "Remove to run test")] public void Horizontal_line_mines_at_edges() { - var minefield = new[] { "* *" }; + var minefield = new[] + { + "* *" + }; var expected = new[] { "*1 1*" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -71,7 +100,14 @@ public void Horizontal_line_mines_at_edges() [Fact(Skip = "Remove to run test")] public void Vertical_line() { - var minefield = new[] { " ", "*", " ", "*", " " }; + var minefield = new[] + { + " ", + "*", + " ", + "*", + " " + }; var expected = new[] { "1", "*", "2", "*", "1" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -79,7 +115,14 @@ public void Vertical_line() [Fact(Skip = "Remove to run test")] public void Vertical_line_mines_at_edges() { - var minefield = new[] { "*", " ", " ", " ", "*" }; + var minefield = new[] + { + "*", + " ", + " ", + " ", + "*" + }; var expected = new[] { "*", "1", " ", "1", "*" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -87,7 +130,14 @@ public void Vertical_line_mines_at_edges() [Fact(Skip = "Remove to run test")] public void Cross() { - var minefield = new[] { " * ", " * ", "*****", " * ", " * " }; + var minefield = new[] + { + " * ", + " * ", + "*****", + " * ", + " * " + }; var expected = new[] { " 2*2 ", "25*52", "*****", "25*52", " 2*2 " }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -95,7 +145,15 @@ public void Cross() [Fact(Skip = "Remove to run test")] public void Large_minefield() { - var minefield = new[] { " * * ", " * ", " * ", " * *", " * * ", " " }; + var minefield = new[] + { + " * * ", + " * ", + " * ", + " * *", + " * * ", + " " + }; var expected = new[] { "1*22*1", "12*322", " 123*2", "112*4*", "1*22*2", "111111" }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } diff --git a/exercises/rectangles/RectanglesTest.cs b/exercises/rectangles/RectanglesTest.cs index c99186a6c7..d94f27fb90 100644 --- a/exercises/rectangles/RectanglesTest.cs +++ b/exercises/rectangles/RectanglesTest.cs @@ -15,63 +15,108 @@ public void No_rows() [Fact(Skip = "Remove to run test")] public void No_columns() { - var strings = new[] { "" }; + var strings = new[] + { + "" + }; Assert.Equal(0, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void No_rectangles() { - var strings = new[] { " " }; + var strings = new[] + { + " " + }; Assert.Equal(0, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void One_rectangle() { - var strings = new[] { "+-+", "| |", "+-+" }; + var strings = new[] + { + "+-+", + "| |", + "+-+" + }; Assert.Equal(1, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Two_rectangles_without_shared_parts() { - var strings = new[] { " +-+", " | |", "+-+-+", "| | ", "+-+ " }; + var strings = new[] + { + " +-+", + " | |", + "+-+-+", + "| | ", + "+-+ " + }; Assert.Equal(2, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Five_rectangles_with_shared_parts() { - var strings = new[] { " +-+", " | |", "+-+-+", "| | |", "+-+-+" }; + var strings = new[] + { + " +-+", + " | |", + "+-+-+", + "| | |", + "+-+-+" + }; Assert.Equal(5, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Rectangle_of_height_1_is_counted() { - var strings = new[] { "+--+", "+--+" }; + var strings = new[] + { + "+--+", + "+--+" + }; Assert.Equal(1, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Rectangle_of_width_1_is_counted() { - var strings = new[] { "++", "||", "++" }; + var strings = new[] + { + "++", + "||", + "++" + }; Assert.Equal(1, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Number_1x1_square_is_counted() { - var strings = new[] { "++", "++" }; + var strings = new[] + { + "++", + "++" + }; Assert.Equal(1, Rectangles.Count(strings)); } [Fact(Skip = "Remove to run test")] public void Only_complete_rectangles_are_counted() { - var strings = new[] { " +-+", " |", "+-+-+", "| | -", "+-+-+" }; + var strings = new[] + { + " +-+", + " |", + "+-+-+", + "| | -", + "+-+-+" + }; Assert.Equal(1, Rectangles.Count(strings)); } diff --git a/generators/Exercises/Generators/Connect.cs b/generators/Exercises/Generators/Connect.cs index e71a653445..17cc859d2a 100644 --- a/generators/Exercises/Generators/Connect.cs +++ b/generators/Exercises/Generators/Connect.cs @@ -1,4 +1,5 @@ using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -9,6 +10,8 @@ protected override void UpdateTestData(TestData data) data.UseVariablesForConstructorParameters = true; data.SetConstructorInputParameters("board"); data.TestedMethod = "Result"; + + data.Input["board"] = new UnescapedValue(Render.ArrayMultiLine(data.Input["board"])); switch (data.Expected) { diff --git a/generators/Exercises/Generators/Minesweeper.cs b/generators/Exercises/Generators/Minesweeper.cs index 6ddec63513..876b5acf80 100644 --- a/generators/Exercises/Generators/Minesweeper.cs +++ b/generators/Exercises/Generators/Minesweeper.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators @@ -14,6 +15,8 @@ protected override void UpdateTestData(TestData data) if (data.Input["minefield"] is JArray) data.Input["minefield"] = Array.Empty(); + + data.Input["minefield"] = new UnescapedValue(Render.ArrayMultiLine(data.Input["minefield"])); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/Rectangles.cs b/generators/Exercises/Generators/Rectangles.cs index e935e5d878..444c25b283 100644 --- a/generators/Exercises/Generators/Rectangles.cs +++ b/generators/Exercises/Generators/Rectangles.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators @@ -14,6 +15,8 @@ protected override void UpdateTestData(TestData data) if (data.Input["strings"] is JArray) data.Input["strings"] = Array.Empty(); + + data.Input["strings"] = new UnescapedValue(Render.ArrayMultiLine(data.Input["strings"])); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index c29482bb7e..e9102875f0 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -1,9 +1,12 @@ using System.Collections.Generic; +using System.Linq; namespace Exercism.CSharp.Output.Rendering { public partial class Render - { + { + private const int MaximumLengthForSingleLineValue = 68; + public string Object(object val) { if (val == null) @@ -43,7 +46,9 @@ public string ObjectMultiLine(object val) return DictionaryMultiLine((dynamic) val); if (IsArray(val)) - return ArrayMultiLine((dynamic) val); + return RenderAsSingleLine((dynamic)val) + ? Array((dynamic) val) + : ArrayMultiLine((dynamic) val); return Object(val); } @@ -57,5 +62,16 @@ private static bool IsArray(object obj) private static bool IsDictionary(object obj) => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>); + + private bool RenderAsSingleLine(T[] elements) + => !elements.Any() || IsNotArrayOfArrays(elements) && RenderedAsSingleLineDoesNotExceedMaximumLength(elements); + + private bool RenderAsSingleLine(T[,] elements) => false; + + private static bool IsNotArrayOfArrays(T[] elements) + => !elements.GetType().GetElementType().IsArray; + + private bool RenderedAsSingleLineDoesNotExceedMaximumLength(T[] elements) + => Array(elements).Length <= MaximumLengthForSingleLineValue; } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderArray.cs b/generators/Output/Rendering/RenderArray.cs index 4148442498..1b0ccc77c7 100644 --- a/generators/Output/Rendering/RenderArray.cs +++ b/generators/Output/Rendering/RenderArray.cs @@ -1,20 +1,17 @@ -using System.Linq; -using Exercism.CSharp.Helpers; +using Exercism.CSharp.Helpers; namespace Exercism.CSharp.Output.Rendering { public partial class Render - { - private const int MaximumLengthForSingleLineValue = 68; - + { public string Array(T[] elements) => elements.Length == 0 ? $"Array.Empty<{typeof(T).ToFriendlyName()}>()" : $"new[]{CollectionInitializer(elements)}"; public string ArrayMultiLine(T[] elements) - => RenderAsSingleLine(elements) - ? Array(elements) + => elements.Length == 0 + ? $"Array.Empty<{typeof(T).ToFriendlyName()}>()" : $"new[]{MultiLineCollectionInitializer(elements)}"; public string Array(T[,] elements) @@ -26,14 +23,5 @@ public string ArrayMultiLine(T[,] elements) => elements.Length == 0 ? $"new {typeof(T).ToFriendlyName()}[,] {{ }}" : $"new[,]{MultiLineCollectionInitializer(elements.Rows(), CollectionInitializer)}"; - - private bool RenderAsSingleLine(T[] elements) - => !elements.Any() || IsNotArrayOfArrays(elements) && RenderedAsSingleLineDoesNotExceedMaximumLength(elements); - - private static bool IsNotArrayOfArrays(T[] elements) - => !elements.GetType().GetElementType().IsArray; - - private bool RenderedAsSingleLineDoesNotExceedMaximumLength(T[] elements) - => Array(elements).Length <= MaximumLengthForSingleLineValue; } } \ No newline at end of file From 046ab428289c8a8877c2b26bbe27bfe6d8b5fbc6 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 5 Jul 2018 19:47:44 +0200 Subject: [PATCH 80/97] generators: Fix list-ops nested empty list --- exercises/list-ops/ListOpsTest.cs | 2 +- generators/Exercises/Generators/ListOps.cs | 12 ++++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/exercises/list-ops/ListOpsTest.cs b/exercises/list-ops/ListOpsTest.cs index 99c5cbcf81..38cbc1cf28 100644 --- a/exercises/list-ops/ListOpsTest.cs +++ b/exercises/list-ops/ListOpsTest.cs @@ -35,7 +35,7 @@ public void Append_entries_to_a_list_and_return_the_new_list_non_empty_lists() [Fact(Skip = "Remove to run test")] public void Concatenate_a_list_of_lists_empty_list() { - var lists = new List(); + var lists = new List>(); Assert.Empty(ListOps.Concat(lists)); } diff --git a/generators/Exercises/Generators/ListOps.cs b/generators/Exercises/Generators/ListOps.cs index 81bf088384..b6e39aaa59 100644 --- a/generators/Exercises/Generators/ListOps.cs +++ b/generators/Exercises/Generators/ListOps.cs @@ -26,7 +26,7 @@ protected override void UpdateTestData(TestData data) data.Input["list2"] = ConvertToList(list2); if (data.Input.TryGetValue("lists", out var lists)) - data.Input["lists"] = ConvertToList(lists); + data.Input["lists"] = ConvertToNestedList(lists); if (data.Input.TryGetValue("function", out var function)) data.Input["function"] = ConvertToFunction(data.Property, function); @@ -67,7 +67,12 @@ private static dynamic ConvertToList(dynamic value) throw new ArgumentException("Unsupported list type"); } - + + private static dynamic ConvertToNestedList(dynamic value) + => IsEmptyList(value) + ? new List>() + : ConvertToList(value); + private static bool IsArrayOfIntegers(dynamic value) => value is int []; @@ -79,6 +84,9 @@ private static bool IsListOfListOfIntegers(dynamic value) private static bool IsListOfListOfListOfIntegers(dynamic value) => value is JArray jArray && jArray.All(IsListOfListOfIntegers); + + private static bool IsEmptyList(dynamic value) + => value is JArray jArray && jArray.Count == 0; protected override void UpdateNamespaces(ISet namespaces) { From 76754ca09aa8fc5f650f5d3e30b12807fbf600d7 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 5 Jul 2018 19:50:28 +0200 Subject: [PATCH 81/97] generators: Add missing namespace to nucleotide-count generator --- exercises/nucleotide-count/NucleotideCountTest.cs | 1 + generators/Exercises/Generators/NucleotideCount.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/exercises/nucleotide-count/NucleotideCountTest.cs b/exercises/nucleotide-count/NucleotideCountTest.cs index bf3bdac204..44a5d9edbd 100644 --- a/exercises/nucleotide-count/NucleotideCountTest.cs +++ b/exercises/nucleotide-count/NucleotideCountTest.cs @@ -1,5 +1,6 @@ // This file was auto-generated based on version 1.3.0 of the canonical data. +using System; using System.Collections.Generic; using Xunit; diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index 1497cc6072..ed93de0eaa 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -22,6 +22,7 @@ private static dynamic ConvertExpected(dynamic expected) protected override void UpdateNamespaces(ISet namespaces) { + namespaces.Add(typeof(ArgumentException).Namespace); namespaces.Add(typeof(Dictionary).Namespace); } From 5e82b5bd0860dc0c018f4d71e6551d45c141dacd Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 5 Jul 2018 19:55:19 +0200 Subject: [PATCH 82/97] generators: Fix failing grep example implementation --- exercises/grep/Example.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/exercises/grep/Example.cs b/exercises/grep/Example.cs index e4760781da..0806200374 100644 --- a/exercises/grep/Example.cs +++ b/exercises/grep/Example.cs @@ -71,7 +71,7 @@ private static IEnumerable FindMatchingLines(string pattern, Flags flags, private static Line CreateLine(string file, int index, string text) => new Line { File = file, Number = index + 1, Text = text }; - private static string FormatMatchingFile(string file) => $"{file}\n"; + private static string FormatMatchingFile(string file) => $"{file}"; private static string FormatMatchingFiles(string pattern, Flags flags, string[] files) { @@ -79,7 +79,7 @@ private static string FormatMatchingFiles(string pattern, Flags flags, string[] .Where(file => FindMatchingLines(pattern, flags, file).Any()) .Select(FormatMatchingFile); - return string.Concat(matchingFiles); + return string.Join("\n", matchingFiles); } private static string FormatMatchingLine(Flags flags, string[] files, Line line) @@ -89,18 +89,18 @@ private static string FormatMatchingLine(Flags flags, string[] files, Line line) if (printLineNumbers && printFileName) { - return $"{line.File}:{line.Number}:{line.Text}\n"; + return $"{line.File}:{line.Number}:{line.Text}"; } if (printLineNumbers && !printFileName) { - return $"{line.Number}:{line.Text}\n"; + return $"{line.Number}:{line.Text}"; } if (!printLineNumbers && printFileName) { - return $"{line.File}:{line.Text}\n"; + return $"{line.File}:{line.Text}"; } - return $"{line.Text}\n"; + return $"{line.Text}"; } private static string FormatMatchingLines(string pattern, Flags flags, string[] files) @@ -109,6 +109,6 @@ private static string FormatMatchingLines(string pattern, Flags flags, string[] .SelectMany(file => FindMatchingLines(pattern, flags, file)) .Select(line => FormatMatchingLine(flags, files, line)); - return string.Concat(matchingFiles); + return string.Join("\n", matchingFiles); } } \ No newline at end of file From 3fe8b01448b7f02438d67ea0d78a146238cb6236 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Thu, 5 Jul 2018 20:01:56 +0200 Subject: [PATCH 83/97] exercises: Use shorthand notation for ValueTuple --- exercises/go-counting/Example.cs | 52 ++++++++++++------------- exercises/go-counting/GoCounting.cs | 4 +- exercises/go-counting/GoCountingTest.cs | 6 +-- exercises/word-search/Example.cs | 14 +++---- 4 files changed, 38 insertions(+), 38 deletions(-) diff --git a/exercises/go-counting/Example.cs b/exercises/go-counting/Example.cs index da48e0bbbf..289714a151 100644 --- a/exercises/go-counting/Example.cs +++ b/exercises/go-counting/Example.cs @@ -37,45 +37,45 @@ private static Owner[][] ParseBoard(string input) private int Cols => board[0].Length; private int Rows => board.Length; - private bool IsValidCoordinate(ValueTuple coordinate) => + private bool IsValidCoordinate((int, int) coordinate) => coordinate.Item2 >= 0 && coordinate.Item2 < Rows && coordinate.Item1 >= 0 && coordinate.Item1 < Cols; - private Owner GetPlayer(ValueTuple coordinate) => board[coordinate.Item2][coordinate.Item1]; + private Owner GetPlayer((int, int) coordinate) => board[coordinate.Item2][coordinate.Item1]; - private bool IsEmpty(ValueTuple coordinate) => GetPlayer(coordinate) == Owner.None; - private bool IsTaken(ValueTuple coordinate) => !IsEmpty(coordinate); + private bool IsEmpty((int, int) coordinate) => GetPlayer(coordinate) == Owner.None; + private bool IsTaken((int, int) coordinate) => !IsEmpty(coordinate); - private IEnumerable> EmptyCoordinates() + private IEnumerable<(int, int)> EmptyCoordinates() { return Enumerable.Range(0, Cols).SelectMany(col => - Enumerable.Range(0, Rows).Select(row => new ValueTuple(col, row))) + Enumerable.Range(0, Rows).Select(row => (col, row))) .Where(IsEmpty); } - private IEnumerable> NeighborCoordinates(ValueTuple coordinate) + private IEnumerable<(int, int)> NeighborCoordinates((int, int) coordinate) { var row = coordinate.Item2; var col = coordinate.Item1; var coords = new[] { - new ValueTuple(col, row - 1), - new ValueTuple(col-1, row), - new ValueTuple(col+1, row), - new ValueTuple(col, row+1) + (col, row - 1), + (col-1, row), + (col+1, row), + (col, row+1) }; return coords.Where(IsValidCoordinate); } - private IEnumerable> TakenNeighborCoordinates(ValueTuple coordinate) => + private IEnumerable<(int, int)> TakenNeighborCoordinates((int, int) coordinate) => NeighborCoordinates(coordinate).Where(IsTaken); - private IEnumerable> EmptyNeighborCoordinates(ValueTuple coordinate) => + private IEnumerable<(int, int)> EmptyNeighborCoordinates((int, int) coordinate) => NeighborCoordinates(coordinate).Where(IsEmpty); - private Owner TerritoryOwner(IEnumerable> coords) + private Owner TerritoryOwner(IEnumerable<(int, int)> coords) { var neighborColors = coords.SelectMany(TakenNeighborCoordinates).Select(GetPlayer); var uniqueNeighborColors = ToSet(neighborColors); @@ -86,12 +86,12 @@ private Owner TerritoryOwner(IEnumerable> coords) return Owner.None; } - private HashSet> TerritoryHelper(HashSet> remainder, HashSet> acc) + private HashSet<(int, int)> TerritoryHelper(HashSet<(int, int)> remainder, HashSet<(int, int)> acc) { if (!remainder.Any()) return acc; - var emptyNeighbors = new HashSet>(remainder.SelectMany(EmptyNeighborCoordinates)); + var emptyNeighbors = new HashSet<(int, int)>(remainder.SelectMany(EmptyNeighborCoordinates)); emptyNeighbors.ExceptWith(acc); var newAcc = ToSet(acc); @@ -99,12 +99,12 @@ private HashSet> TerritoryHelper(HashSet> TerritoryHelper(ValueTuple coordinate) => + private HashSet<(int, int)> TerritoryHelper((int, int) coordinate) => IsValidCoordinate(coordinate) && IsEmpty(coordinate) ? TerritoryHelper(ToSingletonSet(coordinate), ToSingletonSet(coordinate)) - : new HashSet>(); + : new HashSet<(int, int)>(); - public ValueTuple>> Territory(ValueTuple coord) + public ValueTuple> Territory((int, int) coord) { if (coord.Item1 < 0 || coord.Item1 >= Rows || coord.Item2 < 0 || coord.Item2 >= Cols) { @@ -113,13 +113,13 @@ public ValueTuple>> Territory(ValueTuple var coords = TerritoryHelper(coord); if (!coords.Any()) - return (Owner.None, Enumerable.Empty>()); + return (Owner.None, Enumerable.Empty<(int, int)>()); var owner = TerritoryOwner(coords); return (owner, coords.OrderBy(x => x.Item1).ThenBy(x => x.Item2).ToArray()); } - private Dictionary[]> TerritoriesHelper(HashSet> remainder, Dictionary[]> acc) + private Dictionary TerritoriesHelper(HashSet<(int, int)> remainder, Dictionary acc) { if (!remainder.Any()) return acc; @@ -135,15 +135,15 @@ private Dictionary[]> TerritoriesHelper(HashSet[]> Territories() + public Dictionary Territories() { var emptyCoords = EmptyCoordinates(); - var territories = new Dictionary[]> + var territories = new Dictionary { - [Owner.Black] = new ValueTuple[0], - [Owner.White] = new ValueTuple[0], - [Owner.None] = new ValueTuple[0] + [Owner.Black] = Array.Empty<(int, int)>(), + [Owner.White] = Array.Empty<(int, int)>(), + [Owner.None] = Array.Empty<(int, int)>() }; return TerritoriesHelper(ToSet(emptyCoords), territories); diff --git a/exercises/go-counting/GoCounting.cs b/exercises/go-counting/GoCounting.cs index 7bccd2ace0..7637951aad 100644 --- a/exercises/go-counting/GoCounting.cs +++ b/exercises/go-counting/GoCounting.cs @@ -15,12 +15,12 @@ public GoCounting(string input) throw new NotImplementedException("You need to implement this function."); } - public Tuple>> TerritoryFor(ValueTuple coord) + public Tuple> TerritoryFor((int, int) coord) { throw new NotImplementedException("You need to implement this function."); } - public Dictionary>> Territories() + public Dictionary> Territories() { throw new NotImplementedException("You need to implement this function."); } diff --git a/exercises/go-counting/GoCountingTest.cs b/exercises/go-counting/GoCountingTest.cs index 0fd45fec50..c4459cff26 100644 --- a/exercises/go-counting/GoCountingTest.cs +++ b/exercises/go-counting/GoCountingTest.cs @@ -136,7 +136,7 @@ public void One_territory_is_the_whole_board() var board = " "; var sut = new GoCounting(board); var actual = sut.Territories(); - var expected = new Dictionary[]> + var expected = new Dictionary { [Owner.Black] = Array.Empty<(int, int)>(), [Owner.White] = Array.Empty<(int, int)>(), @@ -156,7 +156,7 @@ public void Two_territory_rectangular_board() " BW "; var sut = new GoCounting(board); var actual = sut.Territories(); - var expected = new Dictionary[]> + var expected = new Dictionary { [Owner.Black] = new[] { (0, 0), (0, 1) }, [Owner.White] = new[] { (3, 0), (3, 1) }, @@ -174,7 +174,7 @@ public void Two_region_rectangular_board() var board = " B "; var sut = new GoCounting(board); var actual = sut.Territories(); - var expected = new Dictionary[]> + var expected = new Dictionary { [Owner.Black] = new[] { (0, 0), (2, 0) }, [Owner.White] = Array.Empty<(int, int)>(), diff --git a/exercises/word-search/Example.cs b/exercises/word-search/Example.cs index 2b561ce86d..f5410125cd 100644 --- a/exercises/word-search/Example.cs +++ b/exercises/word-search/Example.cs @@ -9,7 +9,7 @@ public class WordSearch private readonly int height; private (int, int)[] positions; - private static readonly ValueTuple[] Directions = + private static readonly (int, int)[] Directions = { ( 1, 0), ( 0, 1), @@ -29,12 +29,12 @@ public WordSearch(string puzzle) positions = Positions(); } - public Dictionary, ValueTuple>?> Search(IEnumerable words) + public Dictionary Search(IEnumerable words) { return words.ToDictionary(word => word, Search); } - private ValueTuple, ValueTuple>? Search(string word) + private ((int, int), (int, int))? Search(string word) { return Positions() @@ -42,7 +42,7 @@ public WordSearch(string puzzle) .FirstOrDefault(); } - private IEnumerable, ValueTuple>> Find(string word, ValueTuple position, ValueTuple direction) + private IEnumerable<((int, int), (int, int))> Find(string word, (int, int) position, (int, int) direction) { var current = position; @@ -56,10 +56,10 @@ private IEnumerable, ValueTuple>> Find current = (current.Item1 + direction.Item1, current.Item2 + direction.Item2); } - yield return ValueTuple.Create(position, (current.Item1 - direction.Item1, current.Item2 - direction.Item2)); + yield return (position, (current.Item1 - direction.Item1, current.Item2 - direction.Item2)); } - private char? FindChar(ValueTuple coordinate) + private char? FindChar((int, int) coordinate) { if (coordinate.Item1 > 0 && coordinate.Item1 <= width && coordinate.Item2 > 0 && coordinate.Item2 <= height) { @@ -69,7 +69,7 @@ private IEnumerable, ValueTuple>> Find return null; } - private ValueTuple[] Positions() + private (int, int)[] Positions() { return Enumerable.Range(1, width).SelectMany(x => Enumerable.Range(1, height).Select(y => (x, y))) From 56a0fa2e9b8fdf765ca7fca0031c16a6249b0665 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 6 Jul 2018 08:38:44 +0200 Subject: [PATCH 84/97] generators: Fix multiline rendering not handling null references --- generators/Output/Rendering/Render.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index e9102875f0..7d23ce32c2 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -37,6 +37,9 @@ public string Object(object val) public string ObjectMultiLine(object val) { + if (val == null) + return "null"; + switch (val) { case MultiLineString multiLineValue: @@ -63,11 +66,11 @@ private static bool IsArray(object obj) private static bool IsDictionary(object obj) => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>); + private static bool RenderAsSingleLine(T[,] elements) => false; + private bool RenderAsSingleLine(T[] elements) => !elements.Any() || IsNotArrayOfArrays(elements) && RenderedAsSingleLineDoesNotExceedMaximumLength(elements); - private bool RenderAsSingleLine(T[,] elements) => false; - private static bool IsNotArrayOfArrays(T[] elements) => !elements.GetType().GetElementType().IsArray; From 42c4ee8a1a07b6bd2d812b319721f80cca8d94d0 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 6 Jul 2018 08:53:30 +0200 Subject: [PATCH 85/97] generators: Make TestClassFile static --- generators/Exercises/GeneratorExercise.cs | 10 +++------- generators/Generators.csproj | 1 + generators/Helpers/EmbeddedResource.cs | 16 ++++++++++++++++ generators/Input/TrackConfigFile.cs | 6 +++--- generators/Output/TestClassFile.cs | 16 ++++++---------- 5 files changed, 29 insertions(+), 20 deletions(-) create mode 100644 generators/Helpers/EmbeddedResource.cs diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index a799c7241a..201d24f657 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -18,13 +18,9 @@ public abstract class GeneratorExercise : Exercise public override string Name => GetType().ToExerciseName(); public void Regenerate(CanonicalData canonicalData) - { - _canonicalData = canonicalData; - _testData = CreateTestData(); - - var testClass = CreateTestClass(); - var testClassFile = new TestClassFile(testClass); - testClassFile.Write(); + { + var testClass = CreateTestClass(canonicalData); + TestClassFile.Write(testClass); } private TestClass CreateTestClass() diff --git a/generators/Generators.csproj b/generators/Generators.csproj index a56c06b6bb..3d7be3919d 100644 --- a/generators/Generators.csproj +++ b/generators/Generators.csproj @@ -15,5 +15,6 @@ + \ No newline at end of file diff --git a/generators/Helpers/EmbeddedResource.cs b/generators/Helpers/EmbeddedResource.cs new file mode 100644 index 0000000000..8e1e9639ee --- /dev/null +++ b/generators/Helpers/EmbeddedResource.cs @@ -0,0 +1,16 @@ +using System.IO; + +namespace Exercism.CSharp.Helpers +{ + public static class EmbeddedResource + { + public static string Read(string name) + { + using (var stream = typeof(EmbeddedResource).Assembly.GetManifestResourceStream(name)) + using (var streamReader = new StreamReader(stream)) + { + return streamReader.ReadToEnd(); + } + } + } +} diff --git a/generators/Input/TrackConfigFile.cs b/generators/Input/TrackConfigFile.cs index 34e7418074..a312a3cc34 100644 --- a/generators/Input/TrackConfigFile.cs +++ b/generators/Input/TrackConfigFile.cs @@ -1,17 +1,17 @@ using System.Collections.Generic; -using System.IO; using System.Linq; +using Exercism.CSharp.Helpers; using Newtonsoft.Json; namespace Exercism.CSharp.Input { public static class TrackConfigFile { - private const string ConfigFilePath = "../config.json"; + private static readonly string ConfigFileName = $"{typeof(TrackConfigFile).Namespace}.config.json"; public static IEnumerable GetExercises() { - var jsonContents = File.ReadAllText(ConfigFilePath); + var jsonContents = EmbeddedResource.Read(ConfigFileName); var config = JsonConvert.DeserializeObject(jsonContents); return config.Exercises.OrderBy(x => x.Slug).ToArray(); } diff --git a/generators/Output/TestClassFile.cs b/generators/Output/TestClassFile.cs index 32c5150b64..52cbf1453e 100644 --- a/generators/Output/TestClassFile.cs +++ b/generators/Output/TestClassFile.cs @@ -2,23 +2,19 @@ namespace Exercism.CSharp.Output { - public class TestClassFile + public static class TestClassFile { - private readonly TestClass _testClass; - - public TestClassFile(TestClass testClass) => _testClass = testClass; - - public void Write() + public static void Write(TestClass testClass) { - var testClassFilePath = TestClassFilePath; - var testClassContents = _testClass.Render(); + var testClassFilePath = TestClassFilePath(testClass); + var testClassContents = testClass.Render(); Directory.CreateDirectory(Path.GetDirectoryName(testClassFilePath)); File.WriteAllText(testClassFilePath, testClassContents); } - private string TestClassFilePath => Path.Combine("..", "exercises", _testClass.Exercise, TestClassFileName); + private static string TestClassFilePath(TestClass testClass) => Path.Combine("..", "exercises", testClass.Exercise, TestClassFileName(testClass)); - private string TestClassFileName => $"{_testClass.ClassName}.cs"; + private static string TestClassFileName(TestClass testClass) => $"{testClass.ClassName}.cs"; } } \ No newline at end of file From 4959a96eb2215485cbb0817a381b0e3ebaa6a582 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 6 Jul 2018 18:18:01 +0200 Subject: [PATCH 86/97] generators: Merge TestData with TestMethod --- generators/Exercises/GeneratorExercise.cs | 93 ++------ .../Exercises/Generators/AllYourBase.cs | 14 +- generators/Exercises/Generators/Allergies.cs | 31 ++- .../Exercises/Generators/Alphametics.cs | 16 +- generators/Exercises/Generators/Anagram.cs | 8 +- generators/Exercises/Generators/BeerSong.cs | 6 +- .../Exercises/Generators/BinarySearch.cs | 10 +- .../Exercises/Generators/BinarySearchTree.cs | 12 +- generators/Exercises/Generators/BookStore.cs | 12 +- generators/Exercises/Generators/Bowling.cs | 55 ++--- .../Exercises/Generators/BracketPush.cs | 6 +- generators/Exercises/Generators/Change.cs | 10 +- .../Exercises/Generators/CircularBuffer.cs | 14 +- generators/Exercises/Generators/Clock.cs | 51 ++-- .../Exercises/Generators/CollatzConjecture.cs | 6 +- .../Exercises/Generators/ComplexNumbers.cs | 47 ++-- generators/Exercises/Generators/Connect.cs | 18 +- .../Exercises/Generators/CryptoSquare.cs | 6 +- generators/Exercises/Generators/CustomSet.cs | 26 +- .../Generators/DifferenceOfSquares.cs | 4 +- generators/Exercises/Generators/Dominoes.cs | 6 +- generators/Exercises/Generators/Etl.cs | 12 +- .../Exercises/Generators/FlattenArray.cs | 10 +- generators/Exercises/Generators/FoodChain.cs | 10 +- generators/Exercises/Generators/Forth.cs | 10 +- generators/Exercises/Generators/Gigasecond.cs | 8 +- generators/Exercises/Generators/GoCounting.cs | 53 ++--- generators/Exercises/Generators/Grains.cs | 8 +- generators/Exercises/Generators/Grep.cs | 52 ++-- generators/Exercises/Generators/Hamming.cs | 6 +- generators/Exercises/Generators/House.cs | 10 +- .../Generators/KindergartenGarden.cs | 14 +- .../Generators/LargestSeriesProduct.cs | 8 +- generators/Exercises/Generators/Leap.cs | 4 +- generators/Exercises/Generators/ListOps.cs | 32 +-- generators/Exercises/Generators/Luhn.cs | 4 +- generators/Exercises/Generators/Markdown.cs | 10 +- generators/Exercises/Generators/Matrix.cs | 6 +- generators/Exercises/Generators/Meetup.cs | 27 +-- .../Exercises/Generators/Minesweeper.cs | 12 +- generators/Exercises/Generators/NthPrime.cs | 6 +- .../Exercises/Generators/NucleotideCount.cs | 40 ++-- generators/Exercises/Generators/OcrNumbers.cs | 14 +- .../Generators/PalindromeProducts.cs | 23 +- .../Exercises/Generators/PascalsTriangle.cs | 12 +- .../Exercises/Generators/PerfectNumbers.cs | 8 +- .../Exercises/Generators/PhoneNumber.cs | 8 +- generators/Exercises/Generators/Poker.cs | 8 +- generators/Exercises/Generators/Pov.cs | 16 +- generators/Exercises/Generators/Proverb.cs | 12 +- .../Exercises/Generators/QueenAttack.cs | 75 +++--- .../Exercises/Generators/RailFenceCipher.cs | 8 +- .../Exercises/Generators/RationalNumbers.cs | 18 +- generators/Exercises/Generators/React.cs | 12 +- generators/Exercises/Generators/Rectangles.cs | 12 +- .../Exercises/Generators/RnaTranscription.cs | 6 +- .../Exercises/Generators/RobotSimulator.cs | 35 ++- .../Exercises/Generators/RomanNumerals.cs | 6 +- .../Exercises/Generators/RunLengthEncoding.cs | 23 +- .../Exercises/Generators/SaddlePoints.cs | 28 +-- generators/Exercises/Generators/Say.cs | 8 +- .../Exercises/Generators/ScaleGenerator.cs | 4 +- generators/Exercises/Generators/Sieve.cs | 8 +- .../Exercises/Generators/SimpleCipher.cs | 58 ++--- generators/Exercises/Generators/SpaceAge.cs | 8 +- .../Exercises/Generators/SpiralMatrix.cs | 8 +- generators/Exercises/Generators/Sublist.cs | 10 +- .../Exercises/Generators/SumOfMultiples.cs | 6 +- generators/Exercises/Generators/Tournament.cs | 41 ++-- generators/Exercises/Generators/Transpose.cs | 12 +- generators/Exercises/Generators/Triangle.cs | 16 +- generators/Exercises/Generators/TwelveDays.cs | 10 +- generators/Exercises/Generators/TwoBucket.cs | 25 +- generators/Exercises/Generators/TwoFer.cs | 8 +- .../Generators/VariableLengthQuantity.cs | 14 +- generators/Exercises/Generators/WordCount.cs | 8 +- generators/Exercises/Generators/WordSearch.cs | 26 +- generators/Exercises/Generators/Wordy.cs | 6 +- generators/Exercises/Generators/Yacht.cs | 6 +- .../Exercises/Generators/ZebraPuzzle.cs | 4 +- generators/Exercises/Generators/Zipper.cs | 17 +- generators/Exercises/TestedMethodType.cs | 8 +- generators/Generators.csproj | 1 - generators/Helpers/NameExtensions.cs | 1 - generators/Input/JTokenHelper.cs | 2 +- generators/Input/TrackConfigFile.cs | 5 +- generators/Output/Rendering/Render.cs | 2 + generators/Output/Rendering/RenderString.cs | 3 + generators/Output/Rendering/RenderVariable.cs | 8 +- generators/Output/TestClass.cs | 2 +- generators/Output/TestData.cs | 79 ------- generators/Output/TestMethod.cs | 223 ++++++++++++++---- .../Output/TestMethodWithBooleanAssertion.cs | 13 - .../Output/TestMethodWithEmptyAssertion.cs | 12 - .../Output/TestMethodWithEqualityAssertion.cs | 11 - .../TestMethodWithExceptionAssertion.cs | 13 - .../Output/TestMethodWithNullAssertion.cs | 11 - 97 files changed, 843 insertions(+), 971 deletions(-) delete mode 100644 generators/Output/TestData.cs delete mode 100644 generators/Output/TestMethodWithBooleanAssertion.cs delete mode 100644 generators/Output/TestMethodWithEmptyAssertion.cs delete mode 100644 generators/Output/TestMethodWithEqualityAssertion.cs delete mode 100644 generators/Output/TestMethodWithExceptionAssertion.cs delete mode 100644 generators/Output/TestMethodWithNullAssertion.cs diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index 201d24f657..78cbd70acc 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -1,5 +1,4 @@ -using System.Collections; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Helpers; using Exercism.CSharp.Input; @@ -10,12 +9,9 @@ namespace Exercism.CSharp.Exercises { public abstract class GeneratorExercise : Exercise { - private CanonicalData _canonicalData; - private TestData[] _testData; - - protected Render Render { get; } = new Render(); - public override string Name => GetType().ToExerciseName(); + + protected Render Render { get; } = new Render(); public void Regenerate(CanonicalData canonicalData) { @@ -23,28 +19,29 @@ public void Regenerate(CanonicalData canonicalData) TestClassFile.Write(testClass); } - private TestClass CreateTestClass() + private TestClass CreateTestClass(CanonicalData canonicalData) { + var testMethods = CreateTestMethods(canonicalData); var testClass = new TestClass { - Exercise = _canonicalData.Exercise, - CanonicalDataVersion = _canonicalData.Version, - ClassName = _canonicalData.Exercise.ToTestClassName(), - Methods = GetMethods(), - Namespaces = GetNamespaces() + Exercise = canonicalData.Exercise, + CanonicalDataVersion = canonicalData.Version, + ClassName = canonicalData.Exercise.ToTestClassName(), + Methods = testMethods.Select(testMethod => testMethod.Render()).ToList(), + Namespaces = GetNamespaces(testMethods) }; - UpdateTestClass(testClass); + return testClass; } - protected virtual void UpdateTestClass(TestClass @class) + protected virtual void UpdateTestClass(TestClass testClass) { } - private ISet GetNamespaces() + private ISet GetNamespaces(IEnumerable testMethods) { - var exceptionNamespaces = _testData + var exceptionNamespaces = testMethods .Where(x => x.ExceptionThrown != null) .Select(x => x.ExceptionThrown.Namespace); @@ -52,69 +49,29 @@ private ISet GetNamespaces() var namespaces = new SortedSet(defaultNamespaces.Concat(exceptionNamespaces)); UpdateNamespaces(namespaces); - + return namespaces; } protected virtual void UpdateNamespaces(ISet namespaces) { } + + private TestMethod[] CreateTestMethods(CanonicalData canonicalData) => + canonicalData.Cases + .Select(canonicalDataCase => CreateTestMethod(canonicalData, canonicalDataCase)) + .ToArray(); - private IList GetMethods() - { - var renderedMethods = new List(); - - foreach (var data in _testData) - { - UpdateTestData(data); - - var method = CreateTestMethod(data); - UpdateTestMethod(method); - - renderedMethods.Add(method.Render()); - } - - return renderedMethods; - } - - private static TestMethod CreateTestMethod(TestData data) + private TestMethod CreateTestMethod(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) { - if (data.ExceptionThrown != null) - return new TestMethodWithExceptionAssertion(data); + var testMethod = new TestMethod(canonicalData, canonicalDataCase); + UpdateTestMethod(testMethod); - switch (data.Expected) - { - case bool _: - return new TestMethodWithBooleanAssertion(data); - case null: - return new TestMethodWithNullAssertion(data); - default: - if (UseEmptyAssertion(data)) - return new TestMethodWithEmptyAssertion(data); - - return new TestMethodWithEqualityAssertion(data); - } + return testMethod; } - protected virtual void UpdateTestMethod(TestMethod method) + protected virtual void UpdateTestMethod(TestMethod testMethod) { } - - private TestData[] CreateTestData() => - _canonicalData.Cases - .Select(canonicalDataCase => new TestData(_canonicalData, canonicalDataCase)) - .ToArray(); - - protected virtual void UpdateTestData(TestData data) - { - } - - private static bool UseEmptyAssertion(TestData data) - { - if (data.Expected is string) - return false; - - return data.Expected is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; - } } } diff --git a/generators/Exercises/Generators/AllYourBase.cs b/generators/Exercises/Generators/AllYourBase.cs index bc1b23ac26..181dba13b9 100644 --- a/generators/Exercises/Generators/AllYourBase.cs +++ b/generators/Exercises/Generators/AllYourBase.cs @@ -7,16 +7,16 @@ namespace Exercism.CSharp.Exercises.Generators { public class AllYourBase : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Input["digits"] is JArray) - data.Input["digits"] = Array.Empty(); + if (testMethod.Input["digits"] is JArray) + testMethod.Input["digits"] = Array.Empty(); - if (data.Expected is Dictionary) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Expected is Dictionary) + testMethod.ExceptionThrown = typeof(ArgumentException); - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index b25d8e6c82..ac081de98e 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -5,32 +5,29 @@ namespace Exercism.CSharp.Exercises.Generators { public class Allergies : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Property == "allergicTo") - data.TestedMethod = $"Is{data.TestedMethod}"; - else if (data.Property == "list") - data.UseVariableForExpected = true; + if (testMethod.Property == "allergicTo") + testMethod.TestedMethod = $"Is{testMethod.TestedMethod}"; + else if (testMethod.Property == "list") + testMethod.UseVariableForExpected = true; - data.SetConstructorInputParameters("score"); - } + testMethod.SetConstructorInputParameters("score"); - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) - => method.Data.Property == "allergicTo" - ? RenderIsAllergicToAssert(method) - : method.Assert; + private string RenderAssert(TestMethod testMethod) + => testMethod.Property == "allergicTo" + ? RenderIsAllergicToAssert(testMethod) + : testMethod.Assert; - private string RenderIsAllergicToAssert(TestMethod method) + private string RenderIsAllergicToAssert(TestMethod testMethod) { var assert = new StringBuilder(); - foreach (var allergy in method.Data.Expected) - assert.AppendLine(Render.AssertBoolean(allergy["result"], $"sut.{method.Data.TestedMethod}({Render.Object(allergy["substance"])})")); + foreach (var allergy in testMethod.Expected) + assert.AppendLine(Render.AssertBoolean(allergy["result"], $"sut.{testMethod.TestedMethod}({Render.Object(allergy["substance"])})")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/Alphametics.cs b/generators/Exercises/Generators/Alphametics.cs index ec0300b2e7..431853309a 100644 --- a/generators/Exercises/Generators/Alphametics.cs +++ b/generators/Exercises/Generators/Alphametics.cs @@ -7,20 +7,20 @@ namespace Exercism.CSharp.Exercises.Generators { public class Alphametics : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; - data.UseVariableForTested = true; + testMethod.UseVariableForExpected = true; + testMethod.UseVariableForTested = true; - if (data.Expected == null) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Expected == null) + testMethod.ExceptionThrown = typeof(ArgumentException); else - data.Expected = ConvertExpected(data); + testMethod.Expected = ConvertExpected(testMethod); } - private static dynamic ConvertExpected(TestData canonicalDataCase) + private static dynamic ConvertExpected(TestMethod testMethod) { - Dictionary expected = canonicalDataCase.Expected; + Dictionary expected = testMethod.Expected; return expected.ToDictionary(kv => kv.Key[0], kv => Convert.ToInt32(kv.Value)); } diff --git a/generators/Exercises/Generators/Anagram.cs b/generators/Exercises/Generators/Anagram.cs index 578b7b197d..d48feb1730 100644 --- a/generators/Exercises/Generators/Anagram.cs +++ b/generators/Exercises/Generators/Anagram.cs @@ -4,11 +4,11 @@ namespace Exercism.CSharp.Exercises.Generators { public class Anagram : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; - data.SetConstructorInputParameters("subject"); + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; + testMethod.SetConstructorInputParameters("subject"); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/BeerSong.cs b/generators/Exercises/Generators/BeerSong.cs index d79cab351c..475e661605 100644 --- a/generators/Exercises/Generators/BeerSong.cs +++ b/generators/Exercises/Generators/BeerSong.cs @@ -5,10 +5,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class BeerSong : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; - data.Expected = new MultiLineString(data.Expected); + testMethod.UseVariableForExpected = true; + testMethod.Expected = new MultiLineString(testMethod.Expected); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/BinarySearch.cs b/generators/Exercises/Generators/BinarySearch.cs index 0149a28f3d..f0dfdbf57c 100644 --- a/generators/Exercises/Generators/BinarySearch.cs +++ b/generators/Exercises/Generators/BinarySearch.cs @@ -7,13 +7,13 @@ namespace Exercism.CSharp.Exercises.Generators { public class BinarySearch : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Input["array"] is JArray) - data.Input["array"] = Array.Empty(); + if (testMethod.Input["array"] is JArray) + testMethod.Input["array"] = Array.Empty(); - data.SetConstructorInputParameters("array"); - data.UseVariablesForConstructorParameters = true; + testMethod.SetConstructorInputParameters("array"); + testMethod.UseVariablesForConstructorParameters = true; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index 0bb72f17b0..af08765234 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -26,20 +26,20 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(IQueryable).Namespace); } - protected override void UpdateTestMethod(TestMethod method) + protected override void UpdateTestMethod(TestMethod testMethod) { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { var assert = new StringBuilder(); - var treeData = ConvertToIntegers(method.Data.Input["treeData"]); + var treeData = ConvertToIntegers(testMethod.Input["treeData"]); var constructorParameters = Render.Object(treeData.Length == 1 ? treeData[0] : treeData); assert.AppendLine(Render.Variable("tree", $"new BinarySearchTree({constructorParameters})")); - if (method.Data.Expected is Dictionary expected) + if (testMethod.Expected is Dictionary expected) { var tree = new ExpectedDataBinaryTree(expected); foreach (var testAssert in TestAsserts(tree)) @@ -47,7 +47,7 @@ private string RenderAssert(TestMethod method) } else { - var renderedExpected = Render.Object(ConvertToIntegers(method.Data.Expected)); + var renderedExpected = Render.Object(ConvertToIntegers(testMethod.Expected)); assert.AppendLine(Render.AssertEqual(renderedExpected, "tree.AsEnumerable()")); } diff --git a/generators/Exercises/Generators/BookStore.cs b/generators/Exercises/Generators/BookStore.cs index df91f37f97..2c55fa45bb 100644 --- a/generators/Exercises/Generators/BookStore.cs +++ b/generators/Exercises/Generators/BookStore.cs @@ -7,14 +7,14 @@ namespace Exercism.CSharp.Exercises.Generators { public class BookStore : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Input["basket"] is JArray) - data.Input["basket"] = Array.Empty(); + if (testMethod.Input["basket"] is JArray) + testMethod.Input["basket"] = Array.Empty(); - data.Expected = data.Expected / 100.0f; - data.SetInputParameters("basket"); - data.UseVariablesForInput = true; + testMethod.Expected = testMethod.Expected / 100.0f; + testMethod.SetInputParameters("basket"); + testMethod.UseVariablesForInput = true; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index 5a2e870669..37583a1039 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -9,64 +9,61 @@ public class Bowling : GeneratorExercise { private const string PreviousRolls = "previousRolls"; - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Expected is int) - data.UseVariableForTested = true; + if (testMethod.Expected is int) + testMethod.UseVariableForTested = true; else - data.ExceptionThrown = typeof(ArgumentException); + testMethod.ExceptionThrown = typeof(ArgumentException); - data.SetInputParameters(); - } + testMethod.SetInputParameters(); - protected override void UpdateTestMethod(TestMethod method) - { - method.Arrange = RenderArrange(method); - method.Act = RenderAct(method); - method.Assert = RenderAssert(method); + testMethod.Arrange = RenderArrange(testMethod); + testMethod.Act = RenderAct(testMethod); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderArrange(TestMethod method) + private string RenderArrange(TestMethod testMethod) { var builder = new StringBuilder(); builder.AppendLine(Render.Variable("sut", "new BowlingGame()")); - if (!method.Data.Input.ContainsKey(PreviousRolls)) + if (!testMethod.Input.ContainsKey(PreviousRolls)) return builder.ToString(); - var previousRolls = method.Data.Input[PreviousRolls] as int[] ?? Array.Empty(); + var previousRolls = testMethod.Input[PreviousRolls] as int[] ?? Array.Empty(); builder.Append(Render.Variable("previousRolls", Render.ObjectMultiLine(previousRolls))); return builder.ToString(); } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { - if (method.Data.ExceptionThrown != null && method.Data.Input.ContainsKey("roll")) + if (testMethod.ExceptionThrown != null && testMethod.Input.ContainsKey("roll")) { - var actual = Render.Object(method.Data.Input["roll"]); - return Render.AssertThrows(method.Data.ExceptionThrown, $"sut.Roll({actual})"); + var actual = Render.Object(testMethod.Input["roll"]); + return Render.AssertThrows(testMethod.ExceptionThrown, $"sut.Roll({actual})"); } - if (method.Data.ExceptionThrown == null || method.Data.Property != "score") - return method.Assert; + if (testMethod.ExceptionThrown == null || testMethod.Property != "score") + return testMethod.Assert; - return Render.AssertThrows(method.Data.ExceptionThrown, "sut.Score()"); + return Render.AssertThrows(testMethod.ExceptionThrown, "sut.Score()"); } - private string RenderAct(TestMethod method) + private string RenderAct(TestMethod testMethod) { var act = new StringBuilder(); act.AppendLine("DoRoll(previousRolls, sut);"); - if (method.Data.ExceptionThrown != null) + if (testMethod.ExceptionThrown != null) { return act.ToString(); } - if (method.Data.Input.ContainsKey("roll")) + if (testMethod.Input.ContainsKey("roll")) { - act.AppendLine($"sut.Roll({method.Data.Input["roll"]});"); + act.AppendLine($"sut.Roll({testMethod.Input["roll"]});"); act.AppendLine(Render.Variable("actual", "sut.Score()")); return act.ToString(); } @@ -75,14 +72,14 @@ private string RenderAct(TestMethod method) return act.ToString(); } - protected override void UpdateTestClass(TestClass @class) + protected override void UpdateTestClass(TestClass testClass) { - AddDoRollMethod(@class); + AddDoRollMethod(testClass); } - private static void AddDoRollMethod(TestClass @class) + private static void AddDoRollMethod(TestClass testClass) { - @class.Methods.Add(@" + testClass.Methods.Add(@" public void DoRoll(IEnumerable rolls, BowlingGame sut) { foreach (var roll in rolls) diff --git a/generators/Exercises/Generators/BracketPush.cs b/generators/Exercises/Generators/BracketPush.cs index 86e9a80efd..894a9c0198 100644 --- a/generators/Exercises/Generators/BracketPush.cs +++ b/generators/Exercises/Generators/BracketPush.cs @@ -4,10 +4,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class BracketPush : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.Input["value"] = data.Input["value"].Replace("\\", "\\\\"); - data.UseVariablesForInput = true; + testMethod.Input["value"] = testMethod.Input["value"].Replace("\\", "\\\\"); + testMethod.UseVariablesForInput = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Change.cs b/generators/Exercises/Generators/Change.cs index f2e187be8b..044db6a51f 100644 --- a/generators/Exercises/Generators/Change.cs +++ b/generators/Exercises/Generators/Change.cs @@ -5,13 +5,13 @@ namespace Exercism.CSharp.Exercises.Generators { public class Change : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; - if (data.Expected is int) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Expected is int) + testMethod.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/CircularBuffer.cs b/generators/Exercises/Generators/CircularBuffer.cs index 1d13e445f8..483db0d534 100644 --- a/generators/Exercises/Generators/CircularBuffer.cs +++ b/generators/Exercises/Generators/CircularBuffer.cs @@ -7,24 +7,24 @@ namespace Exercism.CSharp.Exercises.Generators { public class CircularBuffer : GeneratorExercise { - protected override void UpdateTestMethod(TestMethod method) + protected override void UpdateTestMethod(TestMethod testMethod) { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { var assert = new StringBuilder(); - assert.AppendLine(RenderSut(method.Data)); + assert.AppendLine(RenderSut(testMethod)); - foreach (var operation in method.Data.Input["operations"]) + foreach (var operation in testMethod.Input["operations"]) assert.AppendLine(RenderOperation(operation)); return assert.ToString(); } - private string RenderSut(TestData canonicalDataCase) - => Render.Variable("buffer", $"new CircularBuffer(capacity: {canonicalDataCase.Input["capacity"]})"); + private string RenderSut(TestMethod testMethod) + => Render.Variable("buffer", $"new CircularBuffer(capacity: {testMethod.Input["capacity"]})"); private string RenderOperation(dynamic operation) { diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 890ffd1f80..60a95f7782 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -13,55 +13,52 @@ public class Clock : GeneratorExercise private const string PropertyCreate = "create"; private const string PropertyEqual = "equal"; - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.SetConstructorInputParameters(ParamHour, ParamMinute); + testMethod.SetConstructorInputParameters(ParamHour, ParamMinute); - if (data.Property == PropertyEqual) + if (testMethod.Property == PropertyEqual) { - var clock1 = data.Input[ParamClock1]; - data.Input[ParamClock1] = new UnescapedValue($"new Clock({clock1[ParamHour]}, {clock1[ParamMinute]})"); + var clock1 = testMethod.Input[ParamClock1]; + testMethod.Input[ParamClock1] = new UnescapedValue($"new Clock({clock1[ParamHour]}, {clock1[ParamMinute]})"); - var clock2 = data.Input[ParamClock2]; - data.Input[ParamHour] = clock2[ParamHour]; - data.Input[ParamMinute] = clock2[ParamMinute]; + var clock2 = testMethod.Input[ParamClock2]; + testMethod.Input[ParamHour] = clock2[ParamHour]; + testMethod.Input[ParamMinute] = clock2[ParamMinute]; } - if (data.Property == PropertyCreate) + if (testMethod.Property == PropertyCreate) { - data.TestedMethod = "ToString"; + testMethod.TestedMethod = "ToString"; } - else if (data.Property == PropertyEqual) + else if (testMethod.Property == PropertyEqual) { - data.TestedMethod = "Equals"; + testMethod.TestedMethod = "Equals"; } - } - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { - if (method.Data.Property == PropertyEqual) + if (testMethod.Property == PropertyEqual) { - return RenderEqualToAssert(method); + return RenderEqualToAssert(testMethod); } - return method.Data.Property == PropertyCreate - ? method.Assert - : RenderConsistencyToAssert(method); + return testMethod.Property == PropertyCreate + ? testMethod.Assert + : RenderConsistencyToAssert(testMethod); } - private string RenderConsistencyToAssert(TestMethod method) - => Render.AssertEqual(method.ExpectedParameter, $"{method.TestedValue}.ToString()"); + private string RenderConsistencyToAssert(TestMethod testMethod) + => Render.AssertEqual(testMethod.ExpectedParameter, $"{testMethod.TestedValue}.ToString()"); - private string RenderEqualToAssert(TestMethod method) + private string RenderEqualToAssert(TestMethod testMethod) { - var expected = Render.Object(method.Data.Input[ParamClock1]); + var expected = Render.Object(testMethod.Input[ParamClock1]); - return method.Data.Expected + return testMethod.Expected ? Render.AssertEqual(expected, "sut") : Render.AssertNotEqual(expected, "sut"); } diff --git a/generators/Exercises/Generators/CollatzConjecture.cs b/generators/Exercises/Generators/CollatzConjecture.cs index 7d5dcc8cb7..f2c4e21b3f 100644 --- a/generators/Exercises/Generators/CollatzConjecture.cs +++ b/generators/Exercises/Generators/CollatzConjecture.cs @@ -5,10 +5,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class CollatzConjecture : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Input["number"] <= 0) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Input["number"] <= 0) + testMethod.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index df615c8c23..6f874fb9d2 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -10,43 +10,40 @@ namespace Exercism.CSharp.Exercises.Generators { public class ComplexNumbers : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedClass = "ComplexNumber"; - data.UseVariableForExpected = IsComplexNumber(data.Expected); - data.Expected = ConvertToType(data.Expected); + testMethod.TestedClass = "ComplexNumber"; + testMethod.UseVariableForExpected = IsComplexNumber(testMethod.Expected); + testMethod.Expected = ConvertToType(testMethod.Expected); - var constructorParamName = data.Input.ContainsKey("z") ? "z" : "z1"; - data.Input["real"] = ConvertToDouble(data.Input[constructorParamName][0]); - data.Input["imaginary"] = ConvertToDouble(data.Input[constructorParamName][1]); + var constructorParamName = testMethod.Input.ContainsKey("z") ? "z" : "z1"; + testMethod.Input["real"] = ConvertToDouble(testMethod.Input[constructorParamName][0]); + testMethod.Input["imaginary"] = ConvertToDouble(testMethod.Input[constructorParamName][1]); - data.SetInputParameters(GetInputParameters(data, constructorParamName)); - data.SetConstructorInputParameters("real", "imaginary"); + testMethod.SetInputParameters(GetInputParameters(testMethod, constructorParamName)); + testMethod.SetConstructorInputParameters("real", "imaginary"); - var keys = data.Input.Keys.ToArray(); + var keys = testMethod.Input.Keys.ToArray(); foreach (var key in keys) - data.Input[key] = ConvertToType(data.Input[key]); - } - - private static string[] GetInputParameters(TestData canonicalDataCase, string constructorParamName) - => canonicalDataCase.Input.Keys.Where(x => x != constructorParamName).ToArray(); + testMethod.Input[key] = ConvertToType(testMethod.Input[key]); - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) - => method.Data.UseVariableForExpected - ? RenderComplexNumberAssert(method) - : method.Assert; + private static string[] GetInputParameters(TestMethod testMethod, string constructorParamName) + => testMethod.Input.Keys.Where(x => x != constructorParamName).ToArray(); + + private string RenderAssert(TestMethod testMethod) + => testMethod.UseVariableForExpected + ? RenderComplexNumberAssert(testMethod) + : testMethod.Assert; - private string RenderComplexNumberAssert(TestMethod method) + private string RenderComplexNumberAssert(TestMethod testMethod) { var assert = new StringBuilder(); - assert.AppendLine(Render.AssertEqualWithin($"{method.ExpectedParameter}.Real()", $"{method.TestedValue}.Real()", 15)); - assert.AppendLine(Render.AssertEqualWithin($"{method.ExpectedParameter}.Imaginary()", $"{method.TestedValue}.Imaginary()", 15)); + assert.AppendLine(Render.AssertEqualWithin($"{testMethod.ExpectedParameter}.Real()", $"{testMethod.TestedValue}.Real()", 15)); + assert.AppendLine(Render.AssertEqualWithin($"{testMethod.ExpectedParameter}.Imaginary()", $"{testMethod.TestedValue}.Imaginary()", 15)); return assert.ToString(); } diff --git a/generators/Exercises/Generators/Connect.cs b/generators/Exercises/Generators/Connect.cs index 17cc859d2a..09e5d28b54 100644 --- a/generators/Exercises/Generators/Connect.cs +++ b/generators/Exercises/Generators/Connect.cs @@ -5,24 +5,24 @@ namespace Exercism.CSharp.Exercises.Generators { public class Connect : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForConstructorParameters = true; - data.SetConstructorInputParameters("board"); - data.TestedMethod = "Result"; + testMethod.UseVariablesForConstructorParameters = true; + testMethod.SetConstructorInputParameters("board"); + testMethod.TestedMethod = "Result"; - data.Input["board"] = new UnescapedValue(Render.ArrayMultiLine(data.Input["board"])); + testMethod.Input["board"] = new UnescapedValue(Render.ArrayMultiLine(testMethod.Input["board"])); - switch (data.Expected) + switch (testMethod.Expected) { case "X": - data.Expected = Render.Enum("ConnectWinner", "Black"); + testMethod.Expected = Render.Enum("ConnectWinner", "Black"); break; case "O": - data.Expected = Render.Enum("ConnectWinner", "White"); + testMethod.Expected = Render.Enum("ConnectWinner", "White"); break; case "": - data.Expected = Render.Enum("ConnectWinner", "None"); + testMethod.Expected = Render.Enum("ConnectWinner", "None"); break; } } diff --git a/generators/Exercises/Generators/CryptoSquare.cs b/generators/Exercises/Generators/CryptoSquare.cs index 73b37cd865..f6ccc3fcea 100644 --- a/generators/Exercises/Generators/CryptoSquare.cs +++ b/generators/Exercises/Generators/CryptoSquare.cs @@ -4,10 +4,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class CryptoSquare : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/CustomSet.cs b/generators/Exercises/Generators/CustomSet.cs index 58079ad437..e1f60ea8f5 100644 --- a/generators/Exercises/Generators/CustomSet.cs +++ b/generators/Exercises/Generators/CustomSet.cs @@ -6,36 +6,36 @@ namespace Exercism.CSharp.Exercises.Generators { public class CustomSet : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; + testMethod.UseVariablesForInput = true; - if (data.Input.ContainsKey("set")) + if (testMethod.Input.ContainsKey("set")) { - if (data.Input["set"] is JArray) + if (testMethod.Input["set"] is JArray) { - data.Input["set"] = new UnescapedValue(""); + testMethod.Input["set"] = new UnescapedValue(""); } - data.SetConstructorInputParameters("set"); + testMethod.SetConstructorInputParameters("set"); } else { - if (data.Input["set1"] is JArray) + if (testMethod.Input["set1"] is JArray) { - data.Input["set1"] = new UnescapedValue(""); + testMethod.Input["set1"] = new UnescapedValue(""); } - data.SetConstructorInputParameters("set1"); - data.Input["set2"] = ConvertCustomSet(data.Input["set2"]); + testMethod.SetConstructorInputParameters("set1"); + testMethod.Input["set2"] = ConvertCustomSet(testMethod.Input["set2"]); - if (data.Property == "equal") + if (testMethod.Property == "equal") { - data.TestedMethod = "Equals"; + testMethod.TestedMethod = "Equals"; } } - data.Expected = ConvertCustomSet(data.Expected); + testMethod.Expected = ConvertCustomSet(testMethod.Expected); } private dynamic ConvertCustomSet(dynamic value) diff --git a/generators/Exercises/Generators/DifferenceOfSquares.cs b/generators/Exercises/Generators/DifferenceOfSquares.cs index 1434168b7c..329a79f65f 100644 --- a/generators/Exercises/Generators/DifferenceOfSquares.cs +++ b/generators/Exercises/Generators/DifferenceOfSquares.cs @@ -4,9 +4,9 @@ namespace Exercism.CSharp.Exercises.Generators { public class DifferenceOfSquares : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = $"Calculate{data.TestedMethod}"; + testMethod.TestedMethod = $"Calculate{testMethod.TestedMethod}"; } } } diff --git a/generators/Exercises/Generators/Dominoes.cs b/generators/Exercises/Generators/Dominoes.cs index d983be42aa..3ec57b950e 100644 --- a/generators/Exercises/Generators/Dominoes.cs +++ b/generators/Exercises/Generators/Dominoes.cs @@ -8,10 +8,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class Dominoes : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.Input["dominoes"] = ConvertDominoes(data.Input["dominoes"]); + testMethod.UseVariablesForInput = true; + testMethod.Input["dominoes"] = ConvertDominoes(testMethod.Input["dominoes"]); } private static ValueTuple[] ConvertDominoes(JToken input) diff --git a/generators/Exercises/Generators/Etl.cs b/generators/Exercises/Generators/Etl.cs index 2456fab05c..db1863000b 100644 --- a/generators/Exercises/Generators/Etl.cs +++ b/generators/Exercises/Generators/Etl.cs @@ -7,13 +7,13 @@ namespace Exercism.CSharp.Exercises.Generators { public class Etl : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; - data.Input = ConvertInput(data.Input); - data.Expected = ConvertExpected(data.Expected); - data.SetInputParameters("input"); + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; + testMethod.Input = ConvertInput(testMethod.Input); + testMethod.Expected = ConvertExpected(testMethod.Expected); + testMethod.SetInputParameters("input"); } private static dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/Generators/FlattenArray.cs b/generators/Exercises/Generators/FlattenArray.cs index f67a75f556..4a26f0f4ff 100644 --- a/generators/Exercises/Generators/FlattenArray.cs +++ b/generators/Exercises/Generators/FlattenArray.cs @@ -5,18 +5,18 @@ namespace Exercism.CSharp.Exercises.Generators { public class FlattenArray : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; - var stringInput = data.Input["array"].ToString(); + var stringInput = testMethod.Input["array"].ToString(); // We skip rendering of pure int arrays. if (stringInput.Contains("System.Int32")) return; - data.Input["array"] = new UnescapedValue(ConvertToObjectArray(stringInput)); + testMethod.Input["array"] = new UnescapedValue(ConvertToObjectArray(stringInput)); } private static string ConvertToObjectArray(string input) diff --git a/generators/Exercises/Generators/FoodChain.cs b/generators/Exercises/Generators/FoodChain.cs index eb6acb6a0b..a3e93cc46b 100644 --- a/generators/Exercises/Generators/FoodChain.cs +++ b/generators/Exercises/Generators/FoodChain.cs @@ -5,14 +5,14 @@ namespace Exercism.CSharp.Exercises.Generators { public class FoodChain : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.Expected = new MultiLineString(data.Expected); - data.UseVariableForExpected = true; + testMethod.Expected = new MultiLineString(testMethod.Expected); + testMethod.UseVariableForExpected = true; - if (data.Input["startVerse"] == data.Input["endVerse"]) + if (testMethod.Input["startVerse"] == testMethod.Input["endVerse"]) { - data.SetInputParameters("startVerse"); + testMethod.SetInputParameters("startVerse"); } } } diff --git a/generators/Exercises/Generators/Forth.cs b/generators/Exercises/Generators/Forth.cs index e88812958e..d1994c0b39 100644 --- a/generators/Exercises/Generators/Forth.cs +++ b/generators/Exercises/Generators/Forth.cs @@ -5,17 +5,17 @@ namespace Exercism.CSharp.Exercises.Generators { public class Forth : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseFullDescriptionPath = true; + testMethod.TestMethodName = testMethod.TestMethodNameWithPath; - if (data.Expected == null) + if (testMethod.Expected == null) { - data.ExceptionThrown = typeof(InvalidOperationException); + testMethod.ExceptionThrown = typeof(InvalidOperationException); } else { - data.Expected = string.Join(" ", data.Expected); + testMethod.Expected = string.Join(" ", testMethod.Expected); } } } diff --git a/generators/Exercises/Generators/Gigasecond.cs b/generators/Exercises/Generators/Gigasecond.cs index fb91af342d..d329460901 100644 --- a/generators/Exercises/Generators/Gigasecond.cs +++ b/generators/Exercises/Generators/Gigasecond.cs @@ -7,11 +7,11 @@ namespace Exercism.CSharp.Exercises.Generators { public class Gigasecond : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - var input = DateTime.Parse(data.Input["birthdate"].ToString()); - data.Input["birthdate"] = new UnescapedValue(RenderDateTime(input)); - data.Expected = new UnescapedValue(RenderDateTime((DateTime)data.Expected)); + var input = DateTime.Parse(testMethod.Input["birthdate"].ToString()); + testMethod.Input["birthdate"] = new UnescapedValue(RenderDateTime(input)); + testMethod.Expected = new UnescapedValue(RenderDateTime((DateTime)testMethod.Expected)); } private static string RenderDateTime(DateTime dateTime) diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index 4c5714a7e7..0a207c0966 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -10,61 +10,58 @@ namespace Exercism.CSharp.Exercises.Generators { public class GoCounting : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; - data.UseVariablesForConstructorParameters = true; - data.UseVariableForTested = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; + testMethod.UseVariablesForConstructorParameters = true; + testMethod.UseVariableForTested = true; - data.Input["board"] = new MultiLineString(data.Input["board"]); - data.SetConstructorInputParameters("board"); + testMethod.Input["board"] = new MultiLineString(testMethod.Input["board"]); + testMethod.SetConstructorInputParameters("board"); - if (data.Property == "territory") + if (testMethod.Property == "territory") { - data.Input["coordinate"] = (data.Input["x"], data.Input["y"]); - data.SetInputParameters("coordinate"); + testMethod.Input["coordinate"] = (testMethod.Input["x"], testMethod.Input["y"]); + testMethod.SetInputParameters("coordinate"); - if (data.Expected.ContainsKey("error")) + if (testMethod.Expected.ContainsKey("error")) { - data.ExceptionThrown = typeof(ArgumentException); + testMethod.ExceptionThrown = typeof(ArgumentException); } else { - var owner = RenderOwner(data.Expected["owner"]); - var territory = RenderTerritory(data.Expected["territory"]); - data.Expected = (owner, territory); + var owner = RenderOwner(testMethod.Expected["owner"]); + var territory = RenderTerritory(testMethod.Expected["territory"]); + testMethod.Expected = (owner, territory); } } else { var expected = new[] { - "new Dictionary[]>", + "new Dictionary", "{", - $" [Owner.Black] = {RenderTerritory(data.Expected["territoryBlack"])},", - $" [Owner.White] = {RenderTerritory(data.Expected["territoryWhite"])},", - $" [Owner.None] = {RenderTerritory(data.Expected["territoryNone"])}", + $" [Owner.Black] = {RenderTerritory(testMethod.Expected["territoryBlack"])},", + $" [Owner.White] = {RenderTerritory(testMethod.Expected["territoryWhite"])},", + $" [Owner.None] = {RenderTerritory(testMethod.Expected["territoryNone"])}", "}" }; - data.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); + testMethod.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); } - } - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { - if (method.Data.ExceptionThrown != null) + if (testMethod.ExceptionThrown != null) { - return method.Assert; + return testMethod.Assert; } - if (method.Data.Property == "territories") + if (testMethod.Property == "territories") { var territoriesAssert = new StringBuilder(); territoriesAssert.AppendLine(Render.AssertEqual("expected.Keys", "actual.Keys")); diff --git a/generators/Exercises/Generators/Grains.cs b/generators/Exercises/Generators/Grains.cs index 758ba2f3ce..4477a12d8b 100644 --- a/generators/Exercises/Generators/Grains.cs +++ b/generators/Exercises/Generators/Grains.cs @@ -5,12 +5,12 @@ namespace Exercism.CSharp.Exercises.Generators { public class Grains : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Expected is int i && i == -1) - data.ExceptionThrown = typeof(ArgumentOutOfRangeException); + if (testMethod.Expected is int i && i == -1) + testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); else - data.Expected = (ulong)data.Expected; + testMethod.Expected = (ulong)testMethod.Expected; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Grep.cs b/generators/Exercises/Generators/Grep.cs index 641852f107..4ce1f5ff8d 100644 --- a/generators/Exercises/Generators/Grep.cs +++ b/generators/Exercises/Generators/Grep.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; @@ -10,37 +8,37 @@ namespace Exercism.CSharp.Exercises.Generators { public class Grep : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = "Match"; - data.Input["flags"] = string.Join(" ", data.Input["flags"]); - data.Expected = ConvertExpected(data.Expected); - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; + testMethod.TestedMethod = "Match"; + testMethod.Input["flags"] = string.Join(" ", testMethod.Input["flags"]); + testMethod.Expected = ConvertExpected(testMethod.Expected); + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; } private static MultiLineString ConvertExpected(dynamic expected) => new MultiLineString(expected as string[] ?? Array.Empty()); - protected override void UpdateTestClass(TestClass @class) + protected override void UpdateTestClass(TestClass testClass) { - @class.IsDisposable = true; + testClass.IsDisposable = true; - AddAdditionalMethods(@class); + AddAdditionalMethods(testClass); } - private static void AddAdditionalMethods(TestClass @class) + private static void AddAdditionalMethods(TestClass testClass) { - AddIliadData(@class); - AddMidsummerNightData(@class); - AddParadiseLostData(@class); - AddConstructor(@class); - AddDisposeMethod(@class); + AddIliadData(testClass); + AddMidsummerNightData(testClass); + AddParadiseLostData(testClass); + AddConstructor(testClass); + AddDisposeMethod(testClass); } - private static void AddIliadData(TestClass @class) + private static void AddIliadData(TestClass testClass) { - @class.Methods.Add(@" + testClass.Methods.Add(@" private const string IliadFileName = ""iliad.txt""; private const string IliadContents = ""Achilles sing, O Goddess! Peleus' son;\n"" + @@ -54,9 +52,9 @@ private static void AddIliadData(TestClass @class) ""Of Atreus, Agamemnon, King of men.\n"";"); } - private static void AddMidsummerNightData(TestClass @class) + private static void AddMidsummerNightData(TestClass testClass) { - @class.Methods.Add(@" + testClass.Methods.Add(@" private const string MidsummerNightFileName = ""midsummer-night.txt""; private const string MidsummerNightContents = ""I do entreat your grace to pardon me.\n"" + @@ -68,9 +66,9 @@ private static void AddMidsummerNightData(TestClass @class) ""If I refuse to wed Demetrius.\n"";"); } - private static void AddParadiseLostData(TestClass @class) + private static void AddParadiseLostData(TestClass testClass) { - @class.Methods.Add(@" + testClass.Methods.Add(@" private const string ParadiseLostFileName = ""paradise-lost.txt""; private const string ParadiseLostContents = ""Of Mans First Disobedience, and the Fruit\n"" + @@ -83,9 +81,9 @@ private static void AddParadiseLostData(TestClass @class) ""That Shepherd, who first taught the chosen Seed\n"";"); } - private static void AddConstructor(TestClass @class) + private static void AddConstructor(TestClass testClass) { - @class.Methods.Add(@" + testClass.Methods.Add(@" public GrepTest() { Directory.SetCurrentDirectory(Path.GetTempPath()); @@ -95,9 +93,9 @@ public GrepTest() }"); } - private static void AddDisposeMethod(TestClass @class) + private static void AddDisposeMethod(TestClass testClass) { - @class.Methods.Add(@" + testClass.Methods.Add(@" public void Dispose() { Directory.SetCurrentDirectory(Path.GetTempPath()); diff --git a/generators/Exercises/Generators/Hamming.cs b/generators/Exercises/Generators/Hamming.cs index 4d896e31a8..8bae530c29 100644 --- a/generators/Exercises/Generators/Hamming.cs +++ b/generators/Exercises/Generators/Hamming.cs @@ -5,10 +5,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class Hamming : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (!(data.Expected is int)) - data.ExceptionThrown = typeof(ArgumentException); + if (!(testMethod.Expected is int)) + testMethod.ExceptionThrown = typeof(ArgumentException); } } } diff --git a/generators/Exercises/Generators/House.cs b/generators/Exercises/Generators/House.cs index 738e1d21bb..5442f8232e 100644 --- a/generators/Exercises/Generators/House.cs +++ b/generators/Exercises/Generators/House.cs @@ -5,14 +5,14 @@ namespace Exercism.CSharp.Exercises.Generators { public class House : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; - data.Expected = new MultiLineString(data.Expected); + testMethod.UseVariableForExpected = true; + testMethod.Expected = new MultiLineString(testMethod.Expected); - if (data.Input["startVerse"] == data.Input["endVerse"]) + if (testMethod.Input["startVerse"] == testMethod.Input["endVerse"]) { - data.SetInputParameters("startVerse"); + testMethod.SetInputParameters("startVerse"); } } } diff --git a/generators/Exercises/Generators/KindergartenGarden.cs b/generators/Exercises/Generators/KindergartenGarden.cs index d48c59b7fe..d6d5785c29 100644 --- a/generators/Exercises/Generators/KindergartenGarden.cs +++ b/generators/Exercises/Generators/KindergartenGarden.cs @@ -7,17 +7,17 @@ namespace Exercism.CSharp.Exercises.Generators { public class KindergartenGarden : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethodType = TestedMethodType.Instance; - data.UseFullDescriptionPath = true; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + testMethod.TestMethodName = testMethod.TestMethodNameWithPath; - if (data.Input.ContainsKey("students")) - data.SetConstructorInputParameters("diagram", "students"); + if (testMethod.Input.ContainsKey("students")) + testMethod.SetConstructorInputParameters("diagram", "students"); else - data.SetConstructorInputParameters("diagram"); + testMethod.SetConstructorInputParameters("diagram"); - data.Expected = ConvertExpected(data.Expected); + testMethod.Expected = ConvertExpected(testMethod.Expected); } private UnescapedValue[] ConvertExpected(IEnumerable plants) diff --git a/generators/Exercises/Generators/LargestSeriesProduct.cs b/generators/Exercises/Generators/LargestSeriesProduct.cs index ee46158d5f..3334f0bcf6 100644 --- a/generators/Exercises/Generators/LargestSeriesProduct.cs +++ b/generators/Exercises/Generators/LargestSeriesProduct.cs @@ -5,12 +5,12 @@ namespace Exercism.CSharp.Exercises.Generators { public class LargestSeriesProduct : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = "GetLargestProduct"; + testMethod.TestedMethod = "GetLargestProduct"; - if (data.Expected == -1) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Expected == -1) + testMethod.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Leap.cs b/generators/Exercises/Generators/Leap.cs index 1a37da5ef8..bd54a614c2 100644 --- a/generators/Exercises/Generators/Leap.cs +++ b/generators/Exercises/Generators/Leap.cs @@ -4,9 +4,9 @@ namespace Exercism.CSharp.Exercises.Generators { public class Leap : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = "IsLeapYear"; + testMethod.TestedMethod = "IsLeapYear"; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ListOps.cs b/generators/Exercises/Generators/ListOps.cs index b6e39aaa59..569034e17b 100644 --- a/generators/Exercises/Generators/ListOps.cs +++ b/generators/Exercises/Generators/ListOps.cs @@ -10,30 +10,30 @@ namespace Exercism.CSharp.Exercises.Generators { public class ListOps : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseFullDescriptionPath = true; - data.UseVariablesForInput = true; - data.UseVariableForExpected = !(data.Expected is int); + testMethod.TestMethodName = testMethod.TestMethodNameWithPath; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = !(testMethod.Expected is int); - if (data.Input.TryGetValue("list", out var list)) - data.Input["list"] = ConvertToList(list); + if (testMethod.Input.TryGetValue("list", out var list)) + testMethod.Input["list"] = ConvertToList(list); - if (data.Input.TryGetValue("list1", out var list1)) - data.Input["list1"] = ConvertToList(list1); + if (testMethod.Input.TryGetValue("list1", out var list1)) + testMethod.Input["list1"] = ConvertToList(list1); - if (data.Input.TryGetValue("list2", out var list2)) - data.Input["list2"] = ConvertToList(list2); + if (testMethod.Input.TryGetValue("list2", out var list2)) + testMethod.Input["list2"] = ConvertToList(list2); - if (data.Input.TryGetValue("lists", out var lists)) - data.Input["lists"] = ConvertToNestedList(lists); + if (testMethod.Input.TryGetValue("lists", out var lists)) + testMethod.Input["lists"] = ConvertToNestedList(lists); - if (data.Input.TryGetValue("function", out var function)) - data.Input["function"] = ConvertToFunction(data.Property, function); + if (testMethod.Input.TryGetValue("function", out var function)) + testMethod.Input["function"] = ConvertToFunction(testMethod.Property, function); - if (data.Expected is IEnumerable) + if (testMethod.Expected is IEnumerable) { - data.Expected = ConvertToList(data.Expected); + testMethod.Expected = ConvertToList(testMethod.Expected); } } diff --git a/generators/Exercises/Generators/Luhn.cs b/generators/Exercises/Generators/Luhn.cs index 124e032e66..4f2d19e1d9 100644 --- a/generators/Exercises/Generators/Luhn.cs +++ b/generators/Exercises/Generators/Luhn.cs @@ -4,9 +4,9 @@ namespace Exercism.CSharp.Exercises.Generators { public class Luhn : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = "IsValid"; + testMethod.TestedMethod = "IsValid"; } } } diff --git a/generators/Exercises/Generators/Markdown.cs b/generators/Exercises/Generators/Markdown.cs index 53aa1b3734..2ccda69322 100644 --- a/generators/Exercises/Generators/Markdown.cs +++ b/generators/Exercises/Generators/Markdown.cs @@ -5,12 +5,12 @@ namespace Exercism.CSharp.Exercises.Generators { public class Markdown : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; - data.Input["markdown"] = new MultiLineString(data.Input["markdown"]); - data.Skip = false; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; + testMethod.Input["markdown"] = new MultiLineString(testMethod.Input["markdown"]); + testMethod.Skip = false; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Matrix.cs b/generators/Exercises/Generators/Matrix.cs index dcc89b57b3..16357039e3 100644 --- a/generators/Exercises/Generators/Matrix.cs +++ b/generators/Exercises/Generators/Matrix.cs @@ -4,10 +4,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class Matrix : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.SetConstructorInputParameters("string"); - data.SetInputParameters("index"); + testMethod.SetConstructorInputParameters("string"); + testMethod.SetInputParameters("index"); } } } diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index 1df8779188..c488431bc0 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -13,26 +13,23 @@ public class Meetup : GeneratorExercise private const string PropertyDay = "Day"; - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = PropertyDay; - data.UseVariableForExpected = true; - data.SetConstructorInputParameters(ParamMonth, ParamYear); - data.SetInputParameters(ParamDayOfWeek, ParamWeek); + testMethod.TestedMethod = PropertyDay; + testMethod.UseVariableForExpected = true; + testMethod.SetConstructorInputParameters(ParamMonth, ParamYear); + testMethod.SetInputParameters(ParamDayOfWeek, ParamWeek); - data.Input[ParamYear] = data.Input[ParamYear]; - data.Input[ParamMonth] = data.Input[ParamMonth]; - data.Input[ParamWeek] = Render.Enum("Schedule", data.Input[ParamWeek]); - data.Input[ParamDayOfWeek] = Render.Enum("DayOfWeek", data.Input[ParamDayOfWeek]); - } + testMethod.Input[ParamYear] = testMethod.Input[ParamYear]; + testMethod.Input[ParamMonth] = testMethod.Input[ParamMonth]; + testMethod.Input[ParamWeek] = Render.Enum("Schedule", testMethod.Input[ParamWeek]); + testMethod.Input[ParamDayOfWeek] = Render.Enum("DayOfWeek", testMethod.Input[ParamDayOfWeek]); - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) - => Render.AssertEqual(method.ExpectedParameter, $"{method.TestedValue}.ToString(\"yyyy-MM-dd\")"); + private string RenderAssert(TestMethod testMethod) + => Render.AssertEqual(testMethod.ExpectedParameter, $"{testMethod.TestedValue}.ToString(\"yyyy-MM-dd\")"); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/Minesweeper.cs b/generators/Exercises/Generators/Minesweeper.cs index 876b5acf80..828e88780e 100644 --- a/generators/Exercises/Generators/Minesweeper.cs +++ b/generators/Exercises/Generators/Minesweeper.cs @@ -8,15 +8,15 @@ namespace Exercism.CSharp.Exercises.Generators { public class Minesweeper : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; - if (data.Input["minefield"] is JArray) - data.Input["minefield"] = Array.Empty(); + if (testMethod.Input["minefield"] is JArray) + testMethod.Input["minefield"] = Array.Empty(); - data.Input["minefield"] = new UnescapedValue(Render.ArrayMultiLine(data.Input["minefield"])); + testMethod.Input["minefield"] = new UnescapedValue(Render.ArrayMultiLine(testMethod.Input["minefield"])); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/NthPrime.cs b/generators/Exercises/Generators/NthPrime.cs index 6295abd340..e3c68d17ed 100644 --- a/generators/Exercises/Generators/NthPrime.cs +++ b/generators/Exercises/Generators/NthPrime.cs @@ -6,10 +6,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class NthPrime : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Expected is Dictionary) - data.ExceptionThrown = typeof(ArgumentOutOfRangeException); + if (testMethod.Expected is Dictionary) + testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index ed93de0eaa..28b027f277 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -7,14 +7,21 @@ namespace Exercism.CSharp.Exercises.Generators { public class NucleotideCount : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Expected.ContainsKey("error")) - return; - - data.UseVariableForExpected = true; - data.SetConstructorInputParameters("strand"); - data.Expected = ConvertExpected(data.Expected); + if (testMethod.Expected.ContainsKey("error")) + { + testMethod.ExceptionThrown = typeof(ArgumentException); + testMethod.TestedMethodType = TestedMethodType.Constructor; + } + else + { + testMethod.Expected = ConvertExpected(testMethod.Expected); + testMethod.TestedMethodType = TestedMethodType.Property; + } + + testMethod.UseVariableForExpected = true; + testMethod.SetConstructorInputParameters("strand"); } private static dynamic ConvertExpected(dynamic expected) @@ -25,24 +32,5 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(ArgumentException).Namespace); namespaces.Add(typeof(Dictionary).Namespace); } - - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); - } - - private string RenderAssert(TestMethod method) - => method.Data.UseVariableForExpected - ? RenderEqualAssert(method) - : RenderThrowsAssert(method); - - private string RenderEqualAssert(TestMethod method) - => Render.AssertEqual("expected", $"sut.{method.Data.TestedMethod}"); - - private string RenderThrowsAssert(TestMethod method) - { - var strand = Render.Object(method.Data.Input["strand"]); - return Render.AssertThrows($"new NucleotideCount({strand})"); - } } } diff --git a/generators/Exercises/Generators/OcrNumbers.cs b/generators/Exercises/Generators/OcrNumbers.cs index 1aeee6603e..05f6940a37 100644 --- a/generators/Exercises/Generators/OcrNumbers.cs +++ b/generators/Exercises/Generators/OcrNumbers.cs @@ -7,15 +7,15 @@ namespace Exercism.CSharp.Exercises.Generators { public class OcrNumbers : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Expected is int i && i <= 0) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Expected is int i && i <= 0) + testMethod.ExceptionThrown = typeof(ArgumentException); - data.Input["rows"] = new MultiLineString(data.Input["rows"]); - data.Expected = data.Expected.ToString(); - data.UseVariableForTested = true; - data.UseVariablesForInput = true; + testMethod.Input["rows"] = new MultiLineString(testMethod.Input["rows"]); + testMethod.Expected = testMethod.Expected.ToString(); + testMethod.UseVariableForTested = true; + testMethod.UseVariablesForInput = true; } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index 60d617d530..098574e618 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -8,30 +8,27 @@ namespace Exercism.CSharp.Exercises.Generators { public class PalindromeProducts : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Expected.ContainsKey("error")) + if (testMethod.Expected.ContainsKey("error")) { - data.ExceptionThrown = typeof(ArgumentException); + testMethod.ExceptionThrown = typeof(ArgumentException); } else { - data.UseVariableForTested = true; - data.UseVariableForExpected = true; - data.Expected = (data.Expected["value"], RenderCoordinates(data.Expected["factors"])); + testMethod.UseVariableForTested = true; + testMethod.UseVariableForExpected = true; + testMethod.Expected = (testMethod.Expected["value"], RenderCoordinates(testMethod.Expected["factors"])); } - } - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { - if (method.Data.ExceptionThrown != null) + if (testMethod.ExceptionThrown != null) { - return method.Assert; + return testMethod.Assert; } var assert = new StringBuilder(); diff --git a/generators/Exercises/Generators/PascalsTriangle.cs b/generators/Exercises/Generators/PascalsTriangle.cs index 20ad61e651..b2d1d7a6b0 100644 --- a/generators/Exercises/Generators/PascalsTriangle.cs +++ b/generators/Exercises/Generators/PascalsTriangle.cs @@ -6,14 +6,14 @@ namespace Exercism.CSharp.Exercises.Generators { public class PascalsTriangle : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; - data.TestedMethod = "Calculate"; - if (data.Expected is JArray jArray) - data.Expected = jArray.ToObject(); + testMethod.UseVariableForExpected = true; + testMethod.TestedMethod = "Calculate"; + if (testMethod.Expected is JArray jArray) + testMethod.Expected = jArray.ToObject(); else - data.ExceptionThrown = typeof(ArgumentOutOfRangeException); + testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/PerfectNumbers.cs b/generators/Exercises/Generators/PerfectNumbers.cs index d61f27404e..69faa4d08d 100644 --- a/generators/Exercises/Generators/PerfectNumbers.cs +++ b/generators/Exercises/Generators/PerfectNumbers.cs @@ -5,12 +5,12 @@ namespace Exercism.CSharp.Exercises.Generators { public class PerfectNumbers : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Expected is string) - data.Expected = Render.Enum("Classification", data.Expected); + if (testMethod.Expected is string) + testMethod.Expected = Render.Enum("Classification", testMethod.Expected); else - data.ExceptionThrown = typeof(ArgumentOutOfRangeException); + testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/PhoneNumber.cs b/generators/Exercises/Generators/PhoneNumber.cs index de1cc4d747..2db4a12112 100644 --- a/generators/Exercises/Generators/PhoneNumber.cs +++ b/generators/Exercises/Generators/PhoneNumber.cs @@ -5,12 +5,12 @@ namespace Exercism.CSharp.Exercises.Generators { public class PhoneNumber : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; + testMethod.UseVariablesForInput = true; - if (data.Expected is null) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Expected is null) + testMethod.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Poker.cs b/generators/Exercises/Generators/Poker.cs index 3460574e7b..e37889f90d 100644 --- a/generators/Exercises/Generators/Poker.cs +++ b/generators/Exercises/Generators/Poker.cs @@ -4,11 +4,11 @@ namespace Exercism.CSharp.Exercises.Generators { public class Poker : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; - data.UseVariableForTested = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; + testMethod.UseVariableForTested = true; } } } diff --git a/generators/Exercises/Generators/Pov.cs b/generators/Exercises/Generators/Pov.cs index d2b8533789..8c4660202d 100644 --- a/generators/Exercises/Generators/Pov.cs +++ b/generators/Exercises/Generators/Pov.cs @@ -7,19 +7,19 @@ namespace Exercism.CSharp.Exercises.Generators { public class Pov : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; - if (data.Expected is null) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Expected is null) + testMethod.ExceptionThrown = typeof(ArgumentException); - data.Input["tree"] = RenderTree(data.Input["tree"]); + testMethod.Input["tree"] = RenderTree(testMethod.Input["tree"]); - if (data.Property == "fromPov") + if (testMethod.Property == "fromPov") { - data.Expected = RenderTree(data.Expected); + testMethod.Expected = RenderTree(testMethod.Expected); } } diff --git a/generators/Exercises/Generators/Proverb.cs b/generators/Exercises/Generators/Proverb.cs index 25f70629fa..a71e197189 100644 --- a/generators/Exercises/Generators/Proverb.cs +++ b/generators/Exercises/Generators/Proverb.cs @@ -7,15 +7,15 @@ namespace Exercism.CSharp.Exercises.Generators { public class Proverb : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; + testMethod.UseVariableForExpected = true; - if (data.Input["strings"] is JArray) - data.Input["strings"] = Array.Empty(); + if (testMethod.Input["strings"] is JArray) + testMethod.Input["strings"] = Array.Empty(); - if (data.Expected is JArray) - data.Expected = Array.Empty(); + if (testMethod.Expected is JArray) + testMethod.Expected = Array.Empty(); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index c5e9a0a253..ad8becd1e6 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -1,59 +1,50 @@ using System; using System.Collections.Generic; -using System.Text; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { public class QueenAttack : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Property != "create") + if (testMethod.Property == "create") + { + if (testMethod.Expected < 0) + { + testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); + } + else + { + testMethod.UseVariableForTested = true; + testMethod.Assert = string.Empty; + } + + var coordinates = GetCoordinatesFromPosition(testMethod.Input["queen"]); + testMethod.Input["X"] = coordinates.Item1; + testMethod.Input["Y"] = coordinates.Item2; + + testMethod.SetInputParameters("X", "Y"); + return; - - if (data.Expected < 0) - data.ExceptionThrown = typeof(ArgumentOutOfRangeException); - - data.UseVariableForTested = true; - - var coordinates = GetCoordinatesFromPosition(data.Input["queen"]); - data.Input["X"] = coordinates.Item1; - data.Input["Y"] = coordinates.Item2; - - data.SetInputParameters("X", "Y"); + } + + if (testMethod.Property == "canAttack") + { + testMethod.UseVariablesForInput = true; + testMethod.Input["white_queen"] = RenderQueen(testMethod.Input["white_queen"]); + testMethod.Input["black_queen"] = RenderQueen(testMethod.Input["black_queen"]); + } } - - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); - } - - private string RenderAssert(TestMethod method) + + private static UnescapedValue RenderQueen(dynamic input) { - if (method.Data.Property == "canAttack") - return RenderCanAttackAssert(method); - - return method.Data.UseVariableForTested - ? string.Empty - : method.Assert; - } - - private string RenderCanAttackAssert(TestMethod method) - { - var assert = new StringBuilder(); - - var (whiteQueenX, whiteQueenY) = GetCoordinatesFromPosition((IDictionary)method.Data.Input["white_queen"]); - var (blackQueenX, blackQueenY) = GetCoordinatesFromPosition((IDictionary)method.Data.Input["black_queen"]); - - assert.AppendLine(Render.Variable("whiteQueen", $"QueenAttack.Create({whiteQueenX},{whiteQueenY})")); - assert.AppendLine(Render.Variable("blackQueen", $"QueenAttack.Create({blackQueenX},{blackQueenY})")); - assert.AppendLine(Render.AssertBoolean((bool)method.Data.Expected, "QueenAttack.CanAttack(whiteQueen, blackQueen)")); - - return assert.ToString(); + var (x, y) = GetCoordinatesFromPosition((IDictionary)input); + return new UnescapedValue($"QueenAttack.Create({x},{y})"); } - private static ValueTuple GetCoordinatesFromPosition(IDictionary expected) + private static (int, int) GetCoordinatesFromPosition(IDictionary expected) { var coordinates = expected["position"]; var positionX = (int)coordinates["row"]; diff --git a/generators/Exercises/Generators/RailFenceCipher.cs b/generators/Exercises/Generators/RailFenceCipher.cs index c1fbcbb068..c281b4fc2c 100644 --- a/generators/Exercises/Generators/RailFenceCipher.cs +++ b/generators/Exercises/Generators/RailFenceCipher.cs @@ -4,11 +4,11 @@ namespace Exercism.CSharp.Exercises.Generators { public class RailFenceCipher : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; - data.SetConstructorInputParameters("rails"); + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; + testMethod.SetConstructorInputParameters("rails"); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index 9a399014a6..114664878a 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -6,29 +6,29 @@ namespace Exercism.CSharp.Exercises.Generators { public class RationalNumbers : GeneratorExercise { - protected override void UpdateTestMethod(TestMethod method) + protected override void UpdateTestMethod(TestMethod testMethod) { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { - switch (method.Data.Property) + switch (testMethod.Property) { case "add": case "sub": case "mul": case "div": const string operationsWithOverloading = "add|+|sub|-|mul|*|div|/"; - var operationCode = operationsWithOverloading.Substring(operationsWithOverloading.IndexOf(method.Data.Property, StringComparison.OrdinalIgnoreCase) + 4, 1); - return Render.AssertEqual(RenderRationalNumber(method.Data.Expected), $"{RenderRationalNumber(method.Data.Input["r1"])} {operationCode} ({RenderRationalNumber(method.Data.Input["r2"])})"); + var operationCode = operationsWithOverloading.Substring(operationsWithOverloading.IndexOf(testMethod.Property, StringComparison.OrdinalIgnoreCase) + 4, 1); + return Render.AssertEqual(RenderRationalNumber(testMethod.Expected), $"{RenderRationalNumber(testMethod.Input["r1"])} {operationCode} ({RenderRationalNumber(testMethod.Input["r2"])})"); case "abs": case "reduce": - return Render.AssertEqual(RenderRationalNumber(method.Data.Expected), $"{RenderRationalNumber(method.Data.Input["r"])}.{method.Data.TestedMethod}()"); + return Render.AssertEqual(RenderRationalNumber(testMethod.Expected), $"{RenderRationalNumber(testMethod.Input["r"])}.{testMethod.TestedMethod}()"); case "exprational": - return Render.AssertEqual(RenderRationalNumber(method.Data.Expected), $"{RenderRationalNumber(method.Data.Input["r"])}.{method.Data.TestedMethod}({method.Data.Input["n"]})"); + return Render.AssertEqual(RenderRationalNumber(testMethod.Expected), $"{RenderRationalNumber(testMethod.Input["r"])}.{testMethod.TestedMethod}({testMethod.Input["n"]})"); case "expreal": - return Render.AssertEqual(method.ExpectedParameter, $"{method.Data.Input["x"]}.{method.Data.TestedMethod}({RenderRationalNumber(method.Data.Input["r"])}), {Precision(method.Data.Expected)}"); + return Render.AssertEqual(testMethod.ExpectedParameter, $"{testMethod.Input["x"]}.{testMethod.TestedMethod}({RenderRationalNumber(testMethod.Input["r"])}), {Precision(testMethod.Expected)}"); default: throw new ArgumentOutOfRangeException(); } diff --git a/generators/Exercises/Generators/React.cs b/generators/Exercises/Generators/React.cs index 0041680882..8a1c368531 100644 --- a/generators/Exercises/Generators/React.cs +++ b/generators/Exercises/Generators/React.cs @@ -10,21 +10,21 @@ namespace Exercism.CSharp.Exercises.Generators { public class React : GeneratorExercise { - protected override void UpdateTestMethod(TestMethod method) + protected override void UpdateTestMethod(TestMethod testMethod) { - method.Arrange = RenderArrange(method); - method.Assert = RenderAssert(); + testMethod.Arrange = RenderArrange(testMethod); + testMethod.Assert = RenderAssert(); } - private string RenderArrange(TestMethod method) + private string RenderArrange(TestMethod testMethod) { var arrange = new StringBuilder(); arrange.AppendLine(Render.Variable("sut", "new Reactor()")); - var cells = RenderCells(method.Data.Input["cells"]); + var cells = RenderCells(testMethod.Input["cells"]); arrange.AppendLine(cells); - var operations = RenderOperations(method.Data.Input["operations"]); + var operations = RenderOperations(testMethod.Input["operations"]); arrange.AppendLine(operations); return arrange.ToString(); diff --git a/generators/Exercises/Generators/Rectangles.cs b/generators/Exercises/Generators/Rectangles.cs index 444c25b283..79ab0c80df 100644 --- a/generators/Exercises/Generators/Rectangles.cs +++ b/generators/Exercises/Generators/Rectangles.cs @@ -8,15 +8,15 @@ namespace Exercism.CSharp.Exercises.Generators { public class Rectangles : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.TestedMethod = "Count"; + testMethod.UseVariablesForInput = true; + testMethod.TestedMethod = "Count"; - if (data.Input["strings"] is JArray) - data.Input["strings"] = Array.Empty(); + if (testMethod.Input["strings"] is JArray) + testMethod.Input["strings"] = Array.Empty(); - data.Input["strings"] = new UnescapedValue(Render.ArrayMultiLine(data.Input["strings"])); + testMethod.Input["strings"] = new UnescapedValue(Render.ArrayMultiLine(testMethod.Input["strings"])); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/RnaTranscription.cs b/generators/Exercises/Generators/RnaTranscription.cs index f150293ede..0ebf602ff9 100644 --- a/generators/Exercises/Generators/RnaTranscription.cs +++ b/generators/Exercises/Generators/RnaTranscription.cs @@ -5,10 +5,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class RnaTranscription : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Expected is null) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Expected is null) + testMethod.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs index 0575bb1fe4..6440ef186d 100644 --- a/generators/Exercises/Generators/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -7,43 +7,40 @@ namespace Exercism.CSharp.Exercises.Generators { public class RobotSimulator : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.Input["direction"] = RenderDirection(data.Input["direction"]); - data.Input["coordinate"] = RenderCreateCoordinate(data.Input["position"]); + testMethod.Input["direction"] = RenderDirection(testMethod.Input["direction"]); + testMethod.Input["coordinate"] = RenderCreateCoordinate(testMethod.Input["position"]); - data.SetConstructorInputParameters("direction", "coordinate"); + testMethod.SetConstructorInputParameters("direction", "coordinate"); - data.UseFullDescriptionPath = true; - } + testMethod.TestMethodName = testMethod.TestMethodNameWithPath; - protected override void UpdateTestMethod(TestMethod method) - { - method.Act = RenderAct(method); - method.Assert = RenderAssert(method); + testMethod.Act = RenderAct(testMethod); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAct(TestMethod method) + private string RenderAct(TestMethod testMethod) { - switch (method.Data.Property) + switch (testMethod.Property) { case "create": return null; - case "instructions": return RenderInstructionsAct(method); - default: return RenderDefaultAct(method); + case "instructions": return RenderInstructionsAct(testMethod); + default: return RenderDefaultAct(testMethod); } } - private static string RenderDefaultAct(TestMethod method) => $"sut.{method.Data.TestedMethod}();"; + private static string RenderDefaultAct(TestMethod testMethod) => $"sut.{testMethod.TestedMethod}();"; - private string RenderInstructionsAct(TestMethod method) + private string RenderInstructionsAct(TestMethod testMethod) { - var actual = Render.Object(method.Data.Input["instructions"]); + var actual = Render.Object(testMethod.Input["instructions"]); return $"sut.Simulate({actual});"; } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { - var expected = (Dictionary)method.Data.Expected; + var expected = (Dictionary)testMethod.Expected; expected.TryGetValue("position", out var position); expected.TryGetValue("direction", out var direction); diff --git a/generators/Exercises/Generators/RomanNumerals.cs b/generators/Exercises/Generators/RomanNumerals.cs index b18316784a..a19155138f 100644 --- a/generators/Exercises/Generators/RomanNumerals.cs +++ b/generators/Exercises/Generators/RomanNumerals.cs @@ -4,10 +4,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class RomanNumerals : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethodType = TestedMethodType.Extension; - data.TestedMethod = "ToRoman"; + testMethod.TestedMethodType = TestedMethodType.ExtensionMethod; + testMethod.TestedMethod = "ToRoman"; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index bbe8ead094..5bffc38428 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -4,25 +4,22 @@ namespace Exercism.CSharp.Exercises.Generators { public class RunLengthEncoding : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseFullDescriptionPath = true; - } + testMethod.TestMethodName = testMethod.TestMethodNameWithPath; - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) - => method.Data.Property == "consistency" - ? RenderConsistencyToAssert(method) - : method.Assert; + private string RenderAssert(TestMethod testMethod) + => testMethod.Property == "consistency" + ? RenderConsistencyToAssert(testMethod) + : testMethod.Assert; - private string RenderConsistencyToAssert(TestMethod method) + private string RenderConsistencyToAssert(TestMethod testMethod) { - var expected = Render.Object(method.Data.Expected); - var actual = $"{method.Data.TestedClass}.Decode({method.Data.TestedClass}.Encode({expected}))"; + var expected = Render.Object(testMethod.Expected); + var actual = $"{testMethod.TestedClass}.Decode({testMethod.TestedClass}.Encode({expected}))"; return Render.AssertEqual(expected, actual); } } diff --git a/generators/Exercises/Generators/SaddlePoints.cs b/generators/Exercises/Generators/SaddlePoints.cs index 69f7e01c9e..236574477d 100644 --- a/generators/Exercises/Generators/SaddlePoints.cs +++ b/generators/Exercises/Generators/SaddlePoints.cs @@ -7,21 +7,21 @@ namespace Exercism.CSharp.Exercises.Generators { public class SaddlePoints : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethodType = TestedMethodType.Instance; - data.TestedMethod = "Calculate"; - data.SetConstructorInputParameters("matrix"); - data.UseVariablesForConstructorParameters = true; - data.UseVariablesForInput = true; - data.UseVariableForTested = true; - data.UseVariableForExpected = true; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + testMethod.TestedMethod = "Calculate"; + testMethod.SetConstructorInputParameters("matrix"); + testMethod.UseVariablesForConstructorParameters = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForTested = true; + testMethod.UseVariableForExpected = true; - data.Input["matrix"] = ToMultiDimensionalArray(data.Input["matrix"]); + testMethod.Input["matrix"] = ToMultiDimensionalArray(testMethod.Input["matrix"]); - if (data.Expected is Array array) + if (testMethod.Expected is Array array) { - data.Expected = ToTupleCollection(array); + testMethod.Expected = ToTupleCollection(array); } } @@ -32,14 +32,14 @@ protected override void UpdateNamespaces(ISet namespaces) private static dynamic ToMultiDimensionalArray(JArray jArray) => jArray.ToObject(); - private static ValueTuple[] ToTupleCollection(Array array) + private static (string, object)[] ToTupleCollection(Array array) { - var tuples = new List>(); + var tuples = new List<(string, object)>(); for (var x = 0; x < array.GetLength(0); x++) { var current = (Dictionary)array.GetValue(x); - tuples.Add(new ValueTuple(current["row"].ToString(), current["column"].ToString())); + tuples.Add((current["row"].ToString(), current["column"].ToString())); } return tuples.ToArray(); diff --git a/generators/Exercises/Generators/Say.cs b/generators/Exercises/Generators/Say.cs index 2d44ceb57f..003c29bc00 100644 --- a/generators/Exercises/Generators/Say.cs +++ b/generators/Exercises/Generators/Say.cs @@ -5,12 +5,12 @@ namespace Exercism.CSharp.Exercises.Generators { public class Say : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = "InEnglish"; + testMethod.TestedMethod = "InEnglish"; - if (data.Expected is int) - data.ExceptionThrown = typeof(ArgumentOutOfRangeException); + if (testMethod.Expected is int) + testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ScaleGenerator.cs b/generators/Exercises/Generators/ScaleGenerator.cs index a4a8e6aa12..74528f1ad9 100644 --- a/generators/Exercises/Generators/ScaleGenerator.cs +++ b/generators/Exercises/Generators/ScaleGenerator.cs @@ -4,9 +4,9 @@ namespace Exercism.CSharp.Exercises.Generators { public class ScaleGenerator : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; + testMethod.UseVariableForExpected = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Sieve.cs b/generators/Exercises/Generators/Sieve.cs index 6acbc8bca9..a15fcb46ea 100644 --- a/generators/Exercises/Generators/Sieve.cs +++ b/generators/Exercises/Generators/Sieve.cs @@ -5,12 +5,12 @@ namespace Exercism.CSharp.Exercises.Generators { public class Sieve : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; + testMethod.UseVariableForExpected = true; - if (data.Input["limit"] < 2) - data.ExceptionThrown = typeof(ArgumentOutOfRangeException); + if (testMethod.Input["limit"] < 2) + testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index 31197aefb5..7e27ed4001 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Text.RegularExpressions; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; @@ -7,59 +8,48 @@ namespace Exercism.CSharp.Exercises.Generators { public class SimpleCipher : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseFullDescriptionPath = true; + testMethod.TestMethodName = testMethod.TestMethodNameWithPath; + + if (testMethod.Input.ContainsKey("key")) + { + testMethod.SetConstructorInputParameters("key"); + } - if (data.Property == "new") + if (testMethod.Property == "new") { + testMethod.TestedMethodType = TestedMethodType.Constructor; + testMethod.ExceptionThrown = typeof(ArgumentException); return; } - data.TestedMethodType = TestedMethodType.Instance; - - if (data.Input.ContainsKey("key")) + if (testMethod.Property == "key") { - data.SetConstructorInputParameters("key"); + testMethod.Expected = new Regex(testMethod.Expected["match"]); + testMethod.TestedMethodType = TestedMethodType.Property; + return; } - if (data.Input.TryGetValue("ciphertext", out var cipherText)) + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + + if (testMethod.Input.TryGetValue("ciphertext", out var cipherText)) { if (cipherText.StartsWith("cipher.key.substring")) { - data.Input["ciphertext"] = new UnescapedValue($"sut.Key.Substring(0, {data.Expected.Length})"); + testMethod.Input["ciphertext"] = new UnescapedValue($"sut.Key.Substring(0, {testMethod.Expected.Length})"); } else if (cipherText == "cipher.encode") { - var plaintext = Render.Object(data.Input["plaintext"]); - data.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); - data.SetInputParameters("ciphertext"); + var plaintext = Render.Object(testMethod.Input["plaintext"]); + testMethod.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); + testMethod.SetInputParameters("ciphertext"); } } - if (data.Expected is string s && s.StartsWith("cipher.key.substring")) - { - data.Expected = new UnescapedValue($"sut.Key.Substring(0, {data.Input["plaintext"].Length})"); - } - } - - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); - } - - private string RenderAssert(TestMethod method) - { - switch (method.Data.Property) + if (testMethod.Expected is string s && s.StartsWith("cipher.key.substring")) { - case "new": - var key = Render.Object(method.Data.Input["key"]); - return Render.AssertThrows($"new SimpleCipher({key})"); - case "key": - var pattern = Render.Object(method.Data.Expected["match"]); - return Render.AssertMatches(pattern, "sut.Key"); - default: - return method.Assert; + testMethod.Expected = new UnescapedValue($"sut.Key.Substring(0, {testMethod.Input["plaintext"].Length})"); } } diff --git a/generators/Exercises/Generators/SpaceAge.cs b/generators/Exercises/Generators/SpaceAge.cs index a2f4b21f3b..f0187dd6d5 100644 --- a/generators/Exercises/Generators/SpaceAge.cs +++ b/generators/Exercises/Generators/SpaceAge.cs @@ -4,11 +4,11 @@ namespace Exercism.CSharp.Exercises.Generators { public class SpaceAge : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = $"On{data.Input["planet"]}"; - data.SetInputParameters(); - data.SetConstructorInputParameters("seconds"); + testMethod.TestedMethod = $"On{testMethod.Input["planet"]}"; + testMethod.SetInputParameters(); + testMethod.SetConstructorInputParameters("seconds"); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/SpiralMatrix.cs b/generators/Exercises/Generators/SpiralMatrix.cs index 7d0aa3a5de..1cebbca7ef 100644 --- a/generators/Exercises/Generators/SpiralMatrix.cs +++ b/generators/Exercises/Generators/SpiralMatrix.cs @@ -5,11 +5,11 @@ namespace Exercism.CSharp.Exercises.Generators { public class SpiralMatrix : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = "GetMatrix"; - data.UseVariableForExpected = true; - data.Expected = ConvertExpected(data.Expected); + testMethod.TestedMethod = "GetMatrix"; + testMethod.UseVariableForExpected = true; + testMethod.Expected = ConvertExpected(testMethod.Expected); } private static int[,] ConvertExpected(JArray jArray) => jArray.ToObject(); diff --git a/generators/Exercises/Generators/Sublist.cs b/generators/Exercises/Generators/Sublist.cs index d4f3e10143..f0864649a9 100644 --- a/generators/Exercises/Generators/Sublist.cs +++ b/generators/Exercises/Generators/Sublist.cs @@ -7,13 +7,13 @@ namespace Exercism.CSharp.Exercises.Generators { public class Sublist : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.Input["listOne"] = ConvertToList(data.Input["listOne"]); - data.Input["listTwo"] = ConvertToList(data.Input["listTwo"]); + testMethod.Input["listOne"] = ConvertToList(testMethod.Input["listOne"]); + testMethod.Input["listTwo"] = ConvertToList(testMethod.Input["listTwo"]); - data.TestedMethod = "Classify"; - data.Expected = Render.Enum("SublistType", data.Expected); + testMethod.TestedMethod = "Classify"; + testMethod.Expected = Render.Enum("SublistType", testMethod.Expected); } private static List ConvertToList(dynamic value) => new List(value as int[] ?? Array.Empty()); diff --git a/generators/Exercises/Generators/SumOfMultiples.cs b/generators/Exercises/Generators/SumOfMultiples.cs index 4fcce14dd3..f3c7e6465c 100644 --- a/generators/Exercises/Generators/SumOfMultiples.cs +++ b/generators/Exercises/Generators/SumOfMultiples.cs @@ -7,10 +7,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class SumOfMultiples : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Input["factors"] is JArray) - data.Input["factors"] = Array.Empty(); + if (testMethod.Input["factors"] is JArray) + testMethod.Input["factors"] = Array.Empty(); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/Tournament.cs b/generators/Exercises/Generators/Tournament.cs index 0700b8878b..fd43f65ef5 100644 --- a/generators/Exercises/Generators/Tournament.cs +++ b/generators/Exercises/Generators/Tournament.cs @@ -9,38 +9,28 @@ namespace Exercism.CSharp.Exercises.Generators { public class Tournament : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = "RunTally"; - data.TestedMethodType = TestedMethodType.Static; - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; - data.Input["rows"] = new MultiLineString(data.Input["rows"]); - data.Expected = new MultiLineString(data.Expected); - } - - protected override void UpdateNamespaces(ISet namespaces) - { - namespaces.Add(typeof(Array).Namespace); - namespaces.Add(typeof(Stream).Namespace); - namespaces.Add(typeof(UTF8Encoding).Namespace); - } + testMethod.TestedMethod = "RunTally"; + testMethod.TestedMethodType = TestedMethodType.StaticMethod; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; + testMethod.Input["rows"] = new MultiLineString(testMethod.Input["rows"]); + testMethod.Expected = new MultiLineString(testMethod.Expected); - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(); + testMethod.Assert = RenderAssert(); } private string RenderAssert() => Render.AssertEqual("expected", "RunTally(rows)"); - protected override void UpdateTestClass(TestClass @class) + protected override void UpdateTestClass(TestClass testClass) { - AddRunTallyMethod(@class); + AddRunTallyMethod(testClass); } - private static void AddRunTallyMethod(TestClass @class) + private static void AddRunTallyMethod(TestClass testClass) { - @class.Methods.Add(@" + testClass.Methods.Add(@" private string RunTally(string input) { var encoding = new UTF8Encoding(); @@ -53,5 +43,12 @@ private string RunTally(string input) } }"); } + + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Array).Namespace); + namespaces.Add(typeof(Stream).Namespace); + namespaces.Add(typeof(UTF8Encoding).Namespace); + } } } diff --git a/generators/Exercises/Generators/Transpose.cs b/generators/Exercises/Generators/Transpose.cs index 07b78944bc..240385f79a 100644 --- a/generators/Exercises/Generators/Transpose.cs +++ b/generators/Exercises/Generators/Transpose.cs @@ -5,14 +5,14 @@ namespace Exercism.CSharp.Exercises.Generators { public class Transpose : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = "String"; - data.Input["lines"] = new MultiLineString(data.Input["lines"]); - data.Expected = new MultiLineString(data.Expected); + testMethod.TestedMethod = "String"; + testMethod.Input["lines"] = new MultiLineString(testMethod.Input["lines"]); + testMethod.Expected = new MultiLineString(testMethod.Expected); - data.UseVariablesForInput = true; - data.UseVariableForExpected = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Triangle.cs b/generators/Exercises/Generators/Triangle.cs index 53f2c3bc5f..f51ff47283 100644 --- a/generators/Exercises/Generators/Triangle.cs +++ b/generators/Exercises/Generators/Triangle.cs @@ -5,17 +5,17 @@ namespace Exercism.CSharp.Exercises.Generators { public class Triangle : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = $"Is{data.TestedMethod}".ToTestedMethodName(); + testMethod.TestedMethod = $"Is{testMethod.TestedMethod}".ToTestedMethodName(); - data.Input["x"] = data.Input["sides"][0]; - data.Input["y"] = data.Input["sides"][1]; - data.Input["z"] = data.Input["sides"][2]; - data.Input.Remove("sides"); - data.SetInputParameters("x", "y", "z"); + testMethod.Input["x"] = testMethod.Input["sides"][0]; + testMethod.Input["y"] = testMethod.Input["sides"][1]; + testMethod.Input["z"] = testMethod.Input["sides"][2]; + testMethod.Input.Remove("sides"); + testMethod.SetInputParameters("x", "y", "z"); - data.UseFullDescriptionPath = true; + testMethod.TestMethodName = testMethod.TestMethodNameWithPath; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/TwelveDays.cs b/generators/Exercises/Generators/TwelveDays.cs index e6be70791d..90c4bd73e4 100644 --- a/generators/Exercises/Generators/TwelveDays.cs +++ b/generators/Exercises/Generators/TwelveDays.cs @@ -5,14 +5,14 @@ namespace Exercism.CSharp.Exercises.Generators { public class TwelveDays : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; - data.Expected = new MultiLineString(data.Expected); + testMethod.UseVariableForExpected = true; + testMethod.Expected = new MultiLineString(testMethod.Expected); - if (data.Input["startVerse"] == data.Input["endVerse"]) + if (testMethod.Input["startVerse"] == testMethod.Input["endVerse"]) { - data.SetInputParameters("startVerse"); + testMethod.SetInputParameters("startVerse"); } } } diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index 8688bd0746..bdd307f26e 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -5,28 +5,25 @@ namespace Exercism.CSharp.Exercises.Generators { public class TwoBucket : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethodType = TestedMethodType.Instance; - data.SetConstructorInputParameters("bucketOne", "bucketTwo", "startBucket"); - data.Input["startBucket"] = Render.Enum("Bucket", data.Input["startBucket"]); - } + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + testMethod.SetConstructorInputParameters("bucketOne", "bucketTwo", "startBucket"); + testMethod.Input["startBucket"] = Render.Enum("Bucket", testMethod.Input["startBucket"]); - protected override void UpdateTestMethod(TestMethod method) - { - method.Act = RenderAct(method); - method.Assert = RenderAssert(method); + testMethod.Act = RenderAct(testMethod); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAct(TestMethod method) => Render.Variable("result", method.TestedMethodInvocation); + private string RenderAct(TestMethod testMethod) => Render.Variable("result", testMethod.TestedMethodInvocation); - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { var assert = new StringBuilder(); - assert.AppendLine(Render.AssertEqual(method.Data.Expected["moves"].ToString(), "result.Moves")); - assert.AppendLine(Render.AssertEqual(method.Data.Expected["otherBucket"].ToString(), "result.OtherBucket")); + assert.AppendLine(Render.AssertEqual(testMethod.Expected["moves"].ToString(), "result.Moves")); + assert.AppendLine(Render.AssertEqual(testMethod.Expected["otherBucket"].ToString(), "result.OtherBucket")); - var expected = Render.Enum("Bucket", method.Data.Expected["goalBucket"]); + var expected = Render.Enum("Bucket", testMethod.Expected["goalBucket"]); assert.AppendLine(Render.AssertEqual(expected.ToString(), "result.GoalBucket")); return assert.ToString(); diff --git a/generators/Exercises/Generators/TwoFer.cs b/generators/Exercises/Generators/TwoFer.cs index 85e9eaf807..2f077dd9da 100644 --- a/generators/Exercises/Generators/TwoFer.cs +++ b/generators/Exercises/Generators/TwoFer.cs @@ -4,12 +4,12 @@ namespace Exercism.CSharp.Exercises.Generators { public class TwoFer : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedMethod = "Name"; + testMethod.TestedMethod = "Name"; - if (data.Input["name"] is null) - data.SetInputParameters(); + if (testMethod.Input["name"] is null) + testMethod.SetInputParameters(); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/VariableLengthQuantity.cs b/generators/Exercises/Generators/VariableLengthQuantity.cs index 906d2ef9d8..3fb539310f 100644 --- a/generators/Exercises/Generators/VariableLengthQuantity.cs +++ b/generators/Exercises/Generators/VariableLengthQuantity.cs @@ -8,16 +8,16 @@ namespace Exercism.CSharp.Exercises.Generators { public class VariableLengthQuantity : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; - data.UseVariablesForInput = true; - data.Input["integers"] = ConvertToUInt32Array(data.Input["integers"]); + testMethod.UseVariableForExpected = true; + testMethod.UseVariablesForInput = true; + testMethod.Input["integers"] = ConvertToUInt32Array(testMethod.Input["integers"]); - if (data.Expected == null) - data.ExceptionThrown = typeof(InvalidOperationException); + if (testMethod.Expected == null) + testMethod.ExceptionThrown = typeof(InvalidOperationException); else - data.Expected = ConvertToUInt32Array(data.Expected); + testMethod.Expected = ConvertToUInt32Array(testMethod.Expected); } private static uint[] ConvertToUInt32Array(IEnumerable input) diff --git a/generators/Exercises/Generators/WordCount.cs b/generators/Exercises/Generators/WordCount.cs index 9f9c795f3f..0ee4d1c8e7 100644 --- a/generators/Exercises/Generators/WordCount.cs +++ b/generators/Exercises/Generators/WordCount.cs @@ -7,11 +7,11 @@ namespace Exercism.CSharp.Exercises.Generators { public class WordCount : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariableForExpected = true; - data.UseVariableForTested = true; - data.Expected = ConvertExpected(data.Expected); + testMethod.UseVariableForExpected = true; + testMethod.UseVariableForTested = true; + testMethod.Expected = ConvertExpected(testMethod.Expected); } private static dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 4805473b89..4c30858511 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; -using DotLiquid.Tags; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; @@ -10,29 +9,26 @@ namespace Exercism.CSharp.Exercises.Generators { public class WordSearch : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.UseVariablesForInput = true; - data.UseVariableForTested = true; - data.UseVariableForExpected = true; - data.UseVariablesForConstructorParameters = true; + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForTested = true; + testMethod.UseVariableForExpected = true; + testMethod.UseVariablesForConstructorParameters = true; - data.SetConstructorInputParameters("grid"); + testMethod.SetConstructorInputParameters("grid"); - data.Input["grid"] = new MultiLineString(data.Input["grid"]); - data.Expected = ((IDictionary)data.Expected).ToDictionary(kv => kv.Key, kv => (((int, int), (int, int))?)ConvertToPosition(kv.Value)); - } + testMethod.Input["grid"] = new MultiLineString(testMethod.Input["grid"]); + testMethod.Expected = ((IDictionary)testMethod.Expected).ToDictionary(kv => kv.Key, kv => (((int, int), (int, int))?)ConvertToPosition(kv.Value)); - protected override void UpdateTestMethod(TestMethod method) - { - method.Assert = RenderAssert(method); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { var assert = new StringBuilder(); - foreach (var kv in method.Data.Expected) + foreach (var kv in testMethod.Expected) assert.AppendLine(RenderAssertForSearchWord(kv.Key, kv.Value)); return assert.ToString(); diff --git a/generators/Exercises/Generators/Wordy.cs b/generators/Exercises/Generators/Wordy.cs index b20c76ea8f..ef27256bc3 100644 --- a/generators/Exercises/Generators/Wordy.cs +++ b/generators/Exercises/Generators/Wordy.cs @@ -5,10 +5,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class Wordy : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - if (data.Expected is bool) - data.ExceptionThrown = typeof(ArgumentException); + if (testMethod.Expected is bool) + testMethod.ExceptionThrown = typeof(ArgumentException); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Yacht.cs b/generators/Exercises/Generators/Yacht.cs index c9abf0c6bf..78c8037527 100644 --- a/generators/Exercises/Generators/Yacht.cs +++ b/generators/Exercises/Generators/Yacht.cs @@ -4,10 +4,10 @@ namespace Exercism.CSharp.Exercises.Generators { public class Yacht : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.TestedClass = "YachtGame"; - data.Input["category"] = Render.Enum("YachtCategory", data.Input["category"]); + testMethod.TestedClass = "YachtGame"; + testMethod.Input["category"] = Render.Enum("YachtCategory", testMethod.Input["category"]); } } } diff --git a/generators/Exercises/Generators/ZebraPuzzle.cs b/generators/Exercises/Generators/ZebraPuzzle.cs index 4eb04cd17b..34b5fe4144 100644 --- a/generators/Exercises/Generators/ZebraPuzzle.cs +++ b/generators/Exercises/Generators/ZebraPuzzle.cs @@ -4,9 +4,9 @@ namespace Exercism.CSharp.Exercises.Generators { public class ZebraPuzzle : GeneratorExercise { - protected override void UpdateTestData(TestData data) + protected override void UpdateTestMethod(TestMethod testMethod) { - data.Expected = Render.Enum("Nationality", data.Expected); + testMethod.Expected = Render.Enum("Nationality", testMethod.Expected); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Zipper.cs b/generators/Exercises/Generators/Zipper.cs index cb48057353..048030c223 100644 --- a/generators/Exercises/Generators/Zipper.cs +++ b/generators/Exercises/Generators/Zipper.cs @@ -3,33 +3,32 @@ using System.Text; using Exercism.CSharp.Helpers; using Exercism.CSharp.Output; -using Humanizer; namespace Exercism.CSharp.Exercises.Generators { public class Zipper : GeneratorExercise { - protected override void UpdateTestMethod(TestMethod method) + protected override void UpdateTestMethod(TestMethod testMethod) { - method.Arrange = RenderArrange(method); - method.Assert = RenderAssert(method); + testMethod.Arrange = RenderArrange(testMethod); + testMethod.Assert = RenderAssert(testMethod); } - private string RenderArrange(TestMethod method) + private string RenderArrange(TestMethod testMethod) { var arrange = new StringBuilder(); - var tree = RenderTree(method.Data.Input["initialTree"]); + var tree = RenderTree(testMethod.Input["initialTree"]); arrange.AppendLine(Render.Variable("tree", tree)); arrange.AppendLine(Render.Variable("sut", "Zipper.FromTree(tree)")); - var operations = RenderOperations(method.Data.Input["operations"]); + var operations = RenderOperations(testMethod.Input["operations"]); arrange.AppendLine(Render.Variable("actual", $"sut{operations}")); return arrange.ToString(); } - private string RenderAssert(TestMethod method) + private string RenderAssert(TestMethod testMethod) { - var expected = RenderExpected(method.Data.Expected); + var expected = RenderExpected(testMethod.Expected); if (expected == null) { return Render.AssertNull("actual"); diff --git a/generators/Exercises/TestedMethodType.cs b/generators/Exercises/TestedMethodType.cs index 46d7b8bc7e..d1a0768d39 100644 --- a/generators/Exercises/TestedMethodType.cs +++ b/generators/Exercises/TestedMethodType.cs @@ -2,8 +2,10 @@ namespace Exercism.CSharp.Exercises { public enum TestedMethodType { - Static, - Instance, - Extension + StaticMethod, + InstanceMethod, + ExtensionMethod, + Property, + Constructor } } \ No newline at end of file diff --git a/generators/Generators.csproj b/generators/Generators.csproj index 3d7be3919d..a56c06b6bb 100644 --- a/generators/Generators.csproj +++ b/generators/Generators.csproj @@ -15,6 +15,5 @@ - \ No newline at end of file diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index d8aaabcb1e..f486cc79d2 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Reflection; using System.Text.RegularExpressions; using Humanizer; diff --git a/generators/Input/JTokenHelper.cs b/generators/Input/JTokenHelper.cs index 967943afd9..02a15c6763 100644 --- a/generators/Input/JTokenHelper.cs +++ b/generators/Input/JTokenHelper.cs @@ -54,7 +54,7 @@ private static dynamic ConvertJObject(JObject jObject) properties[key] = value is JToken jToken ? ConvertJToken(jToken) : value; } - return properties; + return new Dictionary(properties, StringComparer.OrdinalIgnoreCase); } private static dynamic ConvertJArray(JArray jArray) diff --git a/generators/Input/TrackConfigFile.cs b/generators/Input/TrackConfigFile.cs index a312a3cc34..996c510afc 100644 --- a/generators/Input/TrackConfigFile.cs +++ b/generators/Input/TrackConfigFile.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.IO; using System.Linq; using Exercism.CSharp.Helpers; using Newtonsoft.Json; @@ -7,11 +8,11 @@ namespace Exercism.CSharp.Input { public static class TrackConfigFile { - private static readonly string ConfigFileName = $"{typeof(TrackConfigFile).Namespace}.config.json"; + private static readonly string ConfigFilePath = Path.Combine("..", "config.json"); public static IEnumerable GetExercises() { - var jsonContents = EmbeddedResource.Read(ConfigFileName); + var jsonContents = File.ReadAllText(ConfigFilePath); var config = JsonConvert.DeserializeObject(jsonContents); return config.Exercises.OrderBy(x => x.Slug).ToArray(); } diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 7d23ce32c2..45e38f1c64 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using System.Text.RegularExpressions; namespace Exercism.CSharp.Output.Rendering { @@ -21,6 +22,7 @@ public string Object(object val) case float flt: return Float(flt); case ulong ulng: return Ulong(ulng); case char c: return Char(c); + case Regex regex: return Regex(regex); default: if (IsList(val)) return List((dynamic)val); diff --git a/generators/Output/Rendering/RenderString.cs b/generators/Output/Rendering/RenderString.cs index fd09196839..35a3eace25 100644 --- a/generators/Output/Rendering/RenderString.cs +++ b/generators/Output/Rendering/RenderString.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.RegularExpressions; using Humanizer; namespace Exercism.CSharp.Output.Rendering @@ -31,5 +32,7 @@ IEnumerable RenderLines() => ? $"{String($"{t}\n").Indent()} +" : $"{String(t).Indent()}"); } + + public string Regex(Regex regex) => String(regex.ToString()); } } \ No newline at end of file diff --git a/generators/Output/Rendering/RenderVariable.cs b/generators/Output/Rendering/RenderVariable.cs index ff00206e52..fc6e9d0b4c 100644 --- a/generators/Output/Rendering/RenderVariable.cs +++ b/generators/Output/Rendering/RenderVariable.cs @@ -6,11 +6,11 @@ namespace Exercism.CSharp.Output.Rendering { public partial class Render { - public IEnumerable Variables(IDictionary dict) - => dict.Select(Variable).ToArray(); + public IEnumerable Variables(IDictionary variables) + => variables.Select(Variable).ToArray(); - private string Variable(KeyValuePair kv) - => Variable(kv.Key.ToVariableName(), ObjectMultiLine(kv.Value)); + private string Variable(KeyValuePair variable) + => Variable(variable.Key.ToVariableName(), ObjectMultiLine(variable.Value)); public string Variable(string name, string value) => $"var {name} = {value};"; } diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index 1c690d8a94..034e4ad7a1 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -10,7 +10,7 @@ public class TestClass public string Exercise { get; set; } public string ClassName { get; set; } public string CanonicalDataVersion { get; set; } - public ICollection Methods { get; set; } + public IList Methods { get; set; } public ISet Namespaces { get; set; } public bool IsDisposable { get; set; } diff --git a/generators/Output/TestData.cs b/generators/Output/TestData.cs deleted file mode 100644 index 1e017b188b..0000000000 --- a/generators/Output/TestData.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Exercism.CSharp.Exercises; -using Exercism.CSharp.Helpers; -using Exercism.CSharp.Input; - -namespace Exercism.CSharp.Output -{ - public class TestData - { - public TestData(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) - { - Input = new Dictionary(canonicalDataCase.Input); - Expected = canonicalDataCase.Expected; - - Exercise = canonicalData.Exercise; - Property = canonicalDataCase.Property; - - Description = canonicalDataCase.Description; - DescriptionPath = new List(canonicalDataCase.DescriptionPath); - - SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); - - Skip = canonicalDataCase.Index > 0; - - TestedClass = canonicalData.Exercise.ToTestedClassName(); - TestedMethod = canonicalDataCase.Property.ToTestedMethodName(); - } - - public string Exercise { get; } - public string Property { get; } - - public IDictionary Input { get; set; } - public dynamic Expected { get; set; } - - public string Description { get; set; } - public IList DescriptionPath { get; set; } - - public bool Skip { get; set; } - - public bool UseVariablesForInput { get; set; } - public bool UseVariableForExpected { get; set; } - public bool UseVariablesForConstructorParameters { get; set; } - public bool UseVariableForTested { get; set; } - public bool UseFullDescriptionPath { get; set; } - - public string TestMethod => - UseFullDescriptionPath - ? string.Join(" - ", DescriptionPath).ToTestMethodName() - : Description.ToTestMethodName(); - - public string TestedClass { get; set; } - public string TestedMethod { get; set; } - public TestedMethodType TestedMethodType { get; set; } - public Type ExceptionThrown { get; set; } - - public HashSet InputParameters { get; } = new HashSet(); - public HashSet ConstructorInputParameters { get; } = new HashSet(); - - public void SetInputParameters(params string[] properties) - { - InputParameters.Clear(); - InputParameters.UnionWith(properties); - - ConstructorInputParameters.ExceptWith(properties); - } - - public void SetConstructorInputParameters(params string[] properties) - { - ConstructorInputParameters.Clear(); - ConstructorInputParameters.UnionWith(properties); - - InputParameters.ExceptWith(properties); - - TestedMethodType = TestedMethodType.Instance; - } - } -} \ No newline at end of file diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index befa452d37..26f98e8b8a 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -1,62 +1,102 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Text.RegularExpressions; using Exercism.CSharp.Exercises; using Exercism.CSharp.Helpers; +using Exercism.CSharp.Input; using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Output { - public abstract class TestMethod + public class TestMethod { + private enum AssertType + { + Equal, + Empty, + Null, + Throws, + Boolean, + Matches + } + private const string SutVariableName = "sut"; private const string TestedVariableName = "actual"; private const string ExpectedVariableName = "expected"; private const string TemplateName = "TestMethod"; - - private const string ArrangeTemplateName = "Arrange"; - private const string ActTemplateName = "Act"; - - protected Render Renderer { get; } = new Render(); - protected TestMethod(TestData data) => Data = data; + private static readonly Render Renderer = new Render(); - public TestData Data { get; } - - public object ArrangeTemplateParameters { get; set; } - public object ActTemplateParameters { get; set; } - public object AssertTemplateParameters { get; set; } + private readonly HashSet _inputParameterProperties = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _constructorInputParameterProperties = new HashSet(StringComparer.OrdinalIgnoreCase); - public string Act { get; set; } - public string Arrange { get; set; } - public string Assert { get; set; } - - public string Render() + public TestMethod(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) { - ArrangeTemplateParameters = ArrangeTemplateParameters ?? new { Variables }; - ActTemplateParameters = ActTemplateParameters ?? new { }; - AssertTemplateParameters = AssertTemplateParameters ?? new { ExpectedParameter, TestedValue }; + Input = new Dictionary(canonicalDataCase.Input, StringComparer.OrdinalIgnoreCase); + Expected = canonicalDataCase.Expected; + Property = canonicalDataCase.Property; + TestMethodName = canonicalDataCase.Description.ToTestMethodName(); + TestMethodNameWithPath = string.Join(" - ", canonicalDataCase.DescriptionPath).ToTestMethodName(); + TestedClass = canonicalData.Exercise.ToTestedClassName(); + TestedMethod = canonicalDataCase.Property.ToTestedMethodName(); + Skip = canonicalDataCase.Index > 0; + + SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); + } - Arrange = Arrange ?? RenderArrange(); - Act = Act ?? RenderAct(); - Assert = Assert ?? RenderAssert(); + public string Property { get; } + + public IDictionary Input { get; set; } + public dynamic Expected { get; set; } - return Template.Render(TemplateName, new { Name = Data.TestMethod, Data.Skip, Arrange, Act, Assert }); + public bool Skip { get; set; } + + public bool UseVariablesForInput { get; set; } + public bool UseVariableForExpected { get; set; } + public bool UseVariablesForConstructorParameters { get; set; } + public bool UseVariableForTested { get; set; } + private bool UseVariableForSut + => TestedMethodType == TestedMethodType.InstanceMethod || + TestedMethodType == TestedMethodType.Property; + + public string TestMethodName { get; set; } + public string TestMethodNameWithPath { get; } + public string TestedClass { get; set; } + public string TestedMethod { get; set; } + public TestedMethodType TestedMethodType { get; set; } + public Type ExceptionThrown { get; set; } + + public void SetInputParameters(params string[] properties) + { + _inputParameterProperties.Clear(); + _inputParameterProperties.UnionWith(properties); + + _constructorInputParameterProperties.ExceptWith(properties); } - public string SutValue => $"new {Data.TestedClass}({ConstructorParameters})"; - public string TestedValue => Data.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; - public string ExpectedParameter => Data.UseVariableForExpected ? ExpectedVariableName : Renderer.Object(Data.Expected); - - private string InputParameters => string.Join(", ", Data.InputParameters.Select(key => Data.UseVariablesForInput ? key.ToVariableName() : Renderer.Object(Data.Input[key]))); - private string ConstructorParameters => string.Join(", ", Data.ConstructorInputParameters.Select(key => Data.UseVariablesForConstructorParameters ? key.ToVariableName() : Renderer.Object(Data.Input[key]))); + public void SetConstructorInputParameters(params string[] properties) + { + _constructorInputParameterProperties.Clear(); + _constructorInputParameterProperties.UnionWith(properties); + + _inputParameterProperties.ExceptWith(properties); - private IDictionary Input => Data.InputParameters.ToDictionary(key => key, key => Data.Input[key]); - private IDictionary ConstructorInput => Data.ConstructorInputParameters.ToDictionary(key => key, key => Data.Input[key]); + if (TestedMethodType == TestedMethodType.StaticMethod) + TestedMethodType = TestedMethodType.InstanceMethod; + } + + public string SutValue => $"new {TestedClass}({ConstructorParameters})"; + public string TestedValue => UseVariableForTested ? TestedVariableName : TestedMethodInvocation; + public string ExpectedParameter => UseVariableForExpected ? ExpectedVariableName : Renderer.Object(Expected); + + private string InputParameters => string.Join(", ", _inputParameterProperties.Select(key => UseVariablesForInput ? key.ToVariableName() : Renderer.Object(Input[key]))); + private string ConstructorParameters => string.Join(", ", _constructorInputParameterProperties.Select(key => UseVariablesForConstructorParameters ? key.ToVariableName() : Renderer.Object(Input[key]))); - private string ExpectedVariableDeclaration => Renderer.Variable(ExpectedVariableName, Renderer.ObjectMultiLine(Data.Expected)); - private IEnumerable InputVariablesDeclaration => Renderer.Variables(Input); - private IEnumerable ConstructorVariablesDeclaration => Renderer.Variables(ConstructorInput); + private string ExpectedVariableDeclaration => Renderer.Variable(ExpectedVariableName, Renderer.ObjectMultiLine(Expected)); + private IEnumerable InputVariablesDeclaration => Renderer.Variables(_inputParameterProperties.ToDictionary(key => key, key => Input[key])); + private IEnumerable ConstructorVariablesDeclaration => Renderer.Variables(_constructorInputParameterProperties.ToDictionary(key => key, key => Input[key])); private IEnumerable SutVariableDeclaration => new[] { Renderer.Variable(SutVariableName, SutValue) }; private IEnumerable ActualVariableDeclaration => new[] { Renderer.Variable(TestedVariableName, TestedMethodInvocation) }; @@ -66,19 +106,19 @@ public IEnumerable Variables { var lines = new List(); - if (Data.UseVariablesForInput) + if (UseVariablesForInput) lines.AddRange(InputVariablesDeclaration); - if (Data.UseVariablesForConstructorParameters) + if (UseVariablesForConstructorParameters) lines.AddRange(ConstructorVariablesDeclaration); - if (Data.TestedMethodType == TestedMethodType.Instance) + if (UseVariableForSut) lines.AddRange(SutVariableDeclaration); - if (Data.UseVariableForTested) + if (UseVariableForTested) lines.AddRange(ActualVariableDeclaration); - if (Data.UseVariableForExpected) + if (UseVariableForExpected) lines.Add(ExpectedVariableDeclaration); return lines; @@ -89,26 +129,105 @@ public string TestedMethodInvocation { get { - switch (Data.TestedMethodType) + switch (TestedMethodType) { - case TestedMethodType.Static: - return $"{Data.TestedClass}.{Data.TestedMethod}({InputParameters})"; - case TestedMethodType.Instance: - return $"{SutVariableName}.{Data.TestedMethod}({InputParameters})"; - case TestedMethodType.Extension: - return $"{InputParameters}.{Data.TestedMethod}()"; + case TestedMethodType.StaticMethod: + return $"{TestedClass}.{TestedMethod}({InputParameters})"; + case TestedMethodType.ExtensionMethod: + return $"{InputParameters}.{TestedMethod}()"; + case TestedMethodType.InstanceMethod: + return $"{SutVariableName}.{TestedMethod}({InputParameters})"; + case TestedMethodType.Property: + return $"{SutVariableName}.{TestedMethod}"; + case TestedMethodType.Constructor: + return $"new {TestedClass}({ConstructorParameters})"; default: throw new ArgumentOutOfRangeException(); } } } + + + - private string RenderArrange() - => Template.Render(ArrangeTemplateName, ArrangeTemplateParameters); + public string Act { get; set; } + public string Arrange { get; set; } + public string Assert { get; set; } + + public string Render() + { + UpdateBasedOnCurrentAssertType(); + + Arrange = Arrange ?? RenderArrange(); + Act = Act ?? RenderAct(); + Assert = Assert ?? RenderAssert(); - private string RenderAct() - => Template.Render(ActTemplateName, ActTemplateParameters); + return Template.Render(TemplateName, new { Name = TestMethodName, Skip, Arrange, Act, Assert }); + } + + private string RenderArrange() => Template.Render("Arrange", new { Variables }); + + private string RenderAct() => Template.Render("Act", new { }); + + private string RenderAssert() + { + switch (CurrentAssertType) + { + case AssertType.Equal: + return Renderer.AssertEqual(ExpectedParameter, TestedValue); + case AssertType.Empty: + return Renderer.AssertEmpty(ExpectedParameter, TestedValue); + case AssertType.Null: + return Renderer.AssertNull(TestedValue); + case AssertType.Throws: + return Renderer.AssertThrows(ExceptionThrown, TestedValue); + case AssertType.Boolean: + return Renderer.AssertBoolean(Convert.ToBoolean(Expected), TestedValue); + case AssertType.Matches: + return Renderer.AssertMatches(ExpectedParameter, TestedValue); + default: + throw new ArgumentOutOfRangeException(); + } + } + + private void UpdateBasedOnCurrentAssertType() + { + switch (CurrentAssertType) + { + case AssertType.Empty: + UseVariableForExpected = false; + break; + case AssertType.Throws: + UseVariableForExpected = false; + UseVariableForTested = false; + break; + } + } + + private AssertType CurrentAssertType + { + get + { + if (ExceptionThrown != null) + return AssertType.Throws; + + switch (Expected) + { + case null: + return AssertType.Null; + case bool _: + return AssertType.Boolean; + case Regex _: + return AssertType.Matches; + default: + return UseEmptyAssertion + ? AssertType.Empty + : AssertType.Equal; + } + } + } - protected abstract string RenderAssert(); + private bool UseEmptyAssertion + => !(Expected is string) && Expected is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; } } \ No newline at end of file diff --git a/generators/Output/TestMethodWithBooleanAssertion.cs b/generators/Output/TestMethodWithBooleanAssertion.cs deleted file mode 100644 index 114b82241d..0000000000 --- a/generators/Output/TestMethodWithBooleanAssertion.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; - -namespace Exercism.CSharp.Output -{ - public class TestMethodWithBooleanAssertion : TestMethod - { - public TestMethodWithBooleanAssertion(TestData data) : base(data) - { - } - - protected override string RenderAssert() => Renderer.AssertBoolean(Convert.ToBoolean(Data.Expected), TestedValue); - } -} \ No newline at end of file diff --git a/generators/Output/TestMethodWithEmptyAssertion.cs b/generators/Output/TestMethodWithEmptyAssertion.cs deleted file mode 100644 index a10963d792..0000000000 --- a/generators/Output/TestMethodWithEmptyAssertion.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Exercism.CSharp.Output -{ - public class TestMethodWithEmptyAssertion : TestMethod - { - public TestMethodWithEmptyAssertion(TestData data): base(data) - { - Data.UseVariableForExpected = false; - } - - protected override string RenderAssert() => Renderer.AssertEmpty(ExpectedParameter, TestedValue); - } -} \ No newline at end of file diff --git a/generators/Output/TestMethodWithEqualityAssertion.cs b/generators/Output/TestMethodWithEqualityAssertion.cs deleted file mode 100644 index 9a5e57078c..0000000000 --- a/generators/Output/TestMethodWithEqualityAssertion.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Exercism.CSharp.Output -{ - public class TestMethodWithEqualityAssertion : TestMethod - { - public TestMethodWithEqualityAssertion(TestData data) : base(data) - { - } - - protected override string RenderAssert() => Renderer.AssertEqual(ExpectedParameter, TestedValue); - } -} \ No newline at end of file diff --git a/generators/Output/TestMethodWithExceptionAssertion.cs b/generators/Output/TestMethodWithExceptionAssertion.cs deleted file mode 100644 index 87e7678b5b..0000000000 --- a/generators/Output/TestMethodWithExceptionAssertion.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Exercism.CSharp.Output -{ - public class TestMethodWithExceptionAssertion : TestMethod - { - public TestMethodWithExceptionAssertion(TestData data) : base(data) - { - Data.UseVariableForExpected = false; - Data.UseVariableForTested = false; - } - - protected override string RenderAssert() => Renderer.AssertThrows(Data.ExceptionThrown, TestedValue); - } -} \ No newline at end of file diff --git a/generators/Output/TestMethodWithNullAssertion.cs b/generators/Output/TestMethodWithNullAssertion.cs deleted file mode 100644 index a78c3131c3..0000000000 --- a/generators/Output/TestMethodWithNullAssertion.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Exercism.CSharp.Output -{ - public class TestMethodWithNullAssertion : TestMethod - { - public TestMethodWithNullAssertion(TestData data) : base(data) - { - } - - protected override string RenderAssert() => Renderer.AssertNull(TestedValue); - } -} \ No newline at end of file From a47b54dea2ce8124b4636cb60bd039cbaa76cadf Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Fri, 6 Jul 2018 19:51:44 +0200 Subject: [PATCH 87/97] generators: Move TestClass and TestMethod rendering output to separate class --- .../complex-numbers/ComplexNumbersTest.cs | 80 ++-- exercises/meetup/MeetupTest.cs | 380 +++++++++--------- .../rational-numbers/RationalNumbersTest.cs | 6 +- exercises/two-bucket/TwoBucketTest.cs | 48 +-- generators/Exercises/GeneratorExercise.cs | 32 +- generators/Exercises/Generators/Allergies.cs | 3 +- generators/Exercises/Generators/Anagram.cs | 3 +- .../Exercises/Generators/BinarySearch.cs | 5 +- generators/Exercises/Generators/BookStore.cs | 2 +- generators/Exercises/Generators/Bowling.cs | 4 +- generators/Exercises/Generators/Clock.cs | 9 +- .../Exercises/Generators/ComplexNumbers.cs | 18 +- generators/Exercises/Generators/Connect.cs | 3 +- generators/Exercises/Generators/CustomSet.cs | 5 +- generators/Exercises/Generators/Etl.cs | 14 +- generators/Exercises/Generators/FoodChain.cs | 2 +- generators/Exercises/Generators/Gigasecond.cs | 11 +- generators/Exercises/Generators/GoCounting.cs | 5 +- generators/Exercises/Generators/Grep.cs | 10 +- generators/Exercises/Generators/House.cs | 2 +- .../Generators/KindergartenGarden.cs | 4 +- generators/Exercises/Generators/Matrix.cs | 5 +- generators/Exercises/Generators/Meetup.cs | 10 +- .../Exercises/Generators/NucleotideCount.cs | 2 +- .../Exercises/Generators/QueenAttack.cs | 5 +- .../Exercises/Generators/RailFenceCipher.cs | 3 +- .../Exercises/Generators/RationalNumbers.cs | 2 +- .../Exercises/Generators/RobotSimulator.cs | 4 +- .../Exercises/Generators/SaddlePoints.cs | 3 +- .../Exercises/Generators/SimpleCipher.cs | 5 +- generators/Exercises/Generators/SpaceAge.cs | 9 +- generators/Exercises/Generators/Tournament.cs | 2 +- generators/Exercises/Generators/Triangle.cs | 5 +- generators/Exercises/Generators/TwelveDays.cs | 2 +- generators/Exercises/Generators/TwoBucket.cs | 14 +- generators/Exercises/Generators/TwoFer.cs | 5 +- generators/Exercises/Generators/WordSearch.cs | 5 +- generators/Helpers/EnumerableExtensions.cs | 10 + generators/Output/Rendering/Render.cs | 4 +- generators/Output/Rendering/RenderDateTime.cs | 14 + .../Rendering/Templates/_TestClass.liquid | 2 +- generators/Output/TestClass.cs | 19 +- generators/Output/TestClassFile.cs | 20 - generators/Output/TestClassOutput.cs | 54 +++ generators/Output/TestMethod.cs | 199 +-------- generators/Output/TestMethodOutput.cs | 171 ++++++++ 46 files changed, 645 insertions(+), 575 deletions(-) create mode 100644 generators/Helpers/EnumerableExtensions.cs create mode 100644 generators/Output/Rendering/RenderDateTime.cs delete mode 100644 generators/Output/TestClassFile.cs create mode 100644 generators/Output/TestClassOutput.cs create mode 100644 generators/Output/TestMethodOutput.cs diff --git a/exercises/complex-numbers/ComplexNumbersTest.cs b/exercises/complex-numbers/ComplexNumbersTest.cs index 80343bd561..4774dc6204 100644 --- a/exercises/complex-numbers/ComplexNumbersTest.cs +++ b/exercises/complex-numbers/ComplexNumbersTest.cs @@ -52,8 +52,8 @@ public void Imaginary_unit() { var sut = new ComplexNumber(0, 1); var expected = new ComplexNumber(-1, 0); - Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(0, 1)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(0, 1)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(0, 1)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(0, 1)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -61,8 +61,8 @@ public void Add_purely_real_numbers() { var sut = new ComplexNumber(1, 0); var expected = new ComplexNumber(3, 0); - Assert.Equal(expected.Real(), sut.Add(new ComplexNumber(2, 0)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Add(new ComplexNumber(2, 0)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Add(new ComplexNumber(2, 0)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Add(new ComplexNumber(2, 0)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -70,8 +70,8 @@ public void Add_purely_imaginary_numbers() { var sut = new ComplexNumber(0, 1); var expected = new ComplexNumber(0, 3); - Assert.Equal(expected.Real(), sut.Add(new ComplexNumber(0, 2)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Add(new ComplexNumber(0, 2)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Add(new ComplexNumber(0, 2)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Add(new ComplexNumber(0, 2)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -79,8 +79,8 @@ public void Add_numbers_with_real_and_imaginary_part() { var sut = new ComplexNumber(1, 2); var expected = new ComplexNumber(4, 6); - Assert.Equal(expected.Real(), sut.Add(new ComplexNumber(3, 4)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Add(new ComplexNumber(3, 4)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Add(new ComplexNumber(3, 4)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Add(new ComplexNumber(3, 4)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -88,8 +88,8 @@ public void Subtract_purely_real_numbers() { var sut = new ComplexNumber(1, 0); var expected = new ComplexNumber(-1, 0); - Assert.Equal(expected.Real(), sut.Sub(new ComplexNumber(2, 0)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Sub(new ComplexNumber(2, 0)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Sub(new ComplexNumber(2, 0)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Sub(new ComplexNumber(2, 0)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -97,8 +97,8 @@ public void Subtract_purely_imaginary_numbers() { var sut = new ComplexNumber(0, 1); var expected = new ComplexNumber(0, -1); - Assert.Equal(expected.Real(), sut.Sub(new ComplexNumber(0, 2)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Sub(new ComplexNumber(0, 2)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Sub(new ComplexNumber(0, 2)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Sub(new ComplexNumber(0, 2)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -106,8 +106,8 @@ public void Subtract_numbers_with_real_and_imaginary_part() { var sut = new ComplexNumber(1, 2); var expected = new ComplexNumber(-2, -2); - Assert.Equal(expected.Real(), sut.Sub(new ComplexNumber(3, 4)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Sub(new ComplexNumber(3, 4)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Sub(new ComplexNumber(3, 4)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Sub(new ComplexNumber(3, 4)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -115,8 +115,8 @@ public void Multiply_purely_real_numbers() { var sut = new ComplexNumber(1, 0); var expected = new ComplexNumber(2, 0); - Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(2, 0)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(2, 0)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(2, 0)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(2, 0)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -124,8 +124,8 @@ public void Multiply_purely_imaginary_numbers() { var sut = new ComplexNumber(0, 1); var expected = new ComplexNumber(-2, 0); - Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(0, 2)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(0, 2)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(0, 2)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(0, 2)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -133,8 +133,8 @@ public void Multiply_numbers_with_real_and_imaginary_part() { var sut = new ComplexNumber(1, 2); var expected = new ComplexNumber(-5, 10); - Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(3, 4)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(3, 4)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Mul(new ComplexNumber(3, 4)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Mul(new ComplexNumber(3, 4)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -142,8 +142,8 @@ public void Divide_purely_real_numbers() { var sut = new ComplexNumber(1, 0); var expected = new ComplexNumber(0.5, 0); - Assert.Equal(expected.Real(), sut.Div(new ComplexNumber(2, 0)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Div(new ComplexNumber(2, 0)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Div(new ComplexNumber(2, 0)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Div(new ComplexNumber(2, 0)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -151,8 +151,8 @@ public void Divide_purely_imaginary_numbers() { var sut = new ComplexNumber(0, 1); var expected = new ComplexNumber(0.5, 0); - Assert.Equal(expected.Real(), sut.Div(new ComplexNumber(0, 2)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Div(new ComplexNumber(0, 2)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Div(new ComplexNumber(0, 2)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Div(new ComplexNumber(0, 2)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -160,8 +160,8 @@ public void Divide_numbers_with_real_and_imaginary_part() { var sut = new ComplexNumber(1, 2); var expected = new ComplexNumber(0.44, 0.08); - Assert.Equal(expected.Real(), sut.Div(new ComplexNumber(3, 4)).Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Div(new ComplexNumber(3, 4)).Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Div(new ComplexNumber(3, 4)).Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Div(new ComplexNumber(3, 4)).Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -204,8 +204,8 @@ public void Conjugate_a_purely_real_number() { var sut = new ComplexNumber(5, 0); var expected = new ComplexNumber(5, 0); - Assert.Equal(expected.Real(), sut.Conjugate().Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Conjugate().Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Conjugate().Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Conjugate().Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -213,8 +213,8 @@ public void Conjugate_a_purely_imaginary_number() { var sut = new ComplexNumber(0, 5); var expected = new ComplexNumber(0, -5); - Assert.Equal(expected.Real(), sut.Conjugate().Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Conjugate().Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Conjugate().Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Conjugate().Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -222,8 +222,8 @@ public void Conjugate_a_number_with_real_and_imaginary_part() { var sut = new ComplexNumber(1, 1); var expected = new ComplexNumber(1, -1); - Assert.Equal(expected.Real(), sut.Conjugate().Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Conjugate().Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Conjugate().Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Conjugate().Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -231,8 +231,8 @@ public void Eulers_identity_formula() { var sut = new ComplexNumber(0, Math.PI); var expected = new ComplexNumber(-1, 0); - Assert.Equal(expected.Real(), sut.Exp().Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Exp().Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Exp().Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Exp().Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -240,8 +240,8 @@ public void Exponential_of_0() { var sut = new ComplexNumber(0, 0); var expected = new ComplexNumber(1, 0); - Assert.Equal(expected.Real(), sut.Exp().Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Exp().Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Exp().Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Exp().Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -249,8 +249,8 @@ public void Exponential_of_a_purely_real_number() { var sut = new ComplexNumber(1, 0); var expected = new ComplexNumber(Math.E, 0); - Assert.Equal(expected.Real(), sut.Exp().Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Exp().Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Exp().Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Exp().Imaginary(), precision: 7); } [Fact(Skip = "Remove to run test")] @@ -258,7 +258,7 @@ public void Exponential_of_a_number_with_real_and_imaginary_part() { var sut = new ComplexNumber(Math.Log(2.0), Math.PI); var expected = new ComplexNumber(-2, 0); - Assert.Equal(expected.Real(), sut.Exp().Real(), precision: 15); - Assert.Equal(expected.Imaginary(), sut.Exp().Imaginary(), precision: 15); + Assert.Equal(expected.Real(), sut.Exp().Real(), precision: 7); + Assert.Equal(expected.Imaginary(), sut.Exp().Imaginary(), precision: 7); } } \ No newline at end of file diff --git a/exercises/meetup/MeetupTest.cs b/exercises/meetup/MeetupTest.cs index c6ac3b7b24..b0ceaf76e9 100644 --- a/exercises/meetup/MeetupTest.cs +++ b/exercises/meetup/MeetupTest.cs @@ -9,759 +9,759 @@ public class MeetupTest public void Monteenth_of_may_2013() { var sut = new Meetup(5, 2013); - var expected = "2013-05-13"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 5, 13); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Monteenth_of_august_2013() { var sut = new Meetup(8, 2013); - var expected = "2013-08-19"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 8, 19); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Monteenth_of_september_2013() { var sut = new Meetup(9, 2013); - var expected = "2013-09-16"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 9, 16); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Tuesteenth_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-19"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 19); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Tuesteenth_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-16"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 16); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Tuesteenth_of_august_2013() { var sut = new Meetup(8, 2013); - var expected = "2013-08-13"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 8, 13); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Wednesteenth_of_january_2013() { var sut = new Meetup(1, 2013); - var expected = "2013-01-16"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 1, 16); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Wednesteenth_of_february_2013() { var sut = new Meetup(2, 2013); - var expected = "2013-02-13"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 2, 13); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Wednesteenth_of_june_2013() { var sut = new Meetup(6, 2013); - var expected = "2013-06-19"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 6, 19); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Thursteenth_of_may_2013() { var sut = new Meetup(5, 2013); - var expected = "2013-05-16"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 5, 16); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Thursteenth_of_june_2013() { var sut = new Meetup(6, 2013); - var expected = "2013-06-13"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 6, 13); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Thursteenth_of_september_2013() { var sut = new Meetup(9, 2013); - var expected = "2013-09-19"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 9, 19); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Friteenth_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-19"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 19); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Friteenth_of_august_2013() { var sut = new Meetup(8, 2013); - var expected = "2013-08-16"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 8, 16); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Friteenth_of_september_2013() { var sut = new Meetup(9, 2013); - var expected = "2013-09-13"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 9, 13); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Saturteenth_of_february_2013() { var sut = new Meetup(2, 2013); - var expected = "2013-02-16"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 2, 16); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Saturteenth_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-13"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 13); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Saturteenth_of_october_2013() { var sut = new Meetup(10, 2013); - var expected = "2013-10-19"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 10, 19); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Sunteenth_of_may_2013() { var sut = new Meetup(5, 2013); - var expected = "2013-05-19"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 5, 19); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Sunteenth_of_june_2013() { var sut = new Meetup(6, 2013); - var expected = "2013-06-16"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 6, 16); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void Sunteenth_of_october_2013() { var sut = new Meetup(10, 2013); - var expected = "2013-10-13"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Teenth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 10, 13); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Teenth)); } [Fact(Skip = "Remove to run test")] public void First_monday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-04"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 4); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_monday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-01"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 1); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_tuesday_of_may_2013() { var sut = new Meetup(5, 2013); - var expected = "2013-05-07"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 5, 7); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_tuesday_of_june_2013() { var sut = new Meetup(6, 2013); - var expected = "2013-06-04"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 6, 4); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_wednesday_of_july_2013() { var sut = new Meetup(7, 2013); - var expected = "2013-07-03"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 7, 3); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_wednesday_of_august_2013() { var sut = new Meetup(8, 2013); - var expected = "2013-08-07"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 8, 7); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_thursday_of_september_2013() { var sut = new Meetup(9, 2013); - var expected = "2013-09-05"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 9, 5); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_thursday_of_october_2013() { var sut = new Meetup(10, 2013); - var expected = "2013-10-03"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 10, 3); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_friday_of_november_2013() { var sut = new Meetup(11, 2013); - var expected = "2013-11-01"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 11, 1); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_friday_of_december_2013() { var sut = new Meetup(12, 2013); - var expected = "2013-12-06"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 12, 6); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_saturday_of_january_2013() { var sut = new Meetup(1, 2013); - var expected = "2013-01-05"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 1, 5); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_saturday_of_february_2013() { var sut = new Meetup(2, 2013); - var expected = "2013-02-02"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 2, 2); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_sunday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-03"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 3); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void First_sunday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-07"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 7); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.First)); } [Fact(Skip = "Remove to run test")] public void Second_monday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-11"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 11); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_monday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-08"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 8); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_tuesday_of_may_2013() { var sut = new Meetup(5, 2013); - var expected = "2013-05-14"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 5, 14); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_tuesday_of_june_2013() { var sut = new Meetup(6, 2013); - var expected = "2013-06-11"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 6, 11); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_wednesday_of_july_2013() { var sut = new Meetup(7, 2013); - var expected = "2013-07-10"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 7, 10); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_wednesday_of_august_2013() { var sut = new Meetup(8, 2013); - var expected = "2013-08-14"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 8, 14); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_thursday_of_september_2013() { var sut = new Meetup(9, 2013); - var expected = "2013-09-12"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 9, 12); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_thursday_of_october_2013() { var sut = new Meetup(10, 2013); - var expected = "2013-10-10"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 10, 10); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_friday_of_november_2013() { var sut = new Meetup(11, 2013); - var expected = "2013-11-08"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 11, 8); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_friday_of_december_2013() { var sut = new Meetup(12, 2013); - var expected = "2013-12-13"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 12, 13); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_saturday_of_january_2013() { var sut = new Meetup(1, 2013); - var expected = "2013-01-12"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 1, 12); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_saturday_of_february_2013() { var sut = new Meetup(2, 2013); - var expected = "2013-02-09"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 2, 9); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_sunday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-10"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 10); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Second_sunday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-14"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Second).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 14); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Second)); } [Fact(Skip = "Remove to run test")] public void Third_monday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-18"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 18); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_monday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-15"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 15); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_tuesday_of_may_2013() { var sut = new Meetup(5, 2013); - var expected = "2013-05-21"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 5, 21); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_tuesday_of_june_2013() { var sut = new Meetup(6, 2013); - var expected = "2013-06-18"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 6, 18); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_wednesday_of_july_2013() { var sut = new Meetup(7, 2013); - var expected = "2013-07-17"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 7, 17); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_wednesday_of_august_2013() { var sut = new Meetup(8, 2013); - var expected = "2013-08-21"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 8, 21); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_thursday_of_september_2013() { var sut = new Meetup(9, 2013); - var expected = "2013-09-19"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 9, 19); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_thursday_of_october_2013() { var sut = new Meetup(10, 2013); - var expected = "2013-10-17"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 10, 17); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_friday_of_november_2013() { var sut = new Meetup(11, 2013); - var expected = "2013-11-15"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 11, 15); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_friday_of_december_2013() { var sut = new Meetup(12, 2013); - var expected = "2013-12-20"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 12, 20); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_saturday_of_january_2013() { var sut = new Meetup(1, 2013); - var expected = "2013-01-19"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 1, 19); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_saturday_of_february_2013() { var sut = new Meetup(2, 2013); - var expected = "2013-02-16"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 2, 16); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_sunday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-17"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 17); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Third_sunday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-21"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Third).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 21); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Third)); } [Fact(Skip = "Remove to run test")] public void Fourth_monday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-25"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 25); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_monday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-22"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 22); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_tuesday_of_may_2013() { var sut = new Meetup(5, 2013); - var expected = "2013-05-28"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 5, 28); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_tuesday_of_june_2013() { var sut = new Meetup(6, 2013); - var expected = "2013-06-25"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 6, 25); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_wednesday_of_july_2013() { var sut = new Meetup(7, 2013); - var expected = "2013-07-24"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 7, 24); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_wednesday_of_august_2013() { var sut = new Meetup(8, 2013); - var expected = "2013-08-28"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 8, 28); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_thursday_of_september_2013() { var sut = new Meetup(9, 2013); - var expected = "2013-09-26"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 9, 26); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_thursday_of_october_2013() { var sut = new Meetup(10, 2013); - var expected = "2013-10-24"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 10, 24); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_friday_of_november_2013() { var sut = new Meetup(11, 2013); - var expected = "2013-11-22"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 11, 22); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_friday_of_december_2013() { var sut = new Meetup(12, 2013); - var expected = "2013-12-27"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 12, 27); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_saturday_of_january_2013() { var sut = new Meetup(1, 2013); - var expected = "2013-01-26"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 1, 26); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_saturday_of_february_2013() { var sut = new Meetup(2, 2013); - var expected = "2013-02-23"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 2, 23); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_sunday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-24"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 24); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Fourth_sunday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-28"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Fourth).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 28); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Fourth)); } [Fact(Skip = "Remove to run test")] public void Last_monday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-25"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 25); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_monday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-29"; - Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 29); + Assert.Equal(expected, sut.Day(DayOfWeek.Monday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_tuesday_of_may_2013() { var sut = new Meetup(5, 2013); - var expected = "2013-05-28"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 5, 28); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_tuesday_of_june_2013() { var sut = new Meetup(6, 2013); - var expected = "2013-06-25"; - Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 6, 25); + Assert.Equal(expected, sut.Day(DayOfWeek.Tuesday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_wednesday_of_july_2013() { var sut = new Meetup(7, 2013); - var expected = "2013-07-31"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 7, 31); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_wednesday_of_august_2013() { var sut = new Meetup(8, 2013); - var expected = "2013-08-28"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 8, 28); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_thursday_of_september_2013() { var sut = new Meetup(9, 2013); - var expected = "2013-09-26"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 9, 26); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_thursday_of_october_2013() { var sut = new Meetup(10, 2013); - var expected = "2013-10-31"; - Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 10, 31); + Assert.Equal(expected, sut.Day(DayOfWeek.Thursday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_friday_of_november_2013() { var sut = new Meetup(11, 2013); - var expected = "2013-11-29"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 11, 29); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_friday_of_december_2013() { var sut = new Meetup(12, 2013); - var expected = "2013-12-27"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 12, 27); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_saturday_of_january_2013() { var sut = new Meetup(1, 2013); - var expected = "2013-01-26"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 1, 26); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_saturday_of_february_2013() { var sut = new Meetup(2, 2013); - var expected = "2013-02-23"; - Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 2, 23); + Assert.Equal(expected, sut.Day(DayOfWeek.Saturday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_sunday_of_march_2013() { var sut = new Meetup(3, 2013); - var expected = "2013-03-31"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 3, 31); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_sunday_of_april_2013() { var sut = new Meetup(4, 2013); - var expected = "2013-04-28"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2013, 4, 28); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_wednesday_of_february_2012() { var sut = new Meetup(2, 2012); - var expected = "2012-02-29"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2012, 2, 29); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_wednesday_of_december_2014() { var sut = new Meetup(12, 2014); - var expected = "2014-12-31"; - Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2014, 12, 31); + Assert.Equal(expected, sut.Day(DayOfWeek.Wednesday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void Last_sunday_of_february_2015() { var sut = new Meetup(2, 2015); - var expected = "2015-02-22"; - Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Last).ToString("yyyy-MM-dd")); + var expected = new DateTime(2015, 2, 22); + Assert.Equal(expected, sut.Day(DayOfWeek.Sunday, Schedule.Last)); } [Fact(Skip = "Remove to run test")] public void First_friday_of_december_2012() { var sut = new Meetup(12, 2012); - var expected = "2012-12-07"; - Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.First).ToString("yyyy-MM-dd")); + var expected = new DateTime(2012, 12, 7); + Assert.Equal(expected, sut.Day(DayOfWeek.Friday, Schedule.First)); } } \ No newline at end of file diff --git a/exercises/rational-numbers/RationalNumbersTest.cs b/exercises/rational-numbers/RationalNumbersTest.cs index b7325b11b2..6f7ea79e63 100644 --- a/exercises/rational-numbers/RationalNumbersTest.cs +++ b/exercises/rational-numbers/RationalNumbersTest.cs @@ -169,19 +169,19 @@ public void Raise_a_negative_rational_number_to_the_power_of_zero() [Fact(Skip = "Remove to run test")] public void Raise_a_real_number_to_a_positive_rational_number() { - Assert.Equal(16, 8.Expreal(new RationalNumber(4, 3)), 0); + Assert.Equal(16, 8.Expreal(new RationalNumber(4, 3)), precision: 0); } [Fact(Skip = "Remove to run test")] public void Raise_a_real_number_to_a_negative_rational_number() { - Assert.Equal(0.3333333, 9.Expreal(new RationalNumber(-1, 2)), 7); + Assert.Equal(0.3333333, 9.Expreal(new RationalNumber(-1, 2)), precision: 7); } [Fact(Skip = "Remove to run test")] public void Raise_a_real_number_to_a_zero_rational_number() { - Assert.Equal(1, 2.Expreal(new RationalNumber(0, 1)), 0); + Assert.Equal(1, 2.Expreal(new RationalNumber(0, 1)), precision: 0); } [Fact(Skip = "Remove to run test")] diff --git a/exercises/two-bucket/TwoBucketTest.cs b/exercises/two-bucket/TwoBucketTest.cs index bc37231661..5b0035a860 100644 --- a/exercises/two-bucket/TwoBucketTest.cs +++ b/exercises/two-bucket/TwoBucketTest.cs @@ -8,59 +8,59 @@ public class TwoBucketTest public void Measure_using_bucket_one_of_size_3_and_bucket_two_of_size_5_start_with_bucket_one() { var sut = new TwoBucket(3, 5, Bucket.One); - var result = sut.Measure(1); - Assert.Equal(4, result.Moves); - Assert.Equal(5, result.OtherBucket); - Assert.Equal(Bucket.One, result.GoalBucket); + var actual = sut.Measure(1); + Assert.Equal(4, actual.Moves); + Assert.Equal(5, actual.OtherBucket); + Assert.Equal(Bucket.One, actual.GoalBucket); } [Fact(Skip = "Remove to run test")] public void Measure_using_bucket_one_of_size_3_and_bucket_two_of_size_5_start_with_bucket_two() { var sut = new TwoBucket(3, 5, Bucket.Two); - var result = sut.Measure(1); - Assert.Equal(8, result.Moves); - Assert.Equal(3, result.OtherBucket); - Assert.Equal(Bucket.Two, result.GoalBucket); + var actual = sut.Measure(1); + Assert.Equal(8, actual.Moves); + Assert.Equal(3, actual.OtherBucket); + Assert.Equal(Bucket.Two, actual.GoalBucket); } [Fact(Skip = "Remove to run test")] public void Measure_using_bucket_one_of_size_7_and_bucket_two_of_size_11_start_with_bucket_one() { var sut = new TwoBucket(7, 11, Bucket.One); - var result = sut.Measure(2); - Assert.Equal(14, result.Moves); - Assert.Equal(11, result.OtherBucket); - Assert.Equal(Bucket.One, result.GoalBucket); + var actual = sut.Measure(2); + Assert.Equal(14, actual.Moves); + Assert.Equal(11, actual.OtherBucket); + Assert.Equal(Bucket.One, actual.GoalBucket); } [Fact(Skip = "Remove to run test")] public void Measure_using_bucket_one_of_size_7_and_bucket_two_of_size_11_start_with_bucket_two() { var sut = new TwoBucket(7, 11, Bucket.Two); - var result = sut.Measure(2); - Assert.Equal(18, result.Moves); - Assert.Equal(7, result.OtherBucket); - Assert.Equal(Bucket.Two, result.GoalBucket); + var actual = sut.Measure(2); + Assert.Equal(18, actual.Moves); + Assert.Equal(7, actual.OtherBucket); + Assert.Equal(Bucket.Two, actual.GoalBucket); } [Fact(Skip = "Remove to run test")] public void Measure_one_step_using_bucket_one_of_size_1_and_bucket_two_of_size_3_start_with_bucket_two() { var sut = new TwoBucket(1, 3, Bucket.Two); - var result = sut.Measure(3); - Assert.Equal(1, result.Moves); - Assert.Equal(0, result.OtherBucket); - Assert.Equal(Bucket.Two, result.GoalBucket); + var actual = sut.Measure(3); + Assert.Equal(1, actual.Moves); + Assert.Equal(0, actual.OtherBucket); + Assert.Equal(Bucket.Two, actual.GoalBucket); } [Fact(Skip = "Remove to run test")] public void Measure_using_bucket_one_of_size_2_and_bucket_two_of_size_3_start_with_bucket_one_and_end_with_bucket_two() { var sut = new TwoBucket(2, 3, Bucket.One); - var result = sut.Measure(3); - Assert.Equal(2, result.Moves); - Assert.Equal(2, result.OtherBucket); - Assert.Equal(Bucket.Two, result.GoalBucket); + var actual = sut.Measure(3); + Assert.Equal(2, actual.Moves); + Assert.Equal(2, actual.OtherBucket); + Assert.Equal(Bucket.Two, actual.GoalBucket); } } \ No newline at end of file diff --git a/generators/Exercises/GeneratorExercise.cs b/generators/Exercises/GeneratorExercise.cs index 78cbd70acc..79a4b1389c 100644 --- a/generators/Exercises/GeneratorExercise.cs +++ b/generators/Exercises/GeneratorExercise.cs @@ -16,21 +16,21 @@ public abstract class GeneratorExercise : Exercise public void Regenerate(CanonicalData canonicalData) { var testClass = CreateTestClass(canonicalData); - TestClassFile.Write(testClass); + var testClassOutput = new TestClassOutput(testClass); + testClassOutput.WriteToFile(); } private TestClass CreateTestClass(CanonicalData canonicalData) { var testMethods = CreateTestMethods(canonicalData); - var testClass = new TestClass - { - Exercise = canonicalData.Exercise, - CanonicalDataVersion = canonicalData.Version, - ClassName = canonicalData.Exercise.ToTestClassName(), - Methods = testMethods.Select(testMethod => testMethod.Render()).ToList(), - Namespaces = GetNamespaces(testMethods) - }; + var testClass = new TestClass( + exercise: canonicalData.Exercise, + version: canonicalData.Version, + className: canonicalData.Exercise.ToTestClassName(), + testMethods: testMethods + ); UpdateTestClass(testClass); + UpdateNamespaces(testClass.Namespaces); return testClass; } @@ -39,20 +39,6 @@ protected virtual void UpdateTestClass(TestClass testClass) { } - private ISet GetNamespaces(IEnumerable testMethods) - { - var exceptionNamespaces = testMethods - .Where(x => x.ExceptionThrown != null) - .Select(x => x.ExceptionThrown.Namespace); - - var defaultNamespaces = new[] { "Xunit" }; - - var namespaces = new SortedSet(defaultNamespaces.Concat(exceptionNamespaces)); - UpdateNamespaces(namespaces); - - return namespaces; - } - protected virtual void UpdateNamespaces(ISet namespaces) { } diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index ac081de98e..733fec8c1e 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -12,7 +12,8 @@ protected override void UpdateTestMethod(TestMethod testMethod) else if (testMethod.Property == "list") testMethod.UseVariableForExpected = true; - testMethod.SetConstructorInputParameters("score"); + testMethod.ConstructorInputParameters = new[] { "score" }; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; testMethod.Assert = RenderAssert(testMethod); } diff --git a/generators/Exercises/Generators/Anagram.cs b/generators/Exercises/Generators/Anagram.cs index d48feb1730..f440f935c1 100644 --- a/generators/Exercises/Generators/Anagram.cs +++ b/generators/Exercises/Generators/Anagram.cs @@ -8,7 +8,8 @@ protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.UseVariablesForInput = true; testMethod.UseVariableForExpected = true; - testMethod.SetConstructorInputParameters("subject"); + testMethod.ConstructorInputParameters = new[] { "subject" }; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/BinarySearch.cs b/generators/Exercises/Generators/BinarySearch.cs index f0dfdbf57c..6bc64c29e5 100644 --- a/generators/Exercises/Generators/BinarySearch.cs +++ b/generators/Exercises/Generators/BinarySearch.cs @@ -11,8 +11,9 @@ protected override void UpdateTestMethod(TestMethod testMethod) { if (testMethod.Input["array"] is JArray) testMethod.Input["array"] = Array.Empty(); - - testMethod.SetConstructorInputParameters("array"); + + testMethod.ConstructorInputParameters = new[] { "array" }; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; testMethod.UseVariablesForConstructorParameters = true; } diff --git a/generators/Exercises/Generators/BookStore.cs b/generators/Exercises/Generators/BookStore.cs index 2c55fa45bb..46e65ac027 100644 --- a/generators/Exercises/Generators/BookStore.cs +++ b/generators/Exercises/Generators/BookStore.cs @@ -13,7 +13,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.Input["basket"] = Array.Empty(); testMethod.Expected = testMethod.Expected / 100.0f; - testMethod.SetInputParameters("basket"); + testMethod.InputParameters = new[] { "basket" }; testMethod.UseVariablesForInput = true; } diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index 37583a1039..0a4454d6ce 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -16,7 +16,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) else testMethod.ExceptionThrown = typeof(ArgumentException); - testMethod.SetInputParameters(); + testMethod.InputParameters = Array.Empty(); testMethod.Arrange = RenderArrange(testMethod); testMethod.Act = RenderAct(testMethod); @@ -79,7 +79,7 @@ protected override void UpdateTestClass(TestClass testClass) private static void AddDoRollMethod(TestClass testClass) { - testClass.Methods.Add(@" + testClass.AdditionalMethods.Add(@" public void DoRoll(IEnumerable rolls, BowlingGame sut) { foreach (var roll in rolls) diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 60a95f7782..3434b282af 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -14,9 +14,10 @@ public class Clock : GeneratorExercise private const string PropertyEqual = "equal"; protected override void UpdateTestMethod(TestMethod testMethod) - { - testMethod.SetConstructorInputParameters(ParamHour, ParamMinute); - + { + testMethod.ConstructorInputParameters = new[] { ParamHour, ParamMinute }; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + if (testMethod.Property == PropertyEqual) { var clock1 = testMethod.Input[ParamClock1]; @@ -52,7 +53,7 @@ private string RenderAssert(TestMethod testMethod) } private string RenderConsistencyToAssert(TestMethod testMethod) - => Render.AssertEqual(testMethod.ExpectedParameter, $"{testMethod.TestedValue}.ToString()"); + => Render.AssertEqual(Render.Object(testMethod.Expected), $"sut.{testMethod.TestedMethod}({testMethod.Input["value"]}).ToString()"); private string RenderEqualToAssert(TestMethod testMethod) { diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index 6f874fb9d2..560e00d5ad 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -13,6 +13,8 @@ public class ComplexNumbers : GeneratorExercise protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.TestedClass = "ComplexNumber"; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + testMethod.UseVariableForExpected = IsComplexNumber(testMethod.Expected); testMethod.Expected = ConvertToType(testMethod.Expected); @@ -20,8 +22,8 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.Input["real"] = ConvertToDouble(testMethod.Input[constructorParamName][0]); testMethod.Input["imaginary"] = ConvertToDouble(testMethod.Input[constructorParamName][1]); - testMethod.SetInputParameters(GetInputParameters(testMethod, constructorParamName)); - testMethod.SetConstructorInputParameters("real", "imaginary"); + testMethod.InputParameters = GetInputParameters(testMethod, constructorParamName); + testMethod.ConstructorInputParameters = new[] {"real", "imaginary"}; var keys = testMethod.Input.Keys.ToArray(); @@ -41,9 +43,12 @@ private string RenderAssert(TestMethod testMethod) private string RenderComplexNumberAssert(TestMethod testMethod) { + var inputParameters = testMethod.Input.ContainsKey("z") ? "" : Render.Object(testMethod.Input["z2"]); + var actual = $"sut.{testMethod.TestedMethod}({inputParameters})"; + var assert = new StringBuilder(); - assert.AppendLine(Render.AssertEqualWithin($"{testMethod.ExpectedParameter}.Real()", $"{testMethod.TestedValue}.Real()", 15)); - assert.AppendLine(Render.AssertEqualWithin($"{testMethod.ExpectedParameter}.Imaginary()", $"{testMethod.TestedValue}.Imaginary()", 15)); + assert.AppendLine(Render.AssertEqualWithin("expected.Real()", $"{actual}.Real()", 7)); + assert.AppendLine(Render.AssertEqualWithin("expected.Imaginary()", $"{actual}.Imaginary()", 7)); return assert.ToString(); } @@ -55,9 +60,12 @@ protected override void UpdateNamespaces(ISet namespaces) private object ConvertToType(dynamic rawValue) => IsComplexNumber(rawValue) - ? new UnescapedValue($"new ComplexNumber({Render.Object(ConvertToDouble(rawValue[0]))}, {Render.Object(ConvertToDouble(rawValue[1]))})") + ? RenderComplexNumber(rawValue) : rawValue; + private UnescapedValue RenderComplexNumber(dynamic rawValue) + => new UnescapedValue($"new ComplexNumber({Render.Object(ConvertToDouble(rawValue[0]))}, {Render.Object(ConvertToDouble(rawValue[1]))})"); + private static bool IsComplexNumber(object rawValue) => rawValue is int[] || rawValue is double[] || rawValue is float[] || rawValue is JArray; private static object ConvertToDouble(dynamic value) diff --git a/generators/Exercises/Generators/Connect.cs b/generators/Exercises/Generators/Connect.cs index 09e5d28b54..a329736ebe 100644 --- a/generators/Exercises/Generators/Connect.cs +++ b/generators/Exercises/Generators/Connect.cs @@ -8,7 +8,8 @@ public class Connect : GeneratorExercise protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.UseVariablesForConstructorParameters = true; - testMethod.SetConstructorInputParameters("board"); + testMethod.ConstructorInputParameters = new[] { "board" }; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; testMethod.TestedMethod = "Result"; testMethod.Input["board"] = new UnescapedValue(Render.ArrayMultiLine(testMethod.Input["board"])); diff --git a/generators/Exercises/Generators/CustomSet.cs b/generators/Exercises/Generators/CustomSet.cs index e1f60ea8f5..101c05cbc3 100644 --- a/generators/Exercises/Generators/CustomSet.cs +++ b/generators/Exercises/Generators/CustomSet.cs @@ -9,6 +9,7 @@ public class CustomSet : GeneratorExercise protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.UseVariablesForInput = true; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; if (testMethod.Input.ContainsKey("set")) { @@ -17,7 +18,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.Input["set"] = new UnescapedValue(""); } - testMethod.SetConstructorInputParameters("set"); + testMethod.ConstructorInputParameters = new[] { "set" }; } else { @@ -26,7 +27,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.Input["set1"] = new UnescapedValue(""); } - testMethod.SetConstructorInputParameters("set1"); + testMethod.ConstructorInputParameters = new[] { "set1" }; testMethod.Input["set2"] = ConvertCustomSet(testMethod.Input["set2"]); if (testMethod.Property == "equal") diff --git a/generators/Exercises/Generators/Etl.cs b/generators/Exercises/Generators/Etl.cs index db1863000b..a47abab7a0 100644 --- a/generators/Exercises/Generators/Etl.cs +++ b/generators/Exercises/Generators/Etl.cs @@ -11,19 +11,19 @@ protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.UseVariablesForInput = true; testMethod.UseVariableForExpected = true; - testMethod.Input = ConvertInput(testMethod.Input); + + var input = ConvertInput(testMethod.Input); + testMethod.Input.Clear(); + testMethod.Input["input"] = input; testMethod.Expected = ConvertExpected(testMethod.Expected); - testMethod.SetInputParameters("input"); + testMethod.InputParameters = new[] { "input" }; } private static dynamic ConvertExpected(dynamic expected) => ((Dictionary)expected).ToDictionary(kv => kv.Key, kv => Convert.ToInt32(kv.Value)); - private static IDictionary ConvertInput(IDictionary input) - => new Dictionary - { - ["input"] = input.ToDictionary(kv => Convert.ToInt32(kv.Key), kv => (string[])kv.Value) - }; + private static IDictionary ConvertInput(IDictionary input) + => input.ToDictionary(kv => Convert.ToInt32(kv.Key), kv => (string[]) kv.Value); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/FoodChain.cs b/generators/Exercises/Generators/FoodChain.cs index a3e93cc46b..511e74136a 100644 --- a/generators/Exercises/Generators/FoodChain.cs +++ b/generators/Exercises/Generators/FoodChain.cs @@ -12,7 +12,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) if (testMethod.Input["startVerse"] == testMethod.Input["endVerse"]) { - testMethod.SetInputParameters("startVerse"); + testMethod.InputParameters = new[] { "startVerse" }; } } } diff --git a/generators/Exercises/Generators/Gigasecond.cs b/generators/Exercises/Generators/Gigasecond.cs index d329460901..89b931197b 100644 --- a/generators/Exercises/Generators/Gigasecond.cs +++ b/generators/Exercises/Generators/Gigasecond.cs @@ -9,16 +9,7 @@ public class Gigasecond : GeneratorExercise { protected override void UpdateTestMethod(TestMethod testMethod) { - var input = DateTime.Parse(testMethod.Input["birthdate"].ToString()); - testMethod.Input["birthdate"] = new UnescapedValue(RenderDateTime(input)); - testMethod.Expected = new UnescapedValue(RenderDateTime((DateTime)testMethod.Expected)); - } - - private static string RenderDateTime(DateTime dateTime) - { - return dateTime.Hour == 0 && dateTime.Minute == 0 && dateTime.Second == 0 - ? $"new DateTime({dateTime.Year}, {dateTime.Month}, {dateTime.Day})" - : $"new DateTime({dateTime.Year}, {dateTime.Month}, {dateTime.Day}, {dateTime.Hour}, {dateTime.Minute}, {dateTime.Second})"; + testMethod.Input["birthdate"] = DateTime.Parse(testMethod.Input["birthdate"].ToString()); } protected override void UpdateNamespaces(ISet namespaces) diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index 0a207c0966..afeb74e462 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -18,12 +18,13 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.UseVariableForTested = true; testMethod.Input["board"] = new MultiLineString(testMethod.Input["board"]); - testMethod.SetConstructorInputParameters("board"); + testMethod.ConstructorInputParameters = new[] { "board" }; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; if (testMethod.Property == "territory") { testMethod.Input["coordinate"] = (testMethod.Input["x"], testMethod.Input["y"]); - testMethod.SetInputParameters("coordinate"); + testMethod.InputParameters = new[] {"coordinate"}; if (testMethod.Expected.ContainsKey("error")) { diff --git a/generators/Exercises/Generators/Grep.cs b/generators/Exercises/Generators/Grep.cs index 4ce1f5ff8d..54616f7a22 100644 --- a/generators/Exercises/Generators/Grep.cs +++ b/generators/Exercises/Generators/Grep.cs @@ -38,7 +38,7 @@ private static void AddAdditionalMethods(TestClass testClass) private static void AddIliadData(TestClass testClass) { - testClass.Methods.Add(@" + testClass.AdditionalMethods.Add(@" private const string IliadFileName = ""iliad.txt""; private const string IliadContents = ""Achilles sing, O Goddess! Peleus' son;\n"" + @@ -54,7 +54,7 @@ private static void AddIliadData(TestClass testClass) private static void AddMidsummerNightData(TestClass testClass) { - testClass.Methods.Add(@" + testClass.AdditionalMethods.Add(@" private const string MidsummerNightFileName = ""midsummer-night.txt""; private const string MidsummerNightContents = ""I do entreat your grace to pardon me.\n"" + @@ -68,7 +68,7 @@ private static void AddMidsummerNightData(TestClass testClass) private static void AddParadiseLostData(TestClass testClass) { - testClass.Methods.Add(@" + testClass.AdditionalMethods.Add(@" private const string ParadiseLostFileName = ""paradise-lost.txt""; private const string ParadiseLostContents = ""Of Mans First Disobedience, and the Fruit\n"" + @@ -83,7 +83,7 @@ private static void AddParadiseLostData(TestClass testClass) private static void AddConstructor(TestClass testClass) { - testClass.Methods.Add(@" + testClass.AdditionalMethods.Add(@" public GrepTest() { Directory.SetCurrentDirectory(Path.GetTempPath()); @@ -95,7 +95,7 @@ public GrepTest() private static void AddDisposeMethod(TestClass testClass) { - testClass.Methods.Add(@" + testClass.AdditionalMethods.Add(@" public void Dispose() { Directory.SetCurrentDirectory(Path.GetTempPath()); diff --git a/generators/Exercises/Generators/House.cs b/generators/Exercises/Generators/House.cs index 5442f8232e..f3421a932b 100644 --- a/generators/Exercises/Generators/House.cs +++ b/generators/Exercises/Generators/House.cs @@ -12,7 +12,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) if (testMethod.Input["startVerse"] == testMethod.Input["endVerse"]) { - testMethod.SetInputParameters("startVerse"); + testMethod.InputParameters = new[] { "startVerse" }; } } } diff --git a/generators/Exercises/Generators/KindergartenGarden.cs b/generators/Exercises/Generators/KindergartenGarden.cs index d6d5785c29..0207ac9ce6 100644 --- a/generators/Exercises/Generators/KindergartenGarden.cs +++ b/generators/Exercises/Generators/KindergartenGarden.cs @@ -13,9 +13,9 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.TestMethodName = testMethod.TestMethodNameWithPath; if (testMethod.Input.ContainsKey("students")) - testMethod.SetConstructorInputParameters("diagram", "students"); + testMethod.ConstructorInputParameters = new[] { "diagram", "students" }; else - testMethod.SetConstructorInputParameters("diagram"); + testMethod.ConstructorInputParameters = new[] { "diagram" }; testMethod.Expected = ConvertExpected(testMethod.Expected); } diff --git a/generators/Exercises/Generators/Matrix.cs b/generators/Exercises/Generators/Matrix.cs index 16357039e3..62e2689250 100644 --- a/generators/Exercises/Generators/Matrix.cs +++ b/generators/Exercises/Generators/Matrix.cs @@ -6,8 +6,9 @@ public class Matrix : GeneratorExercise { protected override void UpdateTestMethod(TestMethod testMethod) { - testMethod.SetConstructorInputParameters("string"); - testMethod.SetInputParameters("index"); + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + testMethod.ConstructorInputParameters = new[] { "string" }; + testMethod.InputParameters = new[] { "index" }; } } } diff --git a/generators/Exercises/Generators/Meetup.cs b/generators/Exercises/Generators/Meetup.cs index c488431bc0..d8f7fff918 100644 --- a/generators/Exercises/Generators/Meetup.cs +++ b/generators/Exercises/Generators/Meetup.cs @@ -16,21 +16,19 @@ public class Meetup : GeneratorExercise protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.TestedMethod = PropertyDay; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; testMethod.UseVariableForExpected = true; - testMethod.SetConstructorInputParameters(ParamMonth, ParamYear); - testMethod.SetInputParameters(ParamDayOfWeek, ParamWeek); + testMethod.ConstructorInputParameters = new[] { ParamMonth, ParamYear }; + testMethod.InputParameters = new[] { ParamDayOfWeek, ParamWeek }; testMethod.Input[ParamYear] = testMethod.Input[ParamYear]; testMethod.Input[ParamMonth] = testMethod.Input[ParamMonth]; testMethod.Input[ParamWeek] = Render.Enum("Schedule", testMethod.Input[ParamWeek]); testMethod.Input[ParamDayOfWeek] = Render.Enum("DayOfWeek", testMethod.Input[ParamDayOfWeek]); - testMethod.Assert = RenderAssert(testMethod); + testMethod.Expected = DateTime.Parse(testMethod.Expected); } - private string RenderAssert(TestMethod testMethod) - => Render.AssertEqual(testMethod.ExpectedParameter, $"{testMethod.TestedValue}.ToString(\"yyyy-MM-dd\")"); - protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(DayOfWeek).Namespace); diff --git a/generators/Exercises/Generators/NucleotideCount.cs b/generators/Exercises/Generators/NucleotideCount.cs index 28b027f277..d7966717ea 100644 --- a/generators/Exercises/Generators/NucleotideCount.cs +++ b/generators/Exercises/Generators/NucleotideCount.cs @@ -21,7 +21,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) } testMethod.UseVariableForExpected = true; - testMethod.SetConstructorInputParameters("strand"); + testMethod.ConstructorInputParameters = new[] { "strand" }; } private static dynamic ConvertExpected(dynamic expected) diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index ad8becd1e6..5db937fb01 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -24,9 +24,8 @@ protected override void UpdateTestMethod(TestMethod testMethod) var coordinates = GetCoordinatesFromPosition(testMethod.Input["queen"]); testMethod.Input["X"] = coordinates.Item1; testMethod.Input["Y"] = coordinates.Item2; - - testMethod.SetInputParameters("X", "Y"); - + + testMethod.InputParameters = new[] { "X", "Y" }; return; } diff --git a/generators/Exercises/Generators/RailFenceCipher.cs b/generators/Exercises/Generators/RailFenceCipher.cs index c281b4fc2c..f875148e7b 100644 --- a/generators/Exercises/Generators/RailFenceCipher.cs +++ b/generators/Exercises/Generators/RailFenceCipher.cs @@ -8,7 +8,8 @@ protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.UseVariablesForInput = true; testMethod.UseVariableForExpected = true; - testMethod.SetConstructorInputParameters("rails"); + testMethod.ConstructorInputParameters = new[] { "rails" }; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/RationalNumbers.cs b/generators/Exercises/Generators/RationalNumbers.cs index 114664878a..f775e8f78f 100644 --- a/generators/Exercises/Generators/RationalNumbers.cs +++ b/generators/Exercises/Generators/RationalNumbers.cs @@ -28,7 +28,7 @@ private string RenderAssert(TestMethod testMethod) case "exprational": return Render.AssertEqual(RenderRationalNumber(testMethod.Expected), $"{RenderRationalNumber(testMethod.Input["r"])}.{testMethod.TestedMethod}({testMethod.Input["n"]})"); case "expreal": - return Render.AssertEqual(testMethod.ExpectedParameter, $"{testMethod.Input["x"]}.{testMethod.TestedMethod}({RenderRationalNumber(testMethod.Input["r"])}), {Precision(testMethod.Expected)}"); + return Render.AssertEqualWithin(Render.Object(testMethod.Expected), $"{testMethod.Input["x"]}.{testMethod.TestedMethod}({RenderRationalNumber(testMethod.Input["r"])})", Precision(testMethod.Expected)); default: throw new ArgumentOutOfRangeException(); } diff --git a/generators/Exercises/Generators/RobotSimulator.cs b/generators/Exercises/Generators/RobotSimulator.cs index 6440ef186d..8b132f883d 100644 --- a/generators/Exercises/Generators/RobotSimulator.cs +++ b/generators/Exercises/Generators/RobotSimulator.cs @@ -12,8 +12,8 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.Input["direction"] = RenderDirection(testMethod.Input["direction"]); testMethod.Input["coordinate"] = RenderCreateCoordinate(testMethod.Input["position"]); - testMethod.SetConstructorInputParameters("direction", "coordinate"); - + testMethod.ConstructorInputParameters = new[] { "direction", "coordinate" }; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; testMethod.TestMethodName = testMethod.TestMethodNameWithPath; testMethod.Act = RenderAct(testMethod); diff --git a/generators/Exercises/Generators/SaddlePoints.cs b/generators/Exercises/Generators/SaddlePoints.cs index 236574477d..1a3e8150a9 100644 --- a/generators/Exercises/Generators/SaddlePoints.cs +++ b/generators/Exercises/Generators/SaddlePoints.cs @@ -11,7 +11,8 @@ protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.TestedMethodType = TestedMethodType.InstanceMethod; testMethod.TestedMethod = "Calculate"; - testMethod.SetConstructorInputParameters("matrix"); + testMethod.ConstructorInputParameters = new[] { "matrix" }; + testMethod.UseVariablesForConstructorParameters = true; testMethod.UseVariablesForInput = true; testMethod.UseVariableForTested = true; diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index 7e27ed4001..927fefcfb4 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -14,7 +14,8 @@ protected override void UpdateTestMethod(TestMethod testMethod) if (testMethod.Input.ContainsKey("key")) { - testMethod.SetConstructorInputParameters("key"); + testMethod.ConstructorInputParameters = new[] { "key" }; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; } if (testMethod.Property == "new") @@ -43,7 +44,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) { var plaintext = Render.Object(testMethod.Input["plaintext"]); testMethod.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); - testMethod.SetInputParameters("ciphertext"); + testMethod.InputParameters = new[] { "ciphertext" }; } } diff --git a/generators/Exercises/Generators/SpaceAge.cs b/generators/Exercises/Generators/SpaceAge.cs index f0187dd6d5..7d01d039a8 100644 --- a/generators/Exercises/Generators/SpaceAge.cs +++ b/generators/Exercises/Generators/SpaceAge.cs @@ -1,4 +1,5 @@ -using Exercism.CSharp.Output; +using System; +using Exercism.CSharp.Output; namespace Exercism.CSharp.Exercises.Generators { @@ -7,8 +8,10 @@ public class SpaceAge : GeneratorExercise protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.TestedMethod = $"On{testMethod.Input["planet"]}"; - testMethod.SetInputParameters(); - testMethod.SetConstructorInputParameters("seconds"); + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + + testMethod.InputParameters = Array.Empty(); + testMethod.ConstructorInputParameters = new[] {"seconds"}; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Tournament.cs b/generators/Exercises/Generators/Tournament.cs index fd43f65ef5..3dd1a34b7d 100644 --- a/generators/Exercises/Generators/Tournament.cs +++ b/generators/Exercises/Generators/Tournament.cs @@ -30,7 +30,7 @@ protected override void UpdateTestClass(TestClass testClass) private static void AddRunTallyMethod(TestClass testClass) { - testClass.Methods.Add(@" + testClass.AdditionalMethods.Add(@" private string RunTally(string input) { var encoding = new UTF8Encoding(); diff --git a/generators/Exercises/Generators/Triangle.cs b/generators/Exercises/Generators/Triangle.cs index f51ff47283..b184d66ce5 100644 --- a/generators/Exercises/Generators/Triangle.cs +++ b/generators/Exercises/Generators/Triangle.cs @@ -8,14 +8,13 @@ public class Triangle : GeneratorExercise protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.TestedMethod = $"Is{testMethod.TestedMethod}".ToTestedMethodName(); + testMethod.TestMethodName = testMethod.TestMethodNameWithPath; testMethod.Input["x"] = testMethod.Input["sides"][0]; testMethod.Input["y"] = testMethod.Input["sides"][1]; testMethod.Input["z"] = testMethod.Input["sides"][2]; testMethod.Input.Remove("sides"); - testMethod.SetInputParameters("x", "y", "z"); - - testMethod.TestMethodName = testMethod.TestMethodNameWithPath; + testMethod.InputParameters = new[] { "x", "y", "z" }; } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/TwelveDays.cs b/generators/Exercises/Generators/TwelveDays.cs index 90c4bd73e4..2eba8c0745 100644 --- a/generators/Exercises/Generators/TwelveDays.cs +++ b/generators/Exercises/Generators/TwelveDays.cs @@ -12,7 +12,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) if (testMethod.Input["startVerse"] == testMethod.Input["endVerse"]) { - testMethod.SetInputParameters("startVerse"); + testMethod.InputParameters = new[] { "startVerse" }; } } } diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index bdd307f26e..ea5059d283 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -8,23 +8,21 @@ public class TwoBucket : GeneratorExercise protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.TestedMethodType = TestedMethodType.InstanceMethod; - testMethod.SetConstructorInputParameters("bucketOne", "bucketTwo", "startBucket"); - testMethod.Input["startBucket"] = Render.Enum("Bucket", testMethod.Input["startBucket"]); + testMethod.ConstructorInputParameters = new[] { "bucketOne", "bucketTwo", "startBucket" }; - testMethod.Act = RenderAct(testMethod); + testMethod.Input["startBucket"] = Render.Enum("Bucket", testMethod.Input["startBucket"]); + testMethod.UseVariableForTested = true; testMethod.Assert = RenderAssert(testMethod); } - private string RenderAct(TestMethod testMethod) => Render.Variable("result", testMethod.TestedMethodInvocation); - private string RenderAssert(TestMethod testMethod) { var assert = new StringBuilder(); - assert.AppendLine(Render.AssertEqual(testMethod.Expected["moves"].ToString(), "result.Moves")); - assert.AppendLine(Render.AssertEqual(testMethod.Expected["otherBucket"].ToString(), "result.OtherBucket")); + assert.AppendLine(Render.AssertEqual(testMethod.Expected["moves"].ToString(), "actual.Moves")); + assert.AppendLine(Render.AssertEqual(testMethod.Expected["otherBucket"].ToString(), "actual.OtherBucket")); var expected = Render.Enum("Bucket", testMethod.Expected["goalBucket"]); - assert.AppendLine(Render.AssertEqual(expected.ToString(), "result.GoalBucket")); + assert.AppendLine(Render.AssertEqual(expected.ToString(), "actual.GoalBucket")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/TwoFer.cs b/generators/Exercises/Generators/TwoFer.cs index 2f077dd9da..1e7be05598 100644 --- a/generators/Exercises/Generators/TwoFer.cs +++ b/generators/Exercises/Generators/TwoFer.cs @@ -1,4 +1,5 @@ -using Exercism.CSharp.Output; +using System; +using Exercism.CSharp.Output; namespace Exercism.CSharp.Exercises.Generators { @@ -9,7 +10,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.TestedMethod = "Name"; if (testMethod.Input["name"] is null) - testMethod.SetInputParameters(); + testMethod.InputParameters = Array.Empty(); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 4c30858511..925c5d814f 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -15,8 +15,9 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.UseVariableForTested = true; testMethod.UseVariableForExpected = true; testMethod.UseVariablesForConstructorParameters = true; - - testMethod.SetConstructorInputParameters("grid"); + + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + testMethod.ConstructorInputParameters = new[] { "grid" }; testMethod.Input["grid"] = new MultiLineString(testMethod.Input["grid"]); testMethod.Expected = ((IDictionary)testMethod.Expected).ToDictionary(kv => kv.Key, kv => (((int, int), (int, int))?)ConvertToPosition(kv.Value)); diff --git a/generators/Helpers/EnumerableExtensions.cs b/generators/Helpers/EnumerableExtensions.cs new file mode 100644 index 0000000000..1e033c3e6c --- /dev/null +++ b/generators/Helpers/EnumerableExtensions.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace Exercism.CSharp.Helpers +{ + public static class EnumerableExtensions + { + public static SortedSet ToSortedSet(this IEnumerable source) + => new SortedSet(source); + } +} \ No newline at end of file diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 45e38f1c64..2aac028768 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; @@ -22,6 +23,7 @@ public string Object(object val) case float flt: return Float(flt); case ulong ulng: return Ulong(ulng); case char c: return Char(c); + case DateTime dateTime: return DateTime(dateTime); case Regex regex: return Regex(regex); default: if (IsList(val)) diff --git a/generators/Output/Rendering/RenderDateTime.cs b/generators/Output/Rendering/RenderDateTime.cs new file mode 100644 index 0000000000..ebd570a67a --- /dev/null +++ b/generators/Output/Rendering/RenderDateTime.cs @@ -0,0 +1,14 @@ +using System; + +namespace Exercism.CSharp.Output.Rendering +{ + public partial class Render + { + public string DateTime(DateTime dateTime) + { + return dateTime.Hour == 0 && dateTime.Minute == 0 && dateTime.Second == 0 + ? $"new DateTime({dateTime.Year}, {dateTime.Month}, {dateTime.Day})" + : $"new DateTime({dateTime.Year}, {dateTime.Month}, {dateTime.Day}, {dateTime.Hour}, {dateTime.Minute}, {dateTime.Second})"; + } + } +} \ No newline at end of file diff --git a/generators/Output/Rendering/Templates/_TestClass.liquid b/generators/Output/Rendering/Templates/_TestClass.liquid index e351af4ef0..e320d155e9 100644 --- a/generators/Output/Rendering/Templates/_TestClass.liquid +++ b/generators/Output/Rendering/Templates/_TestClass.liquid @@ -1,4 +1,4 @@ -// This file was auto-generated based on version {{CanonicalDataVersion}} of the canonical data. +// This file was auto-generated based on version {{Version}} of the canonical data. {%- for namespace in Namespaces -%} using {{ namespace }}; diff --git a/generators/Output/TestClass.cs b/generators/Output/TestClass.cs index 034e4ad7a1..e5f7383bd5 100644 --- a/generators/Output/TestClass.cs +++ b/generators/Output/TestClass.cs @@ -1,19 +1,18 @@ using System.Collections.Generic; -using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Output { public class TestClass { - private const string TemplateName = "TestClass"; - - public string Exercise { get; set; } - public string ClassName { get; set; } - public string CanonicalDataVersion { get; set; } - public IList Methods { get; set; } - public ISet Namespaces { get; set; } + public TestClass(string exercise, string version, string className, IReadOnlyCollection testMethods) + => (Exercise, Version, ClassName, TestMethods) = (exercise, version, className, testMethods); + + public string Exercise { get; } + public string ClassName { get; } + public string Version { get; } + public IReadOnlyCollection TestMethods { get; } + public ICollection AdditionalMethods { get; } = new List(); + public ISet Namespaces { get; } = new SortedSet(); public bool IsDisposable { get; set; } - - public string Render() => Template.Render(TemplateName, new { ClassName, CanonicalDataVersion, Methods, Namespaces, IsDisposable }); } } \ No newline at end of file diff --git a/generators/Output/TestClassFile.cs b/generators/Output/TestClassFile.cs deleted file mode 100644 index 52cbf1453e..0000000000 --- a/generators/Output/TestClassFile.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.IO; - -namespace Exercism.CSharp.Output -{ - public static class TestClassFile - { - public static void Write(TestClass testClass) - { - var testClassFilePath = TestClassFilePath(testClass); - var testClassContents = testClass.Render(); - - Directory.CreateDirectory(Path.GetDirectoryName(testClassFilePath)); - File.WriteAllText(testClassFilePath, testClassContents); - } - - private static string TestClassFilePath(TestClass testClass) => Path.Combine("..", "exercises", testClass.Exercise, TestClassFileName(testClass)); - - private static string TestClassFileName(TestClass testClass) => $"{testClass.ClassName}.cs"; - } -} \ No newline at end of file diff --git a/generators/Output/TestClassOutput.cs b/generators/Output/TestClassOutput.cs new file mode 100644 index 0000000000..fde80bc75e --- /dev/null +++ b/generators/Output/TestClassOutput.cs @@ -0,0 +1,54 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using System.Linq; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Output.Rendering; + +namespace Exercism.CSharp.Output +{ + public class TestClassOutput + { + private readonly TestClass _testClass; + + public TestClassOutput(TestClass testClass) + => _testClass = testClass; + + public void WriteToFile() + { + var filePath = FilePath; + var renderedContents = Render(); + + Directory.CreateDirectory(Path.GetDirectoryName(filePath)); + File.WriteAllText(filePath, renderedContents); + } + + private string Render() => Template.Render("TestClass", RenderParameters); + + private object RenderParameters => new + { + _testClass.ClassName, + _testClass.Version, + _testClass.IsDisposable, + Methods, + Namespaces + }; + + private IEnumerable Methods + => _testClass.TestMethods + .Select(testMethod => new TestMethodOutput(testMethod).Render()) + .Concat(_testClass.AdditionalMethods); + + private SortedSet Namespaces + => _testClass.TestMethods + .Where(x => x.ExceptionThrown != null) + .Select(x => x.ExceptionThrown.Namespace) + .Concat(_testClass.Namespaces) + .Append("Xunit") + .ToSortedSet(); + + private string FilePath => Path.Combine("..", "exercises", _testClass.Exercise, FileName); + + private string FileName => $"{_testClass.ClassName}.cs"; + } +} \ No newline at end of file diff --git a/generators/Output/TestMethod.cs b/generators/Output/TestMethod.cs index 26f98e8b8a..a4a57a7859 100644 --- a/generators/Output/TestMethod.cs +++ b/generators/Output/TestMethod.cs @@ -1,8 +1,6 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Linq; -using System.Text.RegularExpressions; using Exercism.CSharp.Exercises; using Exercism.CSharp.Helpers; using Exercism.CSharp.Input; @@ -12,26 +10,9 @@ namespace Exercism.CSharp.Output { public class TestMethod { - private enum AssertType - { - Equal, - Empty, - Null, - Throws, - Boolean, - Matches - } + private readonly HashSet _inputParameters = new HashSet(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _constructorInputParameters = new HashSet(StringComparer.OrdinalIgnoreCase); - private const string SutVariableName = "sut"; - private const string TestedVariableName = "actual"; - private const string ExpectedVariableName = "expected"; - private const string TemplateName = "TestMethod"; - - private static readonly Render Renderer = new Render(); - - private readonly HashSet _inputParameterProperties = new HashSet(StringComparer.OrdinalIgnoreCase); - private readonly HashSet _constructorInputParameterProperties = new HashSet(StringComparer.OrdinalIgnoreCase); - public TestMethod(CanonicalData canonicalData, CanonicalDataCase canonicalDataCase) { Input = new Dictionary(canonicalDataCase.Input, StringComparer.OrdinalIgnoreCase); @@ -43,21 +24,23 @@ public TestMethod(CanonicalData canonicalData, CanonicalDataCase canonicalDataCa TestedMethod = canonicalDataCase.Property.ToTestedMethodName(); Skip = canonicalDataCase.Index > 0; - SetInputParameters(canonicalDataCase.Input.Keys.ToArray()); + InputParameters = canonicalDataCase.Input.Keys.ToArray(); } + + public string Act { get; set; } + public string Arrange { get; set; } + public string Assert { get; set; } - public string Property { get; } - - public IDictionary Input { get; set; } + public IDictionary Input { get; } public dynamic Expected { get; set; } - + public string Property { get; } public bool Skip { get; set; } public bool UseVariablesForInput { get; set; } public bool UseVariableForExpected { get; set; } public bool UseVariablesForConstructorParameters { get; set; } public bool UseVariableForTested { get; set; } - private bool UseVariableForSut + public bool UseVariableForSut => TestedMethodType == TestedMethodType.InstanceMethod || TestedMethodType == TestedMethodType.Property; @@ -67,167 +50,29 @@ private bool UseVariableForSut public string TestedMethod { get; set; } public TestedMethodType TestedMethodType { get; set; } public Type ExceptionThrown { get; set; } - - public void SetInputParameters(params string[] properties) - { - _inputParameterProperties.Clear(); - _inputParameterProperties.UnionWith(properties); - - _constructorInputParameterProperties.ExceptWith(properties); - } - - public void SetConstructorInputParameters(params string[] properties) - { - _constructorInputParameterProperties.Clear(); - _constructorInputParameterProperties.UnionWith(properties); - - _inputParameterProperties.ExceptWith(properties); - - if (TestedMethodType == TestedMethodType.StaticMethod) - TestedMethodType = TestedMethodType.InstanceMethod; - } - - public string SutValue => $"new {TestedClass}({ConstructorParameters})"; - public string TestedValue => UseVariableForTested ? TestedVariableName : TestedMethodInvocation; - public string ExpectedParameter => UseVariableForExpected ? ExpectedVariableName : Renderer.Object(Expected); - private string InputParameters => string.Join(", ", _inputParameterProperties.Select(key => UseVariablesForInput ? key.ToVariableName() : Renderer.Object(Input[key]))); - private string ConstructorParameters => string.Join(", ", _constructorInputParameterProperties.Select(key => UseVariablesForConstructorParameters ? key.ToVariableName() : Renderer.Object(Input[key]))); - - private string ExpectedVariableDeclaration => Renderer.Variable(ExpectedVariableName, Renderer.ObjectMultiLine(Expected)); - private IEnumerable InputVariablesDeclaration => Renderer.Variables(_inputParameterProperties.ToDictionary(key => key, key => Input[key])); - private IEnumerable ConstructorVariablesDeclaration => Renderer.Variables(_constructorInputParameterProperties.ToDictionary(key => key, key => Input[key])); - private IEnumerable SutVariableDeclaration => new[] { Renderer.Variable(SutVariableName, SutValue) }; - private IEnumerable ActualVariableDeclaration => new[] { Renderer.Variable(TestedVariableName, TestedMethodInvocation) }; - - public IEnumerable Variables + public IReadOnlyCollection InputParameters { - get + get => _inputParameters; + set { - var lines = new List(); - - if (UseVariablesForInput) - lines.AddRange(InputVariablesDeclaration); - - if (UseVariablesForConstructorParameters) - lines.AddRange(ConstructorVariablesDeclaration); - - if (UseVariableForSut) - lines.AddRange(SutVariableDeclaration); - - if (UseVariableForTested) - lines.AddRange(ActualVariableDeclaration); - - if (UseVariableForExpected) - lines.Add(ExpectedVariableDeclaration); + _inputParameters.Clear(); + _inputParameters.UnionWith(value); - return lines; + _constructorInputParameters.ExceptWith(value); } } - - public string TestedMethodInvocation - { - get - { - switch (TestedMethodType) - { - case TestedMethodType.StaticMethod: - return $"{TestedClass}.{TestedMethod}({InputParameters})"; - case TestedMethodType.ExtensionMethod: - return $"{InputParameters}.{TestedMethod}()"; - case TestedMethodType.InstanceMethod: - return $"{SutVariableName}.{TestedMethod}({InputParameters})"; - case TestedMethodType.Property: - return $"{SutVariableName}.{TestedMethod}"; - case TestedMethodType.Constructor: - return $"new {TestedClass}({ConstructorParameters})"; - default: - throw new ArgumentOutOfRangeException(); - } - } - } - - - - public string Act { get; set; } - public string Arrange { get; set; } - public string Assert { get; set; } - - public string Render() - { - UpdateBasedOnCurrentAssertType(); - - Arrange = Arrange ?? RenderArrange(); - Act = Act ?? RenderAct(); - Assert = Assert ?? RenderAssert(); - - return Template.Render(TemplateName, new { Name = TestMethodName, Skip, Arrange, Act, Assert }); - } - - private string RenderArrange() => Template.Render("Arrange", new { Variables }); - - private string RenderAct() => Template.Render("Act", new { }); - - private string RenderAssert() + public IReadOnlyCollection ConstructorInputParameters { - switch (CurrentAssertType) + get => _constructorInputParameters; + set { - case AssertType.Equal: - return Renderer.AssertEqual(ExpectedParameter, TestedValue); - case AssertType.Empty: - return Renderer.AssertEmpty(ExpectedParameter, TestedValue); - case AssertType.Null: - return Renderer.AssertNull(TestedValue); - case AssertType.Throws: - return Renderer.AssertThrows(ExceptionThrown, TestedValue); - case AssertType.Boolean: - return Renderer.AssertBoolean(Convert.ToBoolean(Expected), TestedValue); - case AssertType.Matches: - return Renderer.AssertMatches(ExpectedParameter, TestedValue); - default: - throw new ArgumentOutOfRangeException(); - } - } + _constructorInputParameters.Clear(); + _constructorInputParameters.UnionWith(value); - private void UpdateBasedOnCurrentAssertType() - { - switch (CurrentAssertType) - { - case AssertType.Empty: - UseVariableForExpected = false; - break; - case AssertType.Throws: - UseVariableForExpected = false; - UseVariableForTested = false; - break; + _inputParameters.ExceptWith(value); } } - - private AssertType CurrentAssertType - { - get - { - if (ExceptionThrown != null) - return AssertType.Throws; - - switch (Expected) - { - case null: - return AssertType.Null; - case bool _: - return AssertType.Boolean; - case Regex _: - return AssertType.Matches; - default: - return UseEmptyAssertion - ? AssertType.Empty - : AssertType.Equal; - } - } - } - - private bool UseEmptyAssertion - => !(Expected is string) && Expected is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; } } \ No newline at end of file diff --git a/generators/Output/TestMethodOutput.cs b/generators/Output/TestMethodOutput.cs new file mode 100644 index 0000000000..163741ea25 --- /dev/null +++ b/generators/Output/TestMethodOutput.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using Exercism.CSharp.Exercises; +using Exercism.CSharp.Helpers; +using Exercism.CSharp.Input; +using Exercism.CSharp.Output.Rendering; + +namespace Exercism.CSharp.Output +{ + public class TestMethodOutput + { + private readonly TestMethod _testMethod; + + public TestMethodOutput(TestMethod testMethod) => _testMethod = testMethod; + + private const string SutVariableName = "sut"; + private const string TestedVariableName = "actual"; + private const string ExpectedVariableName = "expected"; + + private static readonly Render Renderer = new Render(); + + public string SutValue => $"new {_testMethod.TestedClass}({ConstructorParameters})"; + public string TestedValue => _testMethod.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; + public string ExpectedParameter => _testMethod.UseVariableForExpected ? ExpectedVariableName : Renderer.Object(_testMethod.Expected); + + private string InputParameters => string.Join(", ", _testMethod.InputParameters.Select(key => _testMethod.UseVariablesForInput ? key.ToVariableName() : Renderer.Object(_testMethod.Input[key]))); + private string ConstructorParameters => string.Join(", ", _testMethod.ConstructorInputParameters.Select(key => _testMethod.UseVariablesForConstructorParameters ? key.ToVariableName() : Renderer.Object(_testMethod.Input[key]))); + + private string ExpectedVariableDeclaration => Renderer.Variable(ExpectedVariableName, Renderer.ObjectMultiLine(_testMethod.Expected)); + private IEnumerable InputVariablesDeclaration => Renderer.Variables(_testMethod.InputParameters.ToDictionary(key => key, key => _testMethod.Input[key])); + private IEnumerable ConstructorVariablesDeclaration => Renderer.Variables(_testMethod.ConstructorInputParameters.ToDictionary(key => key, key => _testMethod.Input[key])); + private IEnumerable SutVariableDeclaration => new[] { Renderer.Variable(SutVariableName, SutValue) }; + private IEnumerable ActualVariableDeclaration => new[] { Renderer.Variable(TestedVariableName, TestedMethodInvocation) }; + + public IEnumerable Variables + { + get + { + var lines = new List(); + + if (_testMethod.UseVariablesForInput) + lines.AddRange(InputVariablesDeclaration); + + if (_testMethod.UseVariablesForConstructorParameters) + lines.AddRange(ConstructorVariablesDeclaration); + + if (_testMethod.UseVariableForSut) + lines.AddRange(SutVariableDeclaration); + + if (_testMethod.UseVariableForTested) + lines.AddRange(ActualVariableDeclaration); + + if (_testMethod.UseVariableForExpected) + lines.Add(ExpectedVariableDeclaration); + + return lines; + } + } + + public string TestedMethodInvocation + { + get + { + switch (_testMethod.TestedMethodType) + { + case TestedMethodType.StaticMethod: + return $"{_testMethod.TestedClass}.{_testMethod.TestedMethod}({InputParameters})"; + case TestedMethodType.ExtensionMethod: + return $"{InputParameters}.{_testMethod.TestedMethod}()"; + case TestedMethodType.InstanceMethod: + return $"{SutVariableName}.{_testMethod.TestedMethod}({InputParameters})"; + case TestedMethodType.Property: + return $"{SutVariableName}.{_testMethod.TestedMethod}"; + case TestedMethodType.Constructor: + return $"new {_testMethod.TestedClass}({ConstructorParameters})"; + default: + throw new ArgumentOutOfRangeException(); + } + } + } + + public string Render() + { + UpdateBasedOnCurrentAssertType(); + + _testMethod.Arrange = _testMethod.Arrange ?? RenderArrange(); + _testMethod.Act = _testMethod.Act ?? RenderAct(); + _testMethod.Assert = _testMethod.Assert ?? RenderAssert(); + + return Template.Render("TestMethod", new { Name = _testMethod.TestMethodName, _testMethod.Skip, _testMethod.Arrange, _testMethod.Act, _testMethod.Assert }); + } + + private string RenderArrange() => Template.Render("Arrange", new { Variables }); + + private string RenderAct() => Template.Render("Act", new { }); + + private string RenderAssert() + { + switch (CurrentAssertType) + { + case AssertType.Equal: + return Renderer.AssertEqual(ExpectedParameter, TestedValue); + case AssertType.Empty: + return Renderer.AssertEmpty(ExpectedParameter, TestedValue); + case AssertType.Null: + return Renderer.AssertNull(TestedValue); + case AssertType.Throws: + return Renderer.AssertThrows(_testMethod.ExceptionThrown, TestedValue); + case AssertType.Boolean: + return Renderer.AssertBoolean(Convert.ToBoolean(_testMethod.Expected), TestedValue); + case AssertType.Matches: + return Renderer.AssertMatches(ExpectedParameter, TestedValue); + default: + throw new ArgumentOutOfRangeException(); + } + } + + private void UpdateBasedOnCurrentAssertType() + { + switch (CurrentAssertType) + { + case AssertType.Empty: + _testMethod.UseVariableForExpected = false; + break; + case AssertType.Throws: + _testMethod.UseVariableForExpected = false; + _testMethod.UseVariableForTested = false; + break; + } + } + + private AssertType CurrentAssertType + { + get + { + if (_testMethod.ExceptionThrown != null) + return AssertType.Throws; + + switch (_testMethod.Expected) + { + case null: + return AssertType.Null; + case bool _: + return AssertType.Boolean; + case Regex _: + return AssertType.Matches; + default: + return UseEmptyAssertion + ? AssertType.Empty + : AssertType.Equal; + } + } + } + + private bool UseEmptyAssertion + => !(_testMethod.Expected is string) && _testMethod.Expected is IEnumerable enumerable && enumerable.GetEnumerator().MoveNext() == false; + + private enum AssertType + { + Equal, + Empty, + Null, + Throws, + Boolean, + Matches + } + } +} \ No newline at end of file From 2b44b7f6b20d73ab8283031efb9f4b9195f74a5e Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 8 Jul 2018 19:06:09 +0200 Subject: [PATCH 88/97] generators: Extract different property handling paths to separate methods --- generators/Exercises/Generators/Allergies.cs | 17 ++-- .../Exercises/Generators/BinarySearchTree.cs | 37 +++------ generators/Exercises/Generators/Bowling.cs | 6 +- generators/Exercises/Generators/Clock.cs | 68 +++++++--------- .../Exercises/Generators/ComplexNumbers.cs | 10 +-- generators/Exercises/Generators/Connect.cs | 18 +++-- generators/Exercises/Generators/CustomSet.cs | 47 ++++++----- generators/Exercises/Generators/GoCounting.cs | 79 ++++++++++--------- generators/Exercises/Generators/Grep.cs | 5 +- .../Exercises/Generators/PascalsTriangle.cs | 1 + .../Exercises/Generators/QueenAttack.cs | 48 +++++------ .../Exercises/Generators/RunLengthEncoding.cs | 8 +- .../Exercises/Generators/SaddlePoints.cs | 2 +- .../Exercises/Generators/SimpleCipher.cs | 37 +++++---- .../Exercises/Generators/SpiralMatrix.cs | 2 +- generators/Exercises/Generators/TwoBucket.cs | 5 +- generators/Exercises/Generators/WordSearch.cs | 5 +- 17 files changed, 191 insertions(+), 204 deletions(-) diff --git a/generators/Exercises/Generators/Allergies.cs b/generators/Exercises/Generators/Allergies.cs index 733fec8c1e..c410f72523 100644 --- a/generators/Exercises/Generators/Allergies.cs +++ b/generators/Exercises/Generators/Allergies.cs @@ -7,28 +7,21 @@ public class Allergies : GeneratorExercise { protected override void UpdateTestMethod(TestMethod testMethod) { - if (testMethod.Property == "allergicTo") - testMethod.TestedMethod = $"Is{testMethod.TestedMethod}"; - else if (testMethod.Property == "list") - testMethod.UseVariableForExpected = true; - testMethod.ConstructorInputParameters = new[] { "score" }; testMethod.TestedMethodType = TestedMethodType.InstanceMethod; - testMethod.Assert = RenderAssert(testMethod); + if (testMethod.Property == "allergicTo") + testMethod.Assert = RenderIsAllergicToAssert(testMethod); + else if (testMethod.Property == "list") + testMethod.UseVariableForExpected = true; } - private string RenderAssert(TestMethod testMethod) - => testMethod.Property == "allergicTo" - ? RenderIsAllergicToAssert(testMethod) - : testMethod.Assert; - private string RenderIsAllergicToAssert(TestMethod testMethod) { var assert = new StringBuilder(); foreach (var allergy in testMethod.Expected) - assert.AppendLine(Render.AssertBoolean(allergy["result"], $"sut.{testMethod.TestedMethod}({Render.Object(allergy["substance"])})")); + assert.AppendLine(Render.AssertBoolean(allergy["result"], $"sut.IsAllergicTo({Render.Object(allergy["substance"])})")); return assert.ToString(); } diff --git a/generators/Exercises/Generators/BinarySearchTree.cs b/generators/Exercises/Generators/BinarySearchTree.cs index af08765234..3593a79fef 100644 --- a/generators/Exercises/Generators/BinarySearchTree.cs +++ b/generators/Exercises/Generators/BinarySearchTree.cs @@ -5,27 +5,8 @@ namespace Exercism.CSharp.Exercises.Generators { - public class ExpectedDataBinaryTree - { - public ExpectedDataBinaryTree(IReadOnlyDictionary treeNode) - { - Value = treeNode["data"] as string; - if (treeNode["left"] != null) Left = new ExpectedDataBinaryTree(treeNode["left"] as Dictionary); - if (treeNode["right"] != null) Right = new ExpectedDataBinaryTree(treeNode["right"] as Dictionary); - } - - public string Value { get; } - public ExpectedDataBinaryTree Left { get; } - public ExpectedDataBinaryTree Right { get; } - } - public class BinarySearchTree : GeneratorExercise { - protected override void UpdateNamespaces(ISet namespaces) - { - namespaces.Add(typeof(IQueryable).Namespace); - } - protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.Assert = RenderAssert(testMethod); @@ -39,10 +20,9 @@ private string RenderAssert(TestMethod testMethod) var constructorParameters = Render.Object(treeData.Length == 1 ? treeData[0] : treeData); assert.AppendLine(Render.Variable("tree", $"new BinarySearchTree({constructorParameters})")); - if (testMethod.Expected is Dictionary expected) + if (testMethod.Expected is Dictionary) { - var tree = new ExpectedDataBinaryTree(expected); - foreach (var testAssert in TestAsserts(tree)) + foreach (var testAssert in TestAsserts(testMethod.Expected)) assert.AppendLine(testAssert); } else @@ -56,11 +36,16 @@ private string RenderAssert(TestMethod testMethod) private static int[] ConvertToIntegers(dynamic data) => ((string[]) data).Select(int.Parse).ToArray(); - private IEnumerable TestAsserts(ExpectedDataBinaryTree tree, string traverse = "") + private IEnumerable TestAsserts(dynamic tree, string traverse = "") + { + yield return Render.AssertEqual(tree["data"], $"tree{traverse}.Value"); + if (tree["left"] != null) foreach (var assert in TestAsserts(tree["left"], $"{traverse}.Left")) yield return assert; + if (tree["right"] != null) foreach (var assert in TestAsserts(tree["right"], $"{traverse}.Right")) yield return assert; + } + + protected override void UpdateNamespaces(ISet namespaces) { - yield return Render.AssertEqual(tree.Value, $"tree{traverse}.Value"); - if (tree.Left != null) foreach (var assert in TestAsserts(tree.Left, $"{traverse}.Left")) yield return assert; - if (tree.Right != null) foreach (var assert in TestAsserts(tree.Right, $"{traverse}.Right")) yield return assert; + namespaces.Add(typeof(IQueryable).Namespace); } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Bowling.cs b/generators/Exercises/Generators/Bowling.cs index 0a4454d6ce..0df2cdc931 100644 --- a/generators/Exercises/Generators/Bowling.cs +++ b/generators/Exercises/Generators/Bowling.cs @@ -7,8 +7,6 @@ namespace Exercism.CSharp.Exercises.Generators { public class Bowling : GeneratorExercise { - private const string PreviousRolls = "previousRolls"; - protected override void UpdateTestMethod(TestMethod testMethod) { if (testMethod.Expected is int) @@ -28,10 +26,10 @@ private string RenderArrange(TestMethod testMethod) var builder = new StringBuilder(); builder.AppendLine(Render.Variable("sut", "new BowlingGame()")); - if (!testMethod.Input.ContainsKey(PreviousRolls)) + if (!testMethod.Input.ContainsKey("previousRolls")) return builder.ToString(); - var previousRolls = testMethod.Input[PreviousRolls] as int[] ?? Array.Empty(); + var previousRolls = testMethod.Input["previousRolls"] as int[] ?? Array.Empty(); builder.Append(Render.Variable("previousRolls", Render.ObjectMultiLine(previousRolls))); return builder.ToString(); diff --git a/generators/Exercises/Generators/Clock.cs b/generators/Exercises/Generators/Clock.cs index 3434b282af..0b9d57bfe8 100644 --- a/generators/Exercises/Generators/Clock.cs +++ b/generators/Exercises/Generators/Clock.cs @@ -5,63 +5,51 @@ namespace Exercism.CSharp.Exercises.Generators { public class Clock : GeneratorExercise { - private const string ParamClock1 = "clock1"; - private const string ParamClock2 = "clock2"; - private const string ParamHour = "hour"; - private const string ParamMinute = "minute"; - - private const string PropertyCreate = "create"; - private const string PropertyEqual = "equal"; - protected override void UpdateTestMethod(TestMethod testMethod) { - testMethod.ConstructorInputParameters = new[] { ParamHour, ParamMinute }; + testMethod.ConstructorInputParameters = new[] { "hour", "minute" }; testMethod.TestedMethodType = TestedMethodType.InstanceMethod; - if (testMethod.Property == PropertyEqual) - { - var clock1 = testMethod.Input[ParamClock1]; - testMethod.Input[ParamClock1] = new UnescapedValue($"new Clock({clock1[ParamHour]}, {clock1[ParamMinute]})"); - - var clock2 = testMethod.Input[ParamClock2]; - testMethod.Input[ParamHour] = clock2[ParamHour]; - testMethod.Input[ParamMinute] = clock2[ParamMinute]; - } - - if (testMethod.Property == PropertyCreate) - { - testMethod.TestedMethod = "ToString"; - } - else if (testMethod.Property == PropertyEqual) - { - testMethod.TestedMethod = "Equals"; - } + if (testMethod.Property == "create") + UpdateTestMethodForCreateProperty(testMethod); + else if (testMethod.Property == "equal") + UpdateTestMethodForEqualProperty(testMethod); + else + UpdateTestMethodForConsistencyProperty(testMethod); + } - testMethod.Assert = RenderAssert(testMethod); + private static void UpdateTestMethodForCreateProperty(TestMethod testMethod) + { + testMethod.TestedMethod = "ToString"; } - private string RenderAssert(TestMethod testMethod) + private void UpdateTestMethodForEqualProperty(TestMethod testMethod) { - if (testMethod.Property == PropertyEqual) - { - return RenderEqualToAssert(testMethod); - } + var clock1 = testMethod.Input["clock1"]; + testMethod.Input["clock1"] = new UnescapedValue($"new Clock({clock1["hour"]}, {clock1["minute"]})"); - return testMethod.Property == PropertyCreate - ? testMethod.Assert - : RenderConsistencyToAssert(testMethod); - } + var clock2 = testMethod.Input["clock2"]; + testMethod.Input["hour"] = clock2["hour"]; + testMethod.Input["minute"] = clock2["minute"]; - private string RenderConsistencyToAssert(TestMethod testMethod) - => Render.AssertEqual(Render.Object(testMethod.Expected), $"sut.{testMethod.TestedMethod}({testMethod.Input["value"]}).ToString()"); + testMethod.Assert = RenderEqualToAssert(testMethod); + } private string RenderEqualToAssert(TestMethod testMethod) { - var expected = Render.Object(testMethod.Input[ParamClock1]); + var expected = Render.Object(testMethod.Input["clock1"]); return testMethod.Expected ? Render.AssertEqual(expected, "sut") : Render.AssertNotEqual(expected, "sut"); } + + private void UpdateTestMethodForConsistencyProperty(TestMethod testMethod) + { + testMethod.Assert = RenderConsistencyToAssert(testMethod); + } + + private string RenderConsistencyToAssert(TestMethod testMethod) + => Render.AssertEqual(Render.Object(testMethod.Expected), $"sut.{testMethod.TestedMethod}({testMethod.Input["value"]}).ToString()"); } } \ No newline at end of file diff --git a/generators/Exercises/Generators/ComplexNumbers.cs b/generators/Exercises/Generators/ComplexNumbers.cs index 560e00d5ad..c839e1deed 100644 --- a/generators/Exercises/Generators/ComplexNumbers.cs +++ b/generators/Exercises/Generators/ComplexNumbers.cs @@ -53,11 +53,6 @@ private string RenderComplexNumberAssert(TestMethod testMethod) return assert.ToString(); } - protected override void UpdateNamespaces(ISet namespaces) - { - namespaces.Add(typeof(Math).Namespace); - } - private object ConvertToType(dynamic rawValue) => IsComplexNumber(rawValue) ? RenderComplexNumber(rawValue) @@ -82,5 +77,10 @@ private static object ConvertToDouble(dynamic value) return double.Parse(value.ToString()); } } + + protected override void UpdateNamespaces(ISet namespaces) + { + namespaces.Add(typeof(Math).Namespace); + } } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Connect.cs b/generators/Exercises/Generators/Connect.cs index a329736ebe..4c353ed8c6 100644 --- a/generators/Exercises/Generators/Connect.cs +++ b/generators/Exercises/Generators/Connect.cs @@ -1,4 +1,5 @@ -using Exercism.CSharp.Output; +using DotLiquid.Exceptions; +using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators @@ -13,18 +14,21 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.TestedMethod = "Result"; testMethod.Input["board"] = new UnescapedValue(Render.ArrayMultiLine(testMethod.Input["board"])); + testMethod.Expected = ConvertExpected(testMethod); + } + private UnescapedValue ConvertExpected(TestMethod testMethod) + { switch (testMethod.Expected) { case "X": - testMethod.Expected = Render.Enum("ConnectWinner", "Black"); - break; + return Render.Enum("ConnectWinner", "Black"); case "O": - testMethod.Expected = Render.Enum("ConnectWinner", "White"); - break; + return Render.Enum("ConnectWinner", "White"); case "": - testMethod.Expected = Render.Enum("ConnectWinner", "None"); - break; + return Render.Enum("ConnectWinner", "None"); + default: + throw new ArgumentException("Unsupported expected value"); } } } diff --git a/generators/Exercises/Generators/CustomSet.cs b/generators/Exercises/Generators/CustomSet.cs index 101c05cbc3..38140173b6 100644 --- a/generators/Exercises/Generators/CustomSet.cs +++ b/generators/Exercises/Generators/CustomSet.cs @@ -10,36 +10,41 @@ protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.UseVariablesForInput = true; testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + testMethod.Expected = ConvertToCustomSet(testMethod.Expected); if (testMethod.Input.ContainsKey("set")) - { - if (testMethod.Input["set"] is JArray) - { - testMethod.Input["set"] = new UnescapedValue(""); - } + UpdateTestMethodForSingleSetProperty(testMethod); + else + UpdateTestMethodForMultipleSetsProperty(testMethod); + } - testMethod.ConstructorInputParameters = new[] { "set" }; + private static void UpdateTestMethodForSingleSetProperty(TestMethod testMethod) + { + if (testMethod.Input["set"] is JArray) + { + testMethod.Input["set"] = new UnescapedValue(""); } - else + + testMethod.ConstructorInputParameters = new[] {"set"}; + } + + private void UpdateTestMethodForMultipleSetsProperty(TestMethod testMethod) + { + if (testMethod.Input["set1"] is JArray) { - if (testMethod.Input["set1"] is JArray) - { - testMethod.Input["set1"] = new UnescapedValue(""); - } - - testMethod.ConstructorInputParameters = new[] { "set1" }; - testMethod.Input["set2"] = ConvertCustomSet(testMethod.Input["set2"]); - - if (testMethod.Property == "equal") - { - testMethod.TestedMethod = "Equals"; - } + testMethod.Input["set1"] = new UnescapedValue(""); } - testMethod.Expected = ConvertCustomSet(testMethod.Expected); + testMethod.ConstructorInputParameters = new[] {"set1"}; + testMethod.Input["set2"] = ConvertToCustomSet(testMethod.Input["set2"]); + + if (testMethod.Property == "equal") + { + testMethod.TestedMethod = "Equals"; + } } - private dynamic ConvertCustomSet(dynamic value) + private dynamic ConvertToCustomSet(dynamic value) { switch (value) { diff --git a/generators/Exercises/Generators/GoCounting.cs b/generators/Exercises/Generators/GoCounting.cs index afeb74e462..b02796de35 100644 --- a/generators/Exercises/Generators/GoCounting.cs +++ b/generators/Exercises/Generators/GoCounting.cs @@ -22,62 +22,63 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.TestedMethodType = TestedMethodType.InstanceMethod; if (testMethod.Property == "territory") - { - testMethod.Input["coordinate"] = (testMethod.Input["x"], testMethod.Input["y"]); - testMethod.InputParameters = new[] {"coordinate"}; + UpdateTestMethodForTerritoryProperty(testMethod); + else + UpdateTestMethodForTerritoriesProperty(testMethod); + } + + private void UpdateTestMethodForTerritoryProperty(TestMethod testMethod) + { + testMethod.Input["coordinate"] = (testMethod.Input["x"], testMethod.Input["y"]); + testMethod.InputParameters = new[] {"coordinate"}; - if (testMethod.Expected.ContainsKey("error")) - { - testMethod.ExceptionThrown = typeof(ArgumentException); - } - else - { - var owner = RenderOwner(testMethod.Expected["owner"]); - var territory = RenderTerritory(testMethod.Expected["territory"]); - testMethod.Expected = (owner, territory); - } + if (testMethod.Expected.ContainsKey("error")) + { + testMethod.ExceptionThrown = typeof(ArgumentException); } else { - var expected = new[] - { - "new Dictionary", - "{", - $" [Owner.Black] = {RenderTerritory(testMethod.Expected["territoryBlack"])},", - $" [Owner.White] = {RenderTerritory(testMethod.Expected["territoryWhite"])},", - $" [Owner.None] = {RenderTerritory(testMethod.Expected["territoryNone"])}", - "}" - }; - - testMethod.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); + var owner = RenderOwner(testMethod.Expected["owner"]); + var territory = RenderTerritory(testMethod.Expected["territory"]); + testMethod.Expected = (owner, territory); + testMethod.Assert = RenderTerritoryAssert(); } - - testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod testMethod) + private void UpdateTestMethodForTerritoriesProperty(TestMethod testMethod) { - if (testMethod.ExceptionThrown != null) + var expected = new[] { - return testMethod.Assert; - } + "new Dictionary", + "{", + $" [Owner.Black] = {RenderTerritory(testMethod.Expected["territoryBlack"])},", + $" [Owner.White] = {RenderTerritory(testMethod.Expected["territoryWhite"])},", + $" [Owner.None] = {RenderTerritory(testMethod.Expected["territoryNone"])}", + "}" + }; - if (testMethod.Property == "territories") - { - var territoriesAssert = new StringBuilder(); - territoriesAssert.AppendLine(Render.AssertEqual("expected.Keys", "actual.Keys")); - territoriesAssert.AppendLine(Render.AssertEqual("expected[Owner.Black]", "actual[Owner.Black]")); - territoriesAssert.AppendLine(Render.AssertEqual("expected[Owner.White]", "actual[Owner.White]")); - territoriesAssert.AppendLine(Render.AssertEqual("expected[Owner.None]", "actual[Owner.None]")); - return territoriesAssert.ToString(); - } + testMethod.Expected = new UnescapedValue(string.Join(Environment.NewLine, expected)); + testMethod.Assert = RenderTerritoriesAssert(); + } + private string RenderTerritoryAssert() + { var assert = new StringBuilder(); assert.AppendLine(Render.AssertEqual("expected.Item1", "actual.Item1")); assert.AppendLine(Render.AssertEqual("expected.Item2", "actual.Item2")); return assert.ToString(); } + private string RenderTerritoriesAssert() + { + var territoriesAssert = new StringBuilder(); + territoriesAssert.AppendLine(Render.AssertEqual("expected.Keys", "actual.Keys")); + territoriesAssert.AppendLine(Render.AssertEqual("expected[Owner.Black]", "actual[Owner.Black]")); + territoriesAssert.AppendLine(Render.AssertEqual("expected[Owner.White]", "actual[Owner.White]")); + territoriesAssert.AppendLine(Render.AssertEqual("expected[Owner.None]", "actual[Owner.None]")); + return territoriesAssert.ToString(); + } + private UnescapedValue RenderOwner(dynamic owner) => Render.Enum("Owner", owner); private string RenderTerritory(dynamic territory) diff --git a/generators/Exercises/Generators/Grep.cs b/generators/Exercises/Generators/Grep.cs index 54616f7a22..e443aa06a3 100644 --- a/generators/Exercises/Generators/Grep.cs +++ b/generators/Exercises/Generators/Grep.cs @@ -11,12 +11,15 @@ public class Grep : GeneratorExercise protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.TestedMethod = "Match"; - testMethod.Input["flags"] = string.Join(" ", testMethod.Input["flags"]); + testMethod.Input["flags"] = ConvertFlags(testMethod); testMethod.Expected = ConvertExpected(testMethod.Expected); testMethod.UseVariablesForInput = true; testMethod.UseVariableForExpected = true; } + private static dynamic ConvertFlags(TestMethod testMethod) + => string.Join(" ", testMethod.Input["flags"]); + private static MultiLineString ConvertExpected(dynamic expected) => new MultiLineString(expected as string[] ?? Array.Empty()); diff --git a/generators/Exercises/Generators/PascalsTriangle.cs b/generators/Exercises/Generators/PascalsTriangle.cs index b2d1d7a6b0..b178a509a3 100644 --- a/generators/Exercises/Generators/PascalsTriangle.cs +++ b/generators/Exercises/Generators/PascalsTriangle.cs @@ -10,6 +10,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.UseVariableForExpected = true; testMethod.TestedMethod = "Calculate"; + if (testMethod.Expected is JArray jArray) testMethod.Expected = jArray.ToObject(); else diff --git a/generators/Exercises/Generators/QueenAttack.cs b/generators/Exercises/Generators/QueenAttack.cs index 5db937fb01..0be80fe7fd 100644 --- a/generators/Exercises/Generators/QueenAttack.cs +++ b/generators/Exercises/Generators/QueenAttack.cs @@ -10,33 +10,37 @@ public class QueenAttack : GeneratorExercise protected override void UpdateTestMethod(TestMethod testMethod) { if (testMethod.Property == "create") + UpdateTestMethodForCreateProperty(testMethod); + else if (testMethod.Property == "canAttack") + UpdateTestMethodForCanAttackProperty(testMethod); + } + + private static void UpdateTestMethodForCreateProperty(TestMethod testMethod) + { + if (testMethod.Expected < 0) { - if (testMethod.Expected < 0) - { - testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); - } - else - { - testMethod.UseVariableForTested = true; - testMethod.Assert = string.Empty; - } - - var coordinates = GetCoordinatesFromPosition(testMethod.Input["queen"]); - testMethod.Input["X"] = coordinates.Item1; - testMethod.Input["Y"] = coordinates.Item2; - - testMethod.InputParameters = new[] { "X", "Y" }; - return; + testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); } - - if (testMethod.Property == "canAttack") + else { - testMethod.UseVariablesForInput = true; - testMethod.Input["white_queen"] = RenderQueen(testMethod.Input["white_queen"]); - testMethod.Input["black_queen"] = RenderQueen(testMethod.Input["black_queen"]); + testMethod.UseVariableForTested = true; + testMethod.Assert = string.Empty; } + + var coordinates = GetCoordinatesFromPosition(testMethod.Input["queen"]); + testMethod.Input["X"] = coordinates.Item1; + testMethod.Input["Y"] = coordinates.Item2; + + testMethod.InputParameters = new[] {"X", "Y"}; } - + + private static void UpdateTestMethodForCanAttackProperty(TestMethod testMethod) + { + testMethod.UseVariablesForInput = true; + testMethod.Input["white_queen"] = RenderQueen(testMethod.Input["white_queen"]); + testMethod.Input["black_queen"] = RenderQueen(testMethod.Input["black_queen"]); + } + private static UnescapedValue RenderQueen(dynamic input) { var (x, y) = GetCoordinatesFromPosition((IDictionary)input); diff --git a/generators/Exercises/Generators/RunLengthEncoding.cs b/generators/Exercises/Generators/RunLengthEncoding.cs index 5bffc38428..b4b5830120 100644 --- a/generators/Exercises/Generators/RunLengthEncoding.cs +++ b/generators/Exercises/Generators/RunLengthEncoding.cs @@ -8,14 +8,10 @@ protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.TestMethodName = testMethod.TestMethodNameWithPath; - testMethod.Assert = RenderAssert(testMethod); + if (testMethod.Property == "consistency") + testMethod.Assert = RenderConsistencyToAssert(testMethod); } - private string RenderAssert(TestMethod testMethod) - => testMethod.Property == "consistency" - ? RenderConsistencyToAssert(testMethod) - : testMethod.Assert; - private string RenderConsistencyToAssert(TestMethod testMethod) { var expected = Render.Object(testMethod.Expected); diff --git a/generators/Exercises/Generators/SaddlePoints.cs b/generators/Exercises/Generators/SaddlePoints.cs index 1a3e8150a9..afc1ca6493 100644 --- a/generators/Exercises/Generators/SaddlePoints.cs +++ b/generators/Exercises/Generators/SaddlePoints.cs @@ -31,7 +31,7 @@ protected override void UpdateNamespaces(ISet namespaces) namespaces.Add(typeof(string).Namespace); } - private static dynamic ToMultiDimensionalArray(JArray jArray) => jArray.ToObject(); + private static dynamic ToMultiDimensionalArray(JToken jArray) => jArray.ToObject(); private static (string, object)[] ToTupleCollection(Array array) { diff --git a/generators/Exercises/Generators/SimpleCipher.cs b/generators/Exercises/Generators/SimpleCipher.cs index 927fefcfb4..2c2b82922b 100644 --- a/generators/Exercises/Generators/SimpleCipher.cs +++ b/generators/Exercises/Generators/SimpleCipher.cs @@ -13,25 +13,30 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.TestMethodName = testMethod.TestMethodNameWithPath; if (testMethod.Input.ContainsKey("key")) - { testMethod.ConstructorInputParameters = new[] { "key" }; - testMethod.TestedMethodType = TestedMethodType.InstanceMethod; - } - + if (testMethod.Property == "new") - { - testMethod.TestedMethodType = TestedMethodType.Constructor; - testMethod.ExceptionThrown = typeof(ArgumentException); - return; - } + UpdateTestMethodForNewProperty(testMethod); + else if (testMethod.Property == "key") + UpdateTestMethodForKeyProperty(testMethod); + else + UpdateTestMethodForEncodeOrDecodeProperty(testMethod); + } - if (testMethod.Property == "key") - { - testMethod.Expected = new Regex(testMethod.Expected["match"]); - testMethod.TestedMethodType = TestedMethodType.Property; - return; - } + private static void UpdateTestMethodForNewProperty(TestMethod testMethod) + { + testMethod.TestedMethodType = TestedMethodType.Constructor; + testMethod.ExceptionThrown = typeof(ArgumentException); + } + private static void UpdateTestMethodForKeyProperty(TestMethod testMethod) + { + testMethod.Expected = new Regex(testMethod.Expected["match"]); + testMethod.TestedMethodType = TestedMethodType.Property; + } + + private void UpdateTestMethodForEncodeOrDecodeProperty(TestMethod testMethod) + { testMethod.TestedMethodType = TestedMethodType.InstanceMethod; if (testMethod.Input.TryGetValue("ciphertext", out var cipherText)) @@ -44,7 +49,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) { var plaintext = Render.Object(testMethod.Input["plaintext"]); testMethod.Input["ciphertext"] = new UnescapedValue($"sut.Encode({plaintext})"); - testMethod.InputParameters = new[] { "ciphertext" }; + testMethod.InputParameters = new[] {"ciphertext"}; } } diff --git a/generators/Exercises/Generators/SpiralMatrix.cs b/generators/Exercises/Generators/SpiralMatrix.cs index 1cebbca7ef..f85212eaf6 100644 --- a/generators/Exercises/Generators/SpiralMatrix.cs +++ b/generators/Exercises/Generators/SpiralMatrix.cs @@ -12,6 +12,6 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.Expected = ConvertExpected(testMethod.Expected); } - private static int[,] ConvertExpected(JArray jArray) => jArray.ToObject(); + private static int[,] ConvertExpected(JToken jArray) => jArray.ToObject(); } } diff --git a/generators/Exercises/Generators/TwoBucket.cs b/generators/Exercises/Generators/TwoBucket.cs index ea5059d283..051ce53870 100644 --- a/generators/Exercises/Generators/TwoBucket.cs +++ b/generators/Exercises/Generators/TwoBucket.cs @@ -7,11 +7,12 @@ public class TwoBucket : GeneratorExercise { protected override void UpdateTestMethod(TestMethod testMethod) { + testMethod.UseVariableForTested = true; + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; testMethod.ConstructorInputParameters = new[] { "bucketOne", "bucketTwo", "startBucket" }; - testMethod.Input["startBucket"] = Render.Enum("Bucket", testMethod.Input["startBucket"]); - testMethod.UseVariableForTested = true; + testMethod.Assert = RenderAssert(testMethod); } diff --git a/generators/Exercises/Generators/WordSearch.cs b/generators/Exercises/Generators/WordSearch.cs index 925c5d814f..b3bcf2ed72 100644 --- a/generators/Exercises/Generators/WordSearch.cs +++ b/generators/Exercises/Generators/WordSearch.cs @@ -20,11 +20,14 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.ConstructorInputParameters = new[] { "grid" }; testMethod.Input["grid"] = new MultiLineString(testMethod.Input["grid"]); - testMethod.Expected = ((IDictionary)testMethod.Expected).ToDictionary(kv => kv.Key, kv => (((int, int), (int, int))?)ConvertToPosition(kv.Value)); + testMethod.Expected = ConvertExpected(testMethod); testMethod.Assert = RenderAssert(testMethod); } + private static Dictionary ConvertExpected(TestMethod testMethod) + => ((IDictionary)testMethod.Expected).ToDictionary(kv => kv.Key, kv => (((int, int), (int, int))?)ConvertToPosition(kv.Value)); + private string RenderAssert(TestMethod testMethod) { var assert = new StringBuilder(); From f2d030df0ef61d3785a6005e74148081f651cdf0 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 8 Jul 2018 19:18:59 +0200 Subject: [PATCH 89/97] generators: Simplify flatten-array generator --- exercises/flatten-array/FlattenArrayTest.cs | 128 +++++------------- .../Exercises/Generators/FlattenArray.cs | 27 ++-- generators/Helpers/NameExtensions.cs | 2 + 3 files changed, 53 insertions(+), 104 deletions(-) diff --git a/exercises/flatten-array/FlattenArrayTest.cs b/exercises/flatten-array/FlattenArrayTest.cs index 9d66683805..bfc348b279 100644 --- a/exercises/flatten-array/FlattenArrayTest.cs +++ b/exercises/flatten-array/FlattenArrayTest.cs @@ -7,7 +7,12 @@ public class FlattenArrayTest [Fact] public void No_nesting() { - var array = new[] { 0, 1, 2 }; + var array = new object[] + { + 0, + 1, + 2 + }; var expected = new[] { 0, 1, 2 }; Assert.Equal(expected, FlattenArray.Flatten(array)); } @@ -15,17 +20,11 @@ public void No_nesting() [Fact(Skip = "Remove to run test")] public void Flattens_array_with_just_integers_present() { - var array = new object[] { - 1, - new object[] { - 2, - 3, - 4, - 5, - 6, - 7 - }, - 8 + var array = new object[] + { + 1, + new object[] { 2, 3, 4, 5, 6, 7 }, + 8 }; var expected = new[] { 1, 2, 3, 4, 5, 6, 7, 8 }; Assert.Equal(expected, FlattenArray.Flatten(array)); @@ -34,26 +33,12 @@ public void Flattens_array_with_just_integers_present() [Fact(Skip = "Remove to run test")] public void Number_5_level_nesting() { - var array = new object[] { - 0, - 2, - new object[] { - new object[] { - 2, - 3 - }, - 8, - 100, - 4, - new object[] { - new object[] { - new object[] { - 50 - } - } - } - }, - -2 + var array = new object[] + { + 0, + 2, + new object[] { new object[] { 2, 3 }, 8, 100, 4, new object[] { new object[] { new object[] { 50 } } } }, + -2 }; var expected = new[] { 0, 2, 2, 3, 8, 100, 4, 50, -2 }; Assert.Equal(expected, FlattenArray.Flatten(array)); @@ -62,27 +47,11 @@ public void Number_5_level_nesting() [Fact(Skip = "Remove to run test")] public void Number_6_level_nesting() { - var array = new object[] { - 1, - new object[] { - 2, - new object[] { - new object[] { - 3 - } - }, - new object[] { - 4, - new object[] { - new object[] { - 5 - } - } - }, - 6, - 7 - }, - 8 + var array = new object[] + { + 1, + new object[] { 2, new object[] { new object[] { 3 } }, new object[] { 4, new object[] { new object[] { 5 } } }, 6, 7 }, + 8 }; var expected = new[] { 1, 2, 3, 4, 5, 6, 7, 8 }; Assert.Equal(expected, FlattenArray.Flatten(array)); @@ -91,28 +60,12 @@ public void Number_6_level_nesting() [Fact(Skip = "Remove to run test")] public void Number_6_level_nest_list_with_null_values() { - var array = new object[] { - 0, - 2, - new object[] { - new object[] { - 2, - 3 - }, - 8, - new object[] { - new object[] { - 100 - } - }, - null, - new object[] { - new object[] { - null - } - } - }, - -2 + var array = new object[] + { + 0, + 2, + new object[] { new object[] { 2, 3 }, 8, new object[] { new object[] { 100 } }, null, new object[] { new object[] { null } } }, + -2 }; var expected = new[] { 0, 2, 2, 3, 8, 100, -2 }; Assert.Equal(expected, FlattenArray.Flatten(array)); @@ -121,25 +74,14 @@ public void Number_6_level_nest_list_with_null_values() [Fact(Skip = "Remove to run test")] public void All_values_in_nested_list_are_null() { - var array = new object[] { - null, - new object[] { - new object[] { - new object[] { - null - } - } - }, - null, - null, - new object[] { - new object[] { - null, - null - }, + var array = new object[] + { + null, + new object[] { new object[] { new object[] { null } } }, + null, + null, + new object[] { new object[] { null, null }, null }, null - }, - null }; Assert.Empty(FlattenArray.Flatten(array)); } diff --git a/generators/Exercises/Generators/FlattenArray.cs b/generators/Exercises/Generators/FlattenArray.cs index 4a26f0f4ff..3a9cf04f25 100644 --- a/generators/Exercises/Generators/FlattenArray.cs +++ b/generators/Exercises/Generators/FlattenArray.cs @@ -1,5 +1,7 @@ +using System.Linq; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; +using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { @@ -10,19 +12,22 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.UseVariablesForInput = true; testMethod.UseVariableForExpected = true; - var stringInput = testMethod.Input["array"].ToString(); + var renderedArray = Render.ArrayMultiLine(ConvertToObjectArray(testMethod.Input["array"])); + testMethod.Input["array"] = new UnescapedValue(renderedArray.Replace("new[]", "new object[]")); + } - // We skip rendering of pure int arrays. - if (stringInput.Contains("System.Int32")) - return; + private static dynamic ConvertToObjectArray(dynamic input) + { + if (input is int[] ints) + return ints; - testMethod.Input["array"] = new UnescapedValue(ConvertToObjectArray(stringInput)); - } + if (input is JArray jArray) + return jArray.Cast().Select(ConvertToObjectArray).ToArray(); - private static string ConvertToObjectArray(string input) - => input - .Replace("System.Int32", "") - .Replace("]", "}") - .Replace("[", "new object[] {"); + if (input is JToken jToken && jToken.Type == JTokenType.Null) + return null; + + return input; + } } } \ No newline at end of file diff --git a/generators/Helpers/NameExtensions.cs b/generators/Helpers/NameExtensions.cs index f486cc79d2..d91690a6ec 100644 --- a/generators/Helpers/NameExtensions.cs +++ b/generators/Helpers/NameExtensions.cs @@ -71,6 +71,8 @@ public static string ToFriendlyName(this Type type) return "string"; if (type == typeof(char)) return "char"; + if (type == typeof(object)) + return "object"; if (type.IsGenericType && ValueTupleTypes.Contains(type.GetGenericTypeDefinition())) return $"({string.Join(", ", type.GetGenericArguments().Select(ToFriendlyName))})"; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) From 816b0a9f0b6e348483d47fca41859c685a815a4e Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 8 Jul 2018 19:29:35 +0200 Subject: [PATCH 90/97] generators: Refactor test method output --- generators/Output/TestMethodOutput.cs | 73 ++++++++++++++------------- 1 file changed, 38 insertions(+), 35 deletions(-) diff --git a/generators/Output/TestMethodOutput.cs b/generators/Output/TestMethodOutput.cs index 163741ea25..0b2c773309 100644 --- a/generators/Output/TestMethodOutput.cs +++ b/generators/Output/TestMethodOutput.cs @@ -12,70 +12,71 @@ namespace Exercism.CSharp.Output { public class TestMethodOutput { - private readonly TestMethod _testMethod; - - public TestMethodOutput(TestMethod testMethod) => _testMethod = testMethod; - private const string SutVariableName = "sut"; private const string TestedVariableName = "actual"; private const string ExpectedVariableName = "expected"; - - private static readonly Render Renderer = new Render(); - - public string SutValue => $"new {_testMethod.TestedClass}({ConstructorParameters})"; - public string TestedValue => _testMethod.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; - public string ExpectedParameter => _testMethod.UseVariableForExpected ? ExpectedVariableName : Renderer.Object(_testMethod.Expected); - private string InputParameters => string.Join(", ", _testMethod.InputParameters.Select(key => _testMethod.UseVariablesForInput ? key.ToVariableName() : Renderer.Object(_testMethod.Input[key]))); - private string ConstructorParameters => string.Join(", ", _testMethod.ConstructorInputParameters.Select(key => _testMethod.UseVariablesForConstructorParameters ? key.ToVariableName() : Renderer.Object(_testMethod.Input[key]))); + private static readonly Render Renderer = new Render(); + private readonly TestMethod _testMethod; - private string ExpectedVariableDeclaration => Renderer.Variable(ExpectedVariableName, Renderer.ObjectMultiLine(_testMethod.Expected)); - private IEnumerable InputVariablesDeclaration => Renderer.Variables(_testMethod.InputParameters.ToDictionary(key => key, key => _testMethod.Input[key])); - private IEnumerable ConstructorVariablesDeclaration => Renderer.Variables(_testMethod.ConstructorInputParameters.ToDictionary(key => key, key => _testMethod.Input[key])); - private IEnumerable SutVariableDeclaration => new[] { Renderer.Variable(SutVariableName, SutValue) }; - private IEnumerable ActualVariableDeclaration => new[] { Renderer.Variable(TestedVariableName, TestedMethodInvocation) }; + public TestMethodOutput(TestMethod testMethod) => _testMethod = testMethod; - public IEnumerable Variables + private IEnumerable Variables { get { var lines = new List(); if (_testMethod.UseVariablesForInput) - lines.AddRange(InputVariablesDeclaration); + lines.AddRange(InputVariables); if (_testMethod.UseVariablesForConstructorParameters) - lines.AddRange(ConstructorVariablesDeclaration); + lines.AddRange(ConstructorVariables); if (_testMethod.UseVariableForSut) - lines.AddRange(SutVariableDeclaration); + lines.Add(SutVariableDeclaration); if (_testMethod.UseVariableForTested) - lines.AddRange(ActualVariableDeclaration); + lines.Add(TestedVariable); if (_testMethod.UseVariableForExpected) - lines.Add(ExpectedVariableDeclaration); + lines.Add(ExpectedVariable); return lines; } } - - public string TestedMethodInvocation + + private IEnumerable InputVariables => Renderer.Variables(_testMethod.InputParameters.ToDictionary(key => key, key => _testMethod.Input[key])); + private string InputValues => string.Join(", ", _testMethod.InputParameters.Select(key => _testMethod.UseVariablesForInput ? key.ToVariableName() : Renderer.Object(_testMethod.Input[key]))); + + private IEnumerable ConstructorVariables => Renderer.Variables(_testMethod.ConstructorInputParameters.ToDictionary(key => key, key => _testMethod.Input[key])); + private string ConstructorValues => string.Join(", ", _testMethod.ConstructorInputParameters.Select(key => _testMethod.UseVariablesForConstructorParameters ? key.ToVariableName() : Renderer.Object(_testMethod.Input[key]))); + + private string SutVariableDeclaration => Renderer.Variable(SutVariableName, SutParameter); + private string SutParameter => _testMethod.UseVariableForSut ? $"new {_testMethod.TestedClass}({ConstructorValues})" : SutVariableName; + + private string TestedVariable => Renderer.Variable(TestedVariableName, TestedMethodInvocation); + private string TestedValue => _testMethod.UseVariableForTested ? TestedVariableName : TestedMethodInvocation; + + private string ExpectedVariable => Renderer.Variable(ExpectedVariableName, Renderer.ObjectMultiLine(_testMethod.Expected)); + private string ExpectedValue => _testMethod.UseVariableForExpected ? ExpectedVariableName : Renderer.Object(_testMethod.Expected); + + private string TestedMethodInvocation { get { switch (_testMethod.TestedMethodType) { case TestedMethodType.StaticMethod: - return $"{_testMethod.TestedClass}.{_testMethod.TestedMethod}({InputParameters})"; + return $"{_testMethod.TestedClass}.{_testMethod.TestedMethod}({InputValues})"; case TestedMethodType.ExtensionMethod: - return $"{InputParameters}.{_testMethod.TestedMethod}()"; + return $"{InputValues}.{_testMethod.TestedMethod}()"; case TestedMethodType.InstanceMethod: - return $"{SutVariableName}.{_testMethod.TestedMethod}({InputParameters})"; + return $"{SutVariableName}.{_testMethod.TestedMethod}({InputValues})"; case TestedMethodType.Property: return $"{SutVariableName}.{_testMethod.TestedMethod}"; case TestedMethodType.Constructor: - return $"new {_testMethod.TestedClass}({ConstructorParameters})"; + return $"new {_testMethod.TestedClass}({ConstructorValues})"; default: throw new ArgumentOutOfRangeException(); } @@ -84,13 +85,13 @@ public string TestedMethodInvocation public string Render() { - UpdateBasedOnCurrentAssertType(); + Update(); _testMethod.Arrange = _testMethod.Arrange ?? RenderArrange(); _testMethod.Act = _testMethod.Act ?? RenderAct(); _testMethod.Assert = _testMethod.Assert ?? RenderAssert(); - return Template.Render("TestMethod", new { Name = _testMethod.TestMethodName, _testMethod.Skip, _testMethod.Arrange, _testMethod.Act, _testMethod.Assert }); + return Template.Render("TestMethod", RenderValues); } private string RenderArrange() => Template.Render("Arrange", new { Variables }); @@ -102,9 +103,9 @@ private string RenderAssert() switch (CurrentAssertType) { case AssertType.Equal: - return Renderer.AssertEqual(ExpectedParameter, TestedValue); + return Renderer.AssertEqual(ExpectedValue, TestedValue); case AssertType.Empty: - return Renderer.AssertEmpty(ExpectedParameter, TestedValue); + return Renderer.AssertEmpty(ExpectedValue, TestedValue); case AssertType.Null: return Renderer.AssertNull(TestedValue); case AssertType.Throws: @@ -112,13 +113,15 @@ private string RenderAssert() case AssertType.Boolean: return Renderer.AssertBoolean(Convert.ToBoolean(_testMethod.Expected), TestedValue); case AssertType.Matches: - return Renderer.AssertMatches(ExpectedParameter, TestedValue); + return Renderer.AssertMatches(ExpectedValue, TestedValue); default: throw new ArgumentOutOfRangeException(); } } + + private object RenderValues => new { Name = _testMethod.TestMethodName, _testMethod.Skip, _testMethod.Arrange, _testMethod.Act, _testMethod.Assert }; - private void UpdateBasedOnCurrentAssertType() + private void Update() { switch (CurrentAssertType) { From 8eb23b920ef4f48a91c82cd44369924e116301e7 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 8 Jul 2018 20:27:47 +0200 Subject: [PATCH 91/97] generators: Update docs --- docs/GENERATORS.md | 223 +++++++++++++++--- generators/Exercises/Generators/Matrix.cs | 1 - .../Generators/PalindromeProducts.cs | 10 +- 3 files changed, 187 insertions(+), 47 deletions(-) diff --git a/docs/GENERATORS.md b/docs/GENERATORS.md index c8809145c7..21865fdc9d 100644 --- a/docs/GENERATORS.md +++ b/docs/GENERATORS.md @@ -1,4 +1,4 @@ -# Test Generators +# Test generators Test generators allow tracks to generate tests automatically without having to write them ourselves. Each test generator reads from the exercise's `canonical data`, which defines the name of the test, its inputs, and outputs. You can read more about exercism's approach to test suites [here](https://github.com/exercism/docs/blob/master/language-tracks/exercises/anatomy/test-suites.md). @@ -6,7 +6,8 @@ Generating tests automatically removes any sort of user error when creating test An example of a canonical data file can be found [here](https://github.com/exercism/problem-specifications/blob/master/exercises/bob/canonical-data.json) -## Common Terms +## Common terms + When looking through the canonical data and the generator code base, we use a lot of common terminology. This list hopefully clarifies what they represent. - Canonical Data - Represents the entire test suite. @@ -16,13 +17,14 @@ When looking through the canonical data and the generator code base, we use a lo - Input - The input for the test case. - Expected - The expected value when running the test case. -## Adding A Simple Generator -Adding a test generator file is straightforward. Simply add a new file to the generators folder with the name of the exercise (in PascalCase), and extend the `GeneratorExercise` abstract class. +## Adding a simple generator + +Adding a test generator file is straightforward. Simply add a new file to the `Exercises/Generators` folder with the name of the exercise (in PascalCase), and extend the `GeneratorExercise` abstract class. -An example of a simple generator would be the Bob exercise. The source is below, but you can freely view it in the repository [here](https://github.com/exercism/csharp/blob/master/generators/Exercises/Bob.cs). +An example of a simple generator would be the Bob exercise. The source is displayed below, but you can freely view it in the repository [here](https://github.com/exercism/csharp/blob/master/generators/Exercises/Bob.cs). ```csharp -namespace Generators.Exercises +namespace Exercism.CSharp.Exercises.Generators { public class Bob : GeneratorExercise { @@ -32,71 +34,215 @@ namespace Generators.Exercises This is a fully working generator, no other code needs to be written. However, it's simplicity stems from the fact that the test suite and the program itself are relatively trivial. -## Adding A Complex Generator +## Adding a complex generator + +When the default generator output is not sufficient, you can override the `GeneratorExercise` class' virtual methods to override the default behavior. -A more *complex* generator would be the ComplexNumbers generator found [here](https://github.com/exercism/csharp/blob/master/generators/Exercises/ComplexNumbers.cs). +### Method 1: UpdateTestMethod(TestMethod testMethod) -The `GeneratorExercise` abstract class currently exposes five methods that are used for overriding the default behavior when generating an exercise. +Update the test method that described the test method being generated. When you are required to customize a test generator, overriding this method is virtually always what you want to do. -### void UpdateCanonicalData(CanonicalData canonicalData) -Update the canonical data for a given test. +There are many things that can be customized, of which we'll list the more common usages. -The most common use for this override is to iterate over each of the canonical data cases. +#### Customize test data -As an example, if you wanted to change the default behavior so that when the `Input` value of a test is a negative number, an exception should be thrown, the code would look like this. +There are quite some generators that want to change the input or expected value. + +An example of this is the [bracket-push](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/BracketPush.cs) generator, which input value with the key `"value"` requires some additional escaping: ```csharp -protected override void UpdateCanonicalData(CanonicalData canonicalData) +protected override void UpdateTestMethod(TestMethod testMethod) { - foreach (var canonicalDataCase in canonicalData.Cases) - { - var caseInputLessThanZero = (long)canonicalDataCase.Input["number"] < 0; - canonicalDataCase.ExceptionThrown = caseInputLessThanZero ? typeof(ArgumentException) : null; - } + testMethod.Input["value"] = testMethod.Input["value"].Replace("\\", "\\\\"); + // [...] } ``` -### HashSet\ AddAdditionalNamespaces() -Allows more namespaces to be added to the test suite. +Another common use case is to handle empty arrays. If an array is empty, its type will default to `JArray`, which doesn't have any type information. To allow the generator to output a correctly typed array, we have to convert the `JArray` to an array first. -The tests use `Xunit` so all tests will automatically include the `Xunit` namespace. However, more advanced tests may require additional namespaces. +An example of this is the [proverb](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/Proverb.cs) generator, which converts the `JArray` to an empty `string` array: ```csharp -protected override HashSet AddAdditionalNamespaces() +protected override void UpdateTestMethod(TestMethod testMethod) { - return new HashSet() - { - typeof(Dictionary).Namespace - }; + // [...] + + if (testMethod.Input["strings"] is JArray) + testMethod.Input["strings"] = Array.Empty(); + + if (testMethod.Expected is JArray) + testMethod.Expected = Array.Empty(); +} +``` + +#### Output test data as variables + +Sometimes, it might make sense to not define a test method's data inline, but as variables. + +An example of this is the [crypto square](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/CryptoSquare.cs) generator, which indicates that both the test method input as well as the expected value, should be stored in variables: + +```csharp +protected override void UpdateTestMethod(TestMethod testMethod) +{ + testMethod.UseVariablesForInput = true; + testMethod.UseVariableForExpected = true; +} +``` + +#### Custom tested method type + +By default, the generator will test a static method. However, you can also test for instance methods, extension methods, properties and constructors. + +An example of this is the [roman numerals](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/RomanNumerals.cs) generator, which indicates that it tests an extensions method: + +```csharp +protected override void UpdateTestMethod(TestMethod testMethod) +{ + testMethod.TestedMethodType = TestedMethodType.ExtensionMethod; + testMethod.TestedMethod = "ToRoman"; } ``` -This snippet would add the namespace that the `Dictionary` collection lives in (`System.Collections.Generic`). +#### Change names used + +As we saw in the previous example, you can also customize the name of the tested method. You are also allowed to customize the tested class' name and the test method name. -### string RenderTestMethodBody[Arrange/Act/Assert] -Override the default behavior when rendering a test methods arrange, act, and/or assert sections. +An example of this is the [triangle](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/Triangle.cs) generator, which by default generates duplicate test method names (which will be a compile-time error), but instead uses the `TestMethodNameWithPath` to use the full path as the test method name (effectively making the test method name unique): + +```csharp +protected override void UpdateTestMethod(TestMethod testMethod) +{ + // [...] + testMethod.TestMethodName = testMethod.TestMethodNameWithPath; + // [...] +} +``` -More advanced tests may need to leverage a `template`. A template allows you to add additional code to a test and assert more complex statements. +#### Test for an exception being thrown -An example of this is the [RunLengthEncoding](https://github.com/exercism/csharp/blob/master/generators/Exercises/RunLengthEncoding.cs) test. +Some test methods want to verify that an exception is being thrown. -Here the **Assert** is being overridden. The assert needs to call additional functions, but only if the property is `consistency`. Otherwise, render the assert as usual. +An example of this is the [RNA transcription]() generator, which defines that some test methods should throws an `ArgumentException`: -### string[] RenderAdditionalMethods() -Allow additional methods to be added to the test suite. +```csharp +protected override void UpdateTestMethod(TestMethod testMethod) +{ + if (testMethod.Expected is null) + testMethod.ExceptionThrown = typeof(ArgumentException); +} +``` -There may exist cases where a suite of unit tests will need to reuse the same logic in each of the tests. Rather than duplicating code, this method allows you to provide helper methods for the tests. +Note that `ArgumentException` type's namespace will be automatically added to the list of namespaces used in the test class. -An example of this is the [Tournament](https://github.com/exercism/csharp/blob/master/generators/Exercises/Tournament.cs#L45) generator. +#### Custom input/constructor parameters -Additional methods added using this override will be added to the bottom of the test suite. +In some case, you might want to override the parameters that are used as input parameters. + +An example of this is the [two fer]() generator, which does not use any input parameters when the `"name"` input parameter is set to `null`: + +```csharp +protected override void UpdateTestMethod(TestMethod testMethod) +{ + // [...] + + if (testMethod.Input["name"] is null) + testMethod.InputParameters = Array.Empty(); +} +``` + +If a test method tests an instance method, you can also specify which parameters to use as constructor parameters (the others will be input parameters, unless specified otherwise). + +An example of this is the [matrix]() generator, which specifies that the `"string"` parameter should be passed as a constructor parameter: + +```csharp +protected override void UpdateTestMethod(TestMethod testMethod) +{ + testMethod.TestedMethodType = TestedMethodType.InstanceMethod; + testMethod.ConstructorInputParameters = new[] { "string" }; +} +``` + +#### Custom arrange/act/assert code + +Although this should be used as a last resort, some generators might want to skip the default generation completely and control which arrange, act or assert code the test method should contain. + +An example of this is the [run-length-encoding](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/RunLengthEncoding.cs) generator, which uses a custom assertion for one specific property: + +```csharp +protected override void UpdateTestMethod(TestMethod testMethod) +{ + // [...] + + if (testMethod.Property == "consistency") + testMethod.Assert = RenderConsistencyToAssert(testMethod); +} + +private string RenderConsistencyToAssert(TestMethod testMethod) +{ + var expected = Render.Object(testMethod.Expected); + var actual = $"{testMethod.TestedClass}.Decode({testMethod.TestedClass}.Encode({expected}))"; + return Render.AssertEqual(expected, actual); +} +``` + +Note that the `Render` instance is used to render the assertion and the expected value. + +### Method 2: UpdateNamespaces(ISet namespaces) + +Allows additional namespaces to be added to the test suite. + +All tests use the `Xunit` framework, so each test class will automatically include the `Xunit` namespace. However, some test classes may require additional namespaces. + +An example of this is the [gigasecond](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/Gigasecond.cs) generator, which uses the `DateTime` class in its test methods, and thus adds its namespace to the list of namespaces: + +```csharp +protected override void UpdateNamespaces(ISet namespaces) +{ + namespaces.Add(typeof(DateTime).Namespace); +} +``` + +Note that as mentioned before, the namespace of any thrown exception types are automaticall added to the list of namespaces. + +### Method 3: UpdateTestClass(TestClass testClass) + +This method allows you to customize the output of the test class. Only in rare cases would you want to override this method. The most common use case to override this method, is to add additional (helper) methods to the test suite. + +An example of this is the [Tournament](https://github.com/exercism/csharp/blob/master/generators/Exercises/Tournament.cs) generator, which adds a helper method to the test suite: + +```csharp +protected override void UpdateTestClass(TestClass testClass) +{ + AddRunTallyMethod(testClass); +} + +private static void AddRunTallyMethod(TestClass testClass) +{ + testClass.AdditionalMethods.Add(@" +private string RunTally(string input) +{ + var encoding = new UTF8Encoding(); + + using (var inStream = new MemoryStream(encoding.GetBytes(input))) + using (var outStream = new MemoryStream()) + { + Tournament.Tally(inStream, outStream); + return encoding.GetString(outStream.ToArray()); + } +}"); +} +``` + +Additional methods will be added to the bottom of the test suite. ## Updating Existing Files + It is possible that an existing exercise does not match the canonical data. It is OK to update the exercise stub and/or the exercise example to follow the canonical data! An example might be that an exercise is named SumOfMultiples, but the SumOfMultiples.cs and Example.cs files both use `Multiples` as the name of the class. Also, if you find an issue with one of the existing generators or test suites simply open up the generator that you would like to update, make your changes, and then run the generators. ## Running The Generators + This repository is coded against [.NET Core](https://www.microsoft.com/net/core). To run the generators all you need to do is run the following command in the generators directory: `dotnet run` @@ -112,4 +258,5 @@ Once the generator has been run, you can view the output of your generation by n `exercises/bob/BobTest.cs` ## Submitting A Generator + If you are satisfied with the output of your generator, we would love for you to submit a pull request! Please include your generator, updated test suite, and any other corresponding files that you may have changed. diff --git a/generators/Exercises/Generators/Matrix.cs b/generators/Exercises/Generators/Matrix.cs index 62e2689250..9f18faba59 100644 --- a/generators/Exercises/Generators/Matrix.cs +++ b/generators/Exercises/Generators/Matrix.cs @@ -8,7 +8,6 @@ protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.TestedMethodType = TestedMethodType.InstanceMethod; testMethod.ConstructorInputParameters = new[] { "string" }; - testMethod.InputParameters = new[] { "index" }; } } } diff --git a/generators/Exercises/Generators/PalindromeProducts.cs b/generators/Exercises/Generators/PalindromeProducts.cs index 098574e618..93bfbc810c 100644 --- a/generators/Exercises/Generators/PalindromeProducts.cs +++ b/generators/Exercises/Generators/PalindromeProducts.cs @@ -19,18 +19,12 @@ protected override void UpdateTestMethod(TestMethod testMethod) testMethod.UseVariableForTested = true; testMethod.UseVariableForExpected = true; testMethod.Expected = (testMethod.Expected["value"], RenderCoordinates(testMethod.Expected["factors"])); + testMethod.Assert = RenderAssert(); } - - testMethod.Assert = RenderAssert(testMethod); } - private string RenderAssert(TestMethod testMethod) + private string RenderAssert() { - if (testMethod.ExceptionThrown != null) - { - return testMethod.Assert; - } - var assert = new StringBuilder(); assert.AppendLine(Render.AssertEqual("expected.Item1", "actual.Item1")); assert.AppendLine(Render.AssertEqual("expected.Item2", "actual.Item2")); From cc593f9058023f25a92d96d116040fddab70b0be Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 9 Jul 2018 21:24:57 +0200 Subject: [PATCH 92/97] generators: Add missing links to docs and use consistent naming --- docs/GENERATORS.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/GENERATORS.md b/docs/GENERATORS.md index 21865fdc9d..0bb336e42a 100644 --- a/docs/GENERATORS.md +++ b/docs/GENERATORS.md @@ -79,7 +79,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) Sometimes, it might make sense to not define a test method's data inline, but as variables. -An example of this is the [crypto square](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/CryptoSquare.cs) generator, which indicates that both the test method input as well as the expected value, should be stored in variables: +An example of this is the [crypto-square](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/CryptoSquare.cs) generator, which indicates that both the test method input as well as the expected value, should be stored in variables: ```csharp protected override void UpdateTestMethod(TestMethod testMethod) @@ -93,7 +93,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) By default, the generator will test a static method. However, you can also test for instance methods, extension methods, properties and constructors. -An example of this is the [roman numerals](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/RomanNumerals.cs) generator, which indicates that it tests an extensions method: +An example of this is the [roman-numerals](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/RomanNumerals.cs) generator, which indicates that it tests an extensions method: ```csharp protected override void UpdateTestMethod(TestMethod testMethod) @@ -122,7 +122,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) Some test methods want to verify that an exception is being thrown. -An example of this is the [RNA transcription]() generator, which defines that some test methods should throws an `ArgumentException`: +An example of this is the [rna-transcription](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/RnaTranscription.cs) generator, which defines that some test methods should throws an `ArgumentException`: ```csharp protected override void UpdateTestMethod(TestMethod testMethod) @@ -138,7 +138,7 @@ Note that `ArgumentException` type's namespace will be automatically added to th In some case, you might want to override the parameters that are used as input parameters. -An example of this is the [two fer]() generator, which does not use any input parameters when the `"name"` input parameter is set to `null`: +An example of this is the [two-fer](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/TwoFer.cs) generator, which does not use any input parameters when the `"name"` input parameter is set to `null`: ```csharp protected override void UpdateTestMethod(TestMethod testMethod) @@ -152,7 +152,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) If a test method tests an instance method, you can also specify which parameters to use as constructor parameters (the others will be input parameters, unless specified otherwise). -An example of this is the [matrix]() generator, which specifies that the `"string"` parameter should be passed as a constructor parameter: +An example of this is the [matrix](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/Matrix.cs) generator, which specifies that the `"string"` parameter should be passed as a constructor parameter: ```csharp protected override void UpdateTestMethod(TestMethod testMethod) @@ -208,7 +208,7 @@ Note that as mentioned before, the namespace of any thrown exception types are a This method allows you to customize the output of the test class. Only in rare cases would you want to override this method. The most common use case to override this method, is to add additional (helper) methods to the test suite. -An example of this is the [Tournament](https://github.com/exercism/csharp/blob/master/generators/Exercises/Tournament.cs) generator, which adds a helper method to the test suite: +An example of this is the [tournament](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/Tournament.cs) generator, which adds a helper method to the test suite: ```csharp protected override void UpdateTestClass(TestClass testClass) From fbe4a34c7c1ba817459260781d24ee55d93aab75 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 9 Jul 2018 21:25:30 +0200 Subject: [PATCH 93/97] go-counting: Add space between operators in example implementation --- exercises/go-counting/Example.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/exercises/go-counting/Example.cs b/exercises/go-counting/Example.cs index 289714a151..07c1538479 100644 --- a/exercises/go-counting/Example.cs +++ b/exercises/go-counting/Example.cs @@ -60,10 +60,10 @@ private bool IsValidCoordinate((int, int) coordinate) => var coords = new[] { - (col, row - 1), - (col-1, row), - (col+1, row), - (col, row+1) + (col, row - 1), + (col - 1, row), + (col + 1, row), + (col, row + 1) }; return coords.Where(IsValidCoordinate); From 523748a757e733a20679ad074919c90dbc10edfc Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Mon, 9 Jul 2018 21:30:16 +0200 Subject: [PATCH 94/97] generators: Use consistent formatting of input and expected values for minesweeper --- exercises/minesweeper/MinesweeperTest.cs | 83 ++++++++++++++++--- .../Exercises/Generators/Minesweeper.cs | 9 +- 2 files changed, 76 insertions(+), 16 deletions(-) diff --git a/exercises/minesweeper/MinesweeperTest.cs b/exercises/minesweeper/MinesweeperTest.cs index 1f6ee9b320..d8776e2703 100644 --- a/exercises/minesweeper/MinesweeperTest.cs +++ b/exercises/minesweeper/MinesweeperTest.cs @@ -9,7 +9,8 @@ public class MinesweeperTest public void No_rows() { var minefield = Array.Empty(); - Assert.Empty(Minesweeper.Annotate(minefield)); + var expected = Array.Empty(); + Assert.Equal(expected, Minesweeper.Annotate(minefield)); } [Fact(Skip = "Remove to run test")] @@ -19,7 +20,10 @@ public void No_columns() { "" }; - var expected = new[] { "" }; + var expected = new[] + { + "" + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -32,7 +36,12 @@ public void No_mines() " ", " " }; - var expected = new[] { " ", " ", " " }; + var expected = new[] + { + " ", + " ", + " " + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -45,7 +54,12 @@ public void Minefield_with_only_mines() "***", "***" }; - var expected = new[] { "***", "***", "***" }; + var expected = new[] + { + "***", + "***", + "***" + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -58,7 +72,12 @@ public void Mine_surrounded_by_spaces() " * ", " " }; - var expected = new[] { "111", "1*1", "111" }; + var expected = new[] + { + "111", + "1*1", + "111" + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -71,7 +90,12 @@ public void Space_surrounded_by_mines() "* *", "***" }; - var expected = new[] { "***", "*8*", "***" }; + var expected = new[] + { + "***", + "*8*", + "***" + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -82,7 +106,10 @@ public void Horizontal_line() { " * * " }; - var expected = new[] { "1*2*1" }; + var expected = new[] + { + "1*2*1" + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -93,7 +120,10 @@ public void Horizontal_line_mines_at_edges() { "* *" }; - var expected = new[] { "*1 1*" }; + var expected = new[] + { + "*1 1*" + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -108,7 +138,14 @@ public void Vertical_line() "*", " " }; - var expected = new[] { "1", "*", "2", "*", "1" }; + var expected = new[] + { + "1", + "*", + "2", + "*", + "1" + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -123,7 +160,14 @@ public void Vertical_line_mines_at_edges() " ", "*" }; - var expected = new[] { "*", "1", " ", "1", "*" }; + var expected = new[] + { + "*", + "1", + " ", + "1", + "*" + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -138,7 +182,14 @@ public void Cross() " * ", " * " }; - var expected = new[] { " 2*2 ", "25*52", "*****", "25*52", " 2*2 " }; + var expected = new[] + { + " 2*2 ", + "25*52", + "*****", + "25*52", + " 2*2 " + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } @@ -154,7 +205,15 @@ public void Large_minefield() " * * ", " " }; - var expected = new[] { "1*22*1", "12*322", " 123*2", "112*4*", "1*22*2", "111111" }; + var expected = new[] + { + "1*22*1", + "12*322", + " 123*2", + "112*4*", + "1*22*2", + "111111" + }; Assert.Equal(expected, Minesweeper.Annotate(minefield)); } } \ No newline at end of file diff --git a/generators/Exercises/Generators/Minesweeper.cs b/generators/Exercises/Generators/Minesweeper.cs index 828e88780e..d02f96c17d 100644 --- a/generators/Exercises/Generators/Minesweeper.cs +++ b/generators/Exercises/Generators/Minesweeper.cs @@ -12,13 +12,14 @@ protected override void UpdateTestMethod(TestMethod testMethod) { testMethod.UseVariablesForInput = true; testMethod.UseVariableForExpected = true; - - if (testMethod.Input["minefield"] is JArray) - testMethod.Input["minefield"] = Array.Empty(); - testMethod.Input["minefield"] = new UnescapedValue(Render.ArrayMultiLine(testMethod.Input["minefield"])); + testMethod.Input["minefield"] = RenderAsMultilineArray(testMethod.Input["minefield"]); + testMethod.Expected = RenderAsMultilineArray(testMethod.Expected); } + private UnescapedValue RenderAsMultilineArray(dynamic value) + => new UnescapedValue(Render.ArrayMultiLine(value as string[] ?? Array.Empty())); + protected override void UpdateNamespaces(ISet namespaces) { namespaces.Add(typeof(Array).Namespace); From e50998c227d0eb5286c3f460359ce7bb32101175 Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 10 Jul 2018 19:04:56 +0200 Subject: [PATCH 95/97] generators: Increase length for single-line array initializers --- exercises/allergies/AllergiesTest.cs | 23 +- exercises/anagram/AnagramTest.cs | 10 +- exercises/bowling/BowlingTest.cs | 296 +----------------- exercises/change/ChangeTest.cs | 19 +- exercises/dominoes/DominoesTest.cs | 13 +- exercises/poker/PokerTest.cs | 8 +- exercises/proverb/ProverbTest.cs | 6 +- .../scale-generator/ScaleGeneratorTest.cs | 32 +- exercises/word-search/WordSearchTest.cs | 36 +-- generators/Output/Rendering/Render.cs | 4 +- 10 files changed, 26 insertions(+), 421 deletions(-) diff --git a/exercises/allergies/AllergiesTest.cs b/exercises/allergies/AllergiesTest.cs index 37f0efb6b0..5f40f39dcf 100644 --- a/exercises/allergies/AllergiesTest.cs +++ b/exercises/allergies/AllergiesTest.cs @@ -88,17 +88,7 @@ public void Allergic_to_lots_of_stuff() public void Allergic_to_everything() { var sut = new Allergies(255); - var expected = new[] - { - "eggs", - "peanuts", - "shellfish", - "strawberries", - "tomatoes", - "chocolate", - "pollen", - "cats" - }; + var expected = new[] { "eggs", "peanuts", "shellfish", "strawberries", "tomatoes", "chocolate", "pollen", "cats" }; Assert.Equal(expected, sut.List()); } @@ -106,16 +96,7 @@ public void Allergic_to_everything() public void Ignore_non_allergen_score_parts() { var sut = new Allergies(509); - var expected = new[] - { - "eggs", - "shellfish", - "strawberries", - "tomatoes", - "chocolate", - "pollen", - "cats" - }; + var expected = new[] { "eggs", "shellfish", "strawberries", "tomatoes", "chocolate", "pollen", "cats" }; Assert.Equal(expected, sut.List()); } } \ No newline at end of file diff --git a/exercises/anagram/AnagramTest.cs b/exercises/anagram/AnagramTest.cs index 6775007db3..5b6e4f7b7c 100644 --- a/exercises/anagram/AnagramTest.cs +++ b/exercises/anagram/AnagramTest.cs @@ -41,15 +41,7 @@ public void Detects_anagram() [Fact(Skip = "Remove to run test")] public void Detects_three_anagrams() { - var candidates = new[] - { - "gallery", - "ballerina", - "regally", - "clergy", - "largely", - "leading" - }; + var candidates = new[] { "gallery", "ballerina", "regally", "clergy", "largely", "leading" }; var sut = new Anagram("allergy"); var expected = new[] { "gallery", "regally", "largely" }; Assert.Equal(expected, sut.Anagrams(candidates)); diff --git a/exercises/bowling/BowlingTest.cs b/exercises/bowling/BowlingTest.cs index 708d19b3ad..1d251b714a 100644 --- a/exercises/bowling/BowlingTest.cs +++ b/exercises/bowling/BowlingTest.cs @@ -60,30 +60,7 @@ public void Consecutive_spares_each_get_a_one_roll_bonus() public void A_spare_in_the_last_frame_gets_a_one_roll_bonus_that_is_counted_once() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 7, - 3, - 7 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(17, actual); @@ -123,30 +100,7 @@ public void Consecutive_strikes_each_get_the_two_roll_bonus() public void A_strike_in_the_last_frame_gets_a_two_roll_bonus_that_is_counted_once() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 10, - 7, - 1 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(18, actual); @@ -156,30 +110,7 @@ public void A_strike_in_the_last_frame_gets_a_two_roll_bonus_that_is_counted_onc public void Rolling_a_spare_with_the_two_roll_bonus_does_not_get_a_bonus_roll() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 10, - 7, - 3 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(20, actual); @@ -189,30 +120,7 @@ public void Rolling_a_spare_with_the_two_roll_bonus_does_not_get_a_bonus_roll() public void Strikes_with_the_two_roll_bonus_do_not_get_bonus_rolls() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 10, - 10, - 10 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(30, actual); @@ -222,30 +130,7 @@ public void Strikes_with_the_two_roll_bonus_do_not_get_bonus_rolls() public void A_strike_with_the_one_roll_bonus_after_a_spare_in_the_last_frame_does_not_get_a_bonus() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 7, - 3, - 10 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(20, actual); @@ -301,29 +186,7 @@ public void Bonus_roll_after_a_strike_in_the_last_frame_cannot_score_more_than_1 public void Two_bonus_rolls_after_a_strike_in_the_last_frame_cannot_score_more_than_10_points() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 10, - 5 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(6)); } @@ -332,30 +195,7 @@ public void Two_bonus_rolls_after_a_strike_in_the_last_frame_cannot_score_more_t public void Two_bonus_rolls_after_a_strike_in_the_last_frame_can_score_more_than_10_points_if_one_is_a_strike() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 10, - 10, - 6 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6 }; DoRoll(previousRolls, sut); var actual = sut.Score(); Assert.Equal(26, actual); @@ -365,29 +205,7 @@ public void Two_bonus_rolls_after_a_strike_in_the_last_frame_can_score_more_than public void The_second_bonus_rolls_after_a_strike_in_the_last_frame_cannot_be_a_strike_if_the_first_one_is_not_a_strike() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 10, - 6 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(10)); } @@ -396,29 +214,7 @@ public void The_second_bonus_rolls_after_a_strike_in_the_last_frame_cannot_be_a_ public void Second_bonus_roll_after_a_strike_in_the_last_frame_cannot_score_more_than_10_points() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 10, - 10 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(11)); } @@ -463,29 +259,7 @@ public void Bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_before_sco public void Both_bonus_rolls_for_a_strike_in_the_last_frame_must_be_rolled_before_score_can_be_calculated() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 10, - 10 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Score()); } @@ -503,30 +277,7 @@ public void Bonus_roll_for_a_spare_in_the_last_frame_must_be_rolled_before_score public void Cannot_roll_after_bonus_roll_for_spare() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 7, - 3, - 2 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 2 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(2)); } @@ -535,30 +286,7 @@ public void Cannot_roll_after_bonus_roll_for_spare() public void Cannot_roll_after_bonus_rolls_for_strike() { var sut = new BowlingGame(); - var previousRolls = new[] - { - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 10, - 3, - 2 - }; + var previousRolls = new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 3, 2 }; DoRoll(previousRolls, sut); Assert.Throws(() => sut.Roll(2)); } diff --git a/exercises/change/ChangeTest.cs b/exercises/change/ChangeTest.cs index 6e58d44197..9663ad5867 100644 --- a/exercises/change/ChangeTest.cs +++ b/exercises/change/ChangeTest.cs @@ -46,24 +46,7 @@ public void Large_target_values() { var coins = new[] { 1, 2, 5, 10, 20, 50, 100 }; var target = 999; - var expected = new[] - { - 2, - 2, - 5, - 20, - 20, - 50, - 100, - 100, - 100, - 100, - 100, - 100, - 100, - 100, - 100 - }; + var expected = new[] { 2, 2, 5, 20, 20, 50, 100, 100, 100, 100, 100, 100, 100, 100, 100 }; Assert.Equal(expected, Change.FindFewestCoins(coins, target)); } diff --git a/exercises/dominoes/DominoesTest.cs b/exercises/dominoes/DominoesTest.cs index 9adc50ea6e..5f28466d8b 100644 --- a/exercises/dominoes/DominoesTest.cs +++ b/exercises/dominoes/DominoesTest.cs @@ -85,18 +85,7 @@ public void Separate_loops() [Fact(Skip = "Remove to run test")] public void Nine_elements() { - var dominoes = new[] - { - (1, 2), - (5, 3), - (3, 1), - (1, 2), - (2, 4), - (1, 6), - (2, 3), - (3, 4), - (5, 6) - }; + var dominoes = new[] { (1, 2), (5, 3), (3, 1), (1, 2), (2, 4), (1, 6), (2, 3), (3, 4), (5, 6) }; Assert.True(Dominoes.CanChain(dominoes)); } } \ No newline at end of file diff --git a/exercises/poker/PokerTest.cs b/exercises/poker/PokerTest.cs index 5ac37e2ea2..6c49dbab90 100644 --- a/exercises/poker/PokerTest.cs +++ b/exercises/poker/PokerTest.cs @@ -25,13 +25,7 @@ public void Highest_card_out_of_all_hands_wins() [Fact(Skip = "Remove to run test")] public void A_tie_has_multiple_winners() { - var hands = new[] - { - "4D 5S 6S 8D 3C", - "2S 4C 7S 9H 10H", - "3S 4S 5D 6H JH", - "3H 4H 5C 6C JD" - }; + var hands = new[] { "4D 5S 6S 8D 3C", "2S 4C 7S 9H 10H", "3S 4S 5D 6H JH", "3H 4H 5C 6C JD" }; var actual = Poker.BestHands(hands); var expected = new[] { "3S 4S 5D 6H JH", "3H 4H 5C 6C JD" }; Assert.Equal(expected, actual); diff --git a/exercises/proverb/ProverbTest.cs b/exercises/proverb/ProverbTest.cs index c094d74e73..aa4ef8bacd 100644 --- a/exercises/proverb/ProverbTest.cs +++ b/exercises/proverb/ProverbTest.cs @@ -21,11 +21,7 @@ public void One_piece() [Fact(Skip = "Remove to run test")] public void Two_pieces() { - var expected = new[] - { - "For want of a nail the shoe was lost.", - "And all for the want of a nail." - }; + var expected = new[] { "For want of a nail the shoe was lost.", "And all for the want of a nail." }; Assert.Equal(expected, Proverb.Recite(new[] { "nail", "shoe" })); } diff --git a/exercises/scale-generator/ScaleGeneratorTest.cs b/exercises/scale-generator/ScaleGeneratorTest.cs index fa8f80a38c..3f5e9e0870 100644 --- a/exercises/scale-generator/ScaleGeneratorTest.cs +++ b/exercises/scale-generator/ScaleGeneratorTest.cs @@ -7,42 +7,14 @@ public class ScaleGeneratorTest [Fact] public void Chromatic_scale_with_sharps() { - var expected = new[] - { - "C", - "C#", - "D", - "D#", - "E", - "F", - "F#", - "G", - "G#", - "A", - "A#", - "B" - }; + var expected = new[] { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; Assert.Equal(expected, ScaleGenerator.Pitches("C")); } [Fact(Skip = "Remove to run test")] public void Chromatic_scale_with_flats() { - var expected = new[] - { - "F", - "Gb", - "G", - "Ab", - "A", - "Bb", - "B", - "C", - "Db", - "D", - "Eb", - "E" - }; + var expected = new[] { "F", "Gb", "G", "Ab", "A", "Bb", "B", "C", "Db", "D", "Eb", "E" }; Assert.Equal(expected, ScaleGenerator.Pitches("F")); } diff --git a/exercises/word-search/WordSearchTest.cs b/exercises/word-search/WordSearchTest.cs index 1f98fd0a20..be9f85e29d 100644 --- a/exercises/word-search/WordSearchTest.cs +++ b/exercises/word-search/WordSearchTest.cs @@ -374,16 +374,7 @@ public void Should_locate_words_written_bottom_right_to_top_left() [Fact(Skip = "Remove to run test")] public void Should_locate_words_written_bottom_left_to_top_right() { - var wordsToSearchFor = new[] - { - "clojure", - "elixir", - "ecmascript", - "rust", - "java", - "lua", - "lisp" - }; + var wordsToSearchFor = new[] { "clojure", "elixir", "ecmascript", "rust", "java", "lua", "lisp" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -419,17 +410,7 @@ public void Should_locate_words_written_bottom_left_to_top_right() [Fact(Skip = "Remove to run test")] public void Should_locate_words_written_top_right_to_bottom_left() { - var wordsToSearchFor = new[] - { - "clojure", - "elixir", - "ecmascript", - "rust", - "java", - "lua", - "lisp", - "ruby" - }; + var wordsToSearchFor = new[] { "clojure", "elixir", "ecmascript", "rust", "java", "lua", "lisp", "ruby" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + @@ -467,18 +448,7 @@ public void Should_locate_words_written_top_right_to_bottom_left() [Fact(Skip = "Remove to run test")] public void Should_fail_to_locate_a_word_that_is_not_in_the_puzzle() { - var wordsToSearchFor = new[] - { - "clojure", - "elixir", - "ecmascript", - "rust", - "java", - "lua", - "lisp", - "ruby", - "haskell" - }; + var wordsToSearchFor = new[] { "clojure", "elixir", "ecmascript", "rust", "java", "lua", "lisp", "ruby", "haskell" }; var grid = "jefblpepre\n" + "camdcimgtc\n" + diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 2aac028768..53d2cd0259 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -7,7 +7,7 @@ namespace Exercism.CSharp.Output.Rendering { public partial class Render { - private const int MaximumLengthForSingleLineValue = 68; + private const int MaximumLengthForSingleLineValue = 108; public string Object(object val) { @@ -70,7 +70,7 @@ private static bool IsArray(object obj) private static bool IsDictionary(object obj) => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>); - private static bool RenderAsSingleLine(T[,] elements) => false; + private static bool RenderAsSingleLine(T[,] _) => false; private bool RenderAsSingleLine(T[] elements) => !elements.Any() || IsNotArrayOfArrays(elements) && RenderedAsSingleLineDoesNotExceedMaximumLength(elements); From 27643414ce487e332e4c541e156da2208d68dc8d Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Tue, 10 Jul 2018 19:15:56 +0200 Subject: [PATCH 96/97] generators: Remove automatic multi-line rendering for one-dimensional arrays --- exercises/proverb/ProverbTest.cs | 57 +++++- exercises/sieve/SieveTest.cs | 172 +----------------- .../VariableLengthQuantityTest.cs | 38 +--- generators/Exercises/Generators/Proverb.cs | 14 +- generators/Exercises/Generators/Sieve.cs | 6 + generators/Output/Rendering/Render.cs | 23 +-- 6 files changed, 75 insertions(+), 235 deletions(-) diff --git a/exercises/proverb/ProverbTest.cs b/exercises/proverb/ProverbTest.cs index aa4ef8bacd..392225e960 100644 --- a/exercises/proverb/ProverbTest.cs +++ b/exercises/proverb/ProverbTest.cs @@ -8,38 +8,72 @@ public class ProverbTest [Fact] public void Zero_pieces() { - Assert.Empty(Proverb.Recite(Array.Empty())); + var strings = Array.Empty(); + var expected = Array.Empty(); + Assert.Equal(expected, Proverb.Recite(strings)); } [Fact(Skip = "Remove to run test")] public void One_piece() { - var expected = new[] { "And all for the want of a nail." }; - Assert.Equal(expected, Proverb.Recite(new[] { "nail" })); + var strings = new[] + { + "nail" + }; + var expected = new[] + { + "And all for the want of a nail." + }; + Assert.Equal(expected, Proverb.Recite(strings)); } [Fact(Skip = "Remove to run test")] public void Two_pieces() { - var expected = new[] { "For want of a nail the shoe was lost.", "And all for the want of a nail." }; - Assert.Equal(expected, Proverb.Recite(new[] { "nail", "shoe" })); + var strings = new[] + { + "nail", + "shoe" + }; + var expected = new[] + { + "For want of a nail the shoe was lost.", + "And all for the want of a nail." + }; + Assert.Equal(expected, Proverb.Recite(strings)); } [Fact(Skip = "Remove to run test")] public void Three_pieces() { + var strings = new[] + { + "nail", + "shoe", + "horse" + }; var expected = new[] { "For want of a nail the shoe was lost.", "For want of a shoe the horse was lost.", "And all for the want of a nail." }; - Assert.Equal(expected, Proverb.Recite(new[] { "nail", "shoe", "horse" })); + Assert.Equal(expected, Proverb.Recite(strings)); } [Fact(Skip = "Remove to run test")] public void Full_proverb() { + var strings = new[] + { + "nail", + "shoe", + "horse", + "rider", + "message", + "battle", + "kingdom" + }; var expected = new[] { "For want of a nail the shoe was lost.", @@ -50,12 +84,19 @@ public void Full_proverb() "For want of a battle the kingdom was lost.", "And all for the want of a nail." }; - Assert.Equal(expected, Proverb.Recite(new[] { "nail", "shoe", "horse", "rider", "message", "battle", "kingdom" })); + Assert.Equal(expected, Proverb.Recite(strings)); } [Fact(Skip = "Remove to run test")] public void Four_pieces_modernized() { + var strings = new[] + { + "pin", + "gun", + "soldier", + "battle" + }; var expected = new[] { "For want of a pin the gun was lost.", @@ -63,6 +104,6 @@ public void Four_pieces_modernized() "For want of a soldier the battle was lost.", "And all for the want of a pin." }; - Assert.Equal(expected, Proverb.Recite(new[] { "pin", "gun", "soldier", "battle" })); + Assert.Equal(expected, Proverb.Recite(strings)); } } \ No newline at end of file diff --git a/exercises/sieve/SieveTest.cs b/exercises/sieve/SieveTest.cs index 0289943cb8..f7e934c0f5 100644 --- a/exercises/sieve/SieveTest.cs +++ b/exercises/sieve/SieveTest.cs @@ -35,177 +35,7 @@ public void Limit_is_prime() [Fact(Skip = "Remove to run test")] public void Find_primes_up_to_1000() { - var expected = new[] - { - 2, - 3, - 5, - 7, - 11, - 13, - 17, - 19, - 23, - 29, - 31, - 37, - 41, - 43, - 47, - 53, - 59, - 61, - 67, - 71, - 73, - 79, - 83, - 89, - 97, - 101, - 103, - 107, - 109, - 113, - 127, - 131, - 137, - 139, - 149, - 151, - 157, - 163, - 167, - 173, - 179, - 181, - 191, - 193, - 197, - 199, - 211, - 223, - 227, - 229, - 233, - 239, - 241, - 251, - 257, - 263, - 269, - 271, - 277, - 281, - 283, - 293, - 307, - 311, - 313, - 317, - 331, - 337, - 347, - 349, - 353, - 359, - 367, - 373, - 379, - 383, - 389, - 397, - 401, - 409, - 419, - 421, - 431, - 433, - 439, - 443, - 449, - 457, - 461, - 463, - 467, - 479, - 487, - 491, - 499, - 503, - 509, - 521, - 523, - 541, - 547, - 557, - 563, - 569, - 571, - 577, - 587, - 593, - 599, - 601, - 607, - 613, - 617, - 619, - 631, - 641, - 643, - 647, - 653, - 659, - 661, - 673, - 677, - 683, - 691, - 701, - 709, - 719, - 727, - 733, - 739, - 743, - 751, - 757, - 761, - 769, - 773, - 787, - 797, - 809, - 811, - 821, - 823, - 827, - 829, - 839, - 853, - 857, - 859, - 863, - 877, - 881, - 883, - 887, - 907, - 911, - 919, - 929, - 937, - 941, - 947, - 953, - 967, - 971, - 977, - 983, - 991, - 997 - }; + var expected = new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 }; Assert.Equal(expected, Sieve.Primes(1000)); } } \ No newline at end of file diff --git a/exercises/variable-length-quantity/VariableLengthQuantityTest.cs b/exercises/variable-length-quantity/VariableLengthQuantityTest.cs index 3807559502..891314b416 100644 --- a/exercises/variable-length-quantity/VariableLengthQuantityTest.cs +++ b/exercises/variable-length-quantity/VariableLengthQuantityTest.cs @@ -145,24 +145,7 @@ public void Two_multi_byte_values() public void Many_multi_byte_values() { var integers = new[] { 0x2000u, 0x123456u, 0xFFFFFFFu, 0x0u, 0x3FFFu, 0x4000u }; - var expected = new[] - { - 0xC0u, - 0x0u, - 0xC8u, - 0xE8u, - 0x56u, - 0xFFu, - 0xFFu, - 0xFFu, - 0x7Fu, - 0x0u, - 0xFFu, - 0x7Fu, - 0x81u, - 0x80u, - 0x0u - }; + var expected = new[] { 0xC0u, 0x0u, 0xC8u, 0xE8u, 0x56u, 0xFFu, 0xFFu, 0xFFu, 0x7Fu, 0x0u, 0xFFu, 0x7Fu, 0x81u, 0x80u, 0x0u }; Assert.Equal(expected, VariableLengthQuantity.Encode(integers)); } @@ -223,24 +206,7 @@ public void Incomplete_sequence_causes_error_even_if_value_is_zero() [Fact(Skip = "Remove to run test")] public void Multiple_values() { - var integers = new[] - { - 0xC0u, - 0x0u, - 0xC8u, - 0xE8u, - 0x56u, - 0xFFu, - 0xFFu, - 0xFFu, - 0x7Fu, - 0x0u, - 0xFFu, - 0x7Fu, - 0x81u, - 0x80u, - 0x0u - }; + var integers = new[] { 0xC0u, 0x0u, 0xC8u, 0xE8u, 0x56u, 0xFFu, 0xFFu, 0xFFu, 0x7Fu, 0x0u, 0xFFu, 0x7Fu, 0x81u, 0x80u, 0x0u }; var expected = new[] { 0x2000u, 0x123456u, 0xFFFFFFFu, 0x0u, 0x3FFFu, 0x4000u }; Assert.Equal(expected, VariableLengthQuantity.Decode(integers)); } diff --git a/generators/Exercises/Generators/Proverb.cs b/generators/Exercises/Generators/Proverb.cs index a71e197189..c4b6fd337e 100644 --- a/generators/Exercises/Generators/Proverb.cs +++ b/generators/Exercises/Generators/Proverb.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators @@ -9,14 +10,15 @@ public class Proverb : GeneratorExercise { protected override void UpdateTestMethod(TestMethod testMethod) { + testMethod.UseVariablesForInput = true; testMethod.UseVariableForExpected = true; - - if (testMethod.Input["strings"] is JArray) - testMethod.Input["strings"] = Array.Empty(); - - if (testMethod.Expected is JArray) - testMethod.Expected = Array.Empty(); + + testMethod.Input["strings"] = RenderAsMultilineArray(testMethod.Input["strings"]); + testMethod.Expected = RenderAsMultilineArray(testMethod.Expected); } + + private UnescapedValue RenderAsMultilineArray(dynamic value) + => new UnescapedValue(Render.ArrayMultiLine(value as string[] ?? Array.Empty())); protected override void UpdateNamespaces(ISet namespaces) { diff --git a/generators/Exercises/Generators/Sieve.cs b/generators/Exercises/Generators/Sieve.cs index a15fcb46ea..3c743a8adc 100644 --- a/generators/Exercises/Generators/Sieve.cs +++ b/generators/Exercises/Generators/Sieve.cs @@ -1,5 +1,6 @@ using System; using Exercism.CSharp.Output; +using Exercism.CSharp.Output.Rendering; namespace Exercism.CSharp.Exercises.Generators { @@ -11,6 +12,11 @@ protected override void UpdateTestMethod(TestMethod testMethod) if (testMethod.Input["limit"] < 2) testMethod.ExceptionThrown = typeof(ArgumentOutOfRangeException); + else + testMethod.Expected = RenderAsSingleLineArray(testMethod.Expected); } + + private UnescapedValue RenderAsSingleLineArray(dynamic value) + => new UnescapedValue(Render.Array(value as int[] ?? Array.Empty())); } } \ No newline at end of file diff --git a/generators/Output/Rendering/Render.cs b/generators/Output/Rendering/Render.cs index 53d2cd0259..85249f2a51 100644 --- a/generators/Output/Rendering/Render.cs +++ b/generators/Output/Rendering/Render.cs @@ -6,9 +6,7 @@ namespace Exercism.CSharp.Output.Rendering { public partial class Render - { - private const int MaximumLengthForSingleLineValue = 108; - + { public string Object(object val) { if (val == null) @@ -53,9 +51,9 @@ public string ObjectMultiLine(object val) return DictionaryMultiLine((dynamic) val); if (IsArray(val)) - return RenderAsSingleLine((dynamic)val) - ? Array((dynamic) val) - : ArrayMultiLine((dynamic) val); + return RenderArrayAsMultiline((dynamic) val) + ? ArrayMultiLine((dynamic) val) + : Array((dynamic) val); return Object(val); } @@ -70,15 +68,12 @@ private static bool IsArray(object obj) private static bool IsDictionary(object obj) => obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>); - private static bool RenderAsSingleLine(T[,] _) => false; - - private bool RenderAsSingleLine(T[] elements) - => !elements.Any() || IsNotArrayOfArrays(elements) && RenderedAsSingleLineDoesNotExceedMaximumLength(elements); + private static bool RenderArrayAsMultiline(T[,] _) => true; - private static bool IsNotArrayOfArrays(T[] elements) - => !elements.GetType().GetElementType().IsArray; + private static bool RenderArrayAsMultiline(T[] elements) + => IsNestedArray(elements) && elements.Length > 0; - private bool RenderedAsSingleLineDoesNotExceedMaximumLength(T[] elements) - => Array(elements).Length <= MaximumLengthForSingleLineValue; + private static bool IsNestedArray(T[] elements) + => elements.GetType().GetElementType().IsArray; } } \ No newline at end of file From e46f68760c8fb4184c250cb07fcd5818d3c323dc Mon Sep 17 00:00:00 2001 From: Erik Schierboom Date: Sun, 15 Jul 2018 09:58:41 +0200 Subject: [PATCH 97/97] generators: Update docs --- docs/GENERATORS.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/GENERATORS.md b/docs/GENERATORS.md index 0bb336e42a..f37eb750f6 100644 --- a/docs/GENERATORS.md +++ b/docs/GENERATORS.md @@ -2,7 +2,7 @@ Test generators allow tracks to generate tests automatically without having to write them ourselves. Each test generator reads from the exercise's `canonical data`, which defines the name of the test, its inputs, and outputs. You can read more about exercism's approach to test suites [here](https://github.com/exercism/docs/blob/master/language-tracks/exercises/anatomy/test-suites.md). -Generating tests automatically removes any sort of user error when creating tests. We want the tests to be accurate with respect to its canonical data. Test generation also makes it much easier to keep tests up to date. As the canonical data changes, the tests will be automatically updated when the generator for that test is run. +Generating tests automatically removes any sort of user error when creating tests. Furthermore, we want the tests to be accurate with respect to its canonical data. Test generation also makes it much easier to keep tests up to date. As the canonical data changes, the tests will be automatically updated when the generator for that test is run. An example of a canonical data file can be found [here](https://github.com/exercism/problem-specifications/blob/master/exercises/bob/canonical-data.json) @@ -19,7 +19,7 @@ When looking through the canonical data and the generator code base, we use a lo ## Adding a simple generator -Adding a test generator file is straightforward. Simply add a new file to the `Exercises/Generators` folder with the name of the exercise (in PascalCase), and extend the `GeneratorExercise` abstract class. +Adding a test generator is straightforward. Simply add a new file to the `Exercises/Generators` folder with the name of the exercise (in PascalCase), and create a class that extends the `GeneratorExercise` class. An example of a simple generator would be the Bob exercise. The source is displayed below, but you can freely view it in the repository [here](https://github.com/exercism/csharp/blob/master/generators/Exercises/Bob.cs). @@ -32,11 +32,11 @@ namespace Exercism.CSharp.Exercises.Generators } ``` -This is a fully working generator, no other code needs to be written. However, it's simplicity stems from the fact that the test suite and the program itself are relatively trivial. +This is a fully working generator, no other code needs to be written! However, it's simplicity stems from the fact that the test suite and the program itself are relatively trivial. ## Adding a complex generator -When the default generator output is not sufficient, you can override the `GeneratorExercise` class' virtual methods to override the default behavior. +When the generator's default output is not sufficient, you can override the `GeneratorExercise` class' virtual methods to override the default behavior. ### Method 1: UpdateTestMethod(TestMethod testMethod) @@ -46,9 +46,9 @@ There are many things that can be customized, of which we'll list the more commo #### Customize test data -There are quite some generators that want to change the input or expected value. +It is not uncommon that a generator has to transform its input data or expected value to a different value/representation. -An example of this is the [bracket-push](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/BracketPush.cs) generator, which input value with the key `"value"` requires some additional escaping: +An example of this is the [bracket-push](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/BracketPush.cs) generator, which has a `"value"` input value, which is of type `string`. However, this `string` value contains a backslash, which needs to escaped in order for it to be rendered correctly: ```csharp protected override void UpdateTestMethod(TestMethod testMethod) @@ -122,7 +122,7 @@ protected override void UpdateTestMethod(TestMethod testMethod) Some test methods want to verify that an exception is being thrown. -An example of this is the [rna-transcription](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/RnaTranscription.cs) generator, which defines that some test methods should throws an `ArgumentException`: +An example of this is the [rna-transcription](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/RnaTranscription.cs) generator, which defines that some of its test methods should throw an `ArgumentException`: ```csharp protected override void UpdateTestMethod(TestMethod testMethod) @@ -136,7 +136,7 @@ Note that `ArgumentException` type's namespace will be automatically added to th #### Custom input/constructor parameters -In some case, you might want to override the parameters that are used as input parameters. +In some cases, you might want to override the parameters that are used as input parameters. An example of this is the [two-fer](https://github.com/exercism/csharp/blob/master/generators/Exercises/Generators/TwoFer.cs) generator, which does not use any input parameters when the `"name"` input parameter is set to `null`: @@ -202,7 +202,7 @@ protected override void UpdateNamespaces(ISet namespaces) } ``` -Note that as mentioned before, the namespace of any thrown exception types are automaticall added to the list of namespaces. +Note that as mentioned before, the namespace of any thrown exception types are automatically added to the list of namespaces. ### Method 3: UpdateTestClass(TestClass testClass)