-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSyncALTestCodeunitCmdlet.cs
More file actions
208 lines (173 loc) · 8.01 KB
/
Copy pathSyncALTestCodeunitCmdlet.cs
File metadata and controls
208 lines (173 loc) · 8.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
namespace ATDD.TestScriptor
{
[Cmdlet(VerbsData.Sync, "ALTestCodeunit")]
public class SyncALTestCodeunitCmdlet : PSCmdlet
{
private List<TestScenario> scenarioCache = new List<TestScenario>();
[Parameter(Mandatory = true)]
public string CodeunitPath { get; set; }
private SwitchParameter InitializeFunction { get; set; }
[Parameter(ValueFromPipeline = true)]
[ValidateNotNull()]
public TestFeature[] Feature { get; set; } = new TestFeature[] { };
[Parameter()]
[ValidateNotNullOrEmpty()]
public string GivenFunctionName { get; set; } = "{0}";
[Parameter()]
[ValidateNotNullOrEmpty()]
public string WhenFunctionName { get; set; } = "{0}";
[Parameter()]
[ValidateNotNullOrEmpty()]
public string ThenFunctionName { get; set; } = "{0}";
[Parameter()]
[ValidateNotNull()]
public string BannerFormat { get; set; } = "// Generated on {0} at {1} by {2}";
protected override void ProcessRecord() => scenarioCache.AddRange(Feature.SelectMany(f => f.Scenarios));
protected override void EndProcessing()
{
var uniqueFeatureNames =
scenarioCache
.Select(s => s.Feature.ToString())
.Distinct();
var elementFunctionNames =
scenarioCache
.SelectMany(s => s.Elements)
.Select(e => new { Element = e, FunctionName = GetElementFunctionName(e) })
.ToDictionary(o => o.Element, o => o.FunctionName);
var uniqueFunctionNames =
elementFunctionNames
.Values
.Distinct()
.OrderBy(f => f);
CodeunitPath = File.Exists(CodeunitPath) ? CodeunitPath : Path.Combine(this.SessionState.Path.CurrentFileSystemLocation.Path, CodeunitPath);
if (!File.Exists(CodeunitPath))
{
return;
}
var lines = File.ReadAllLines(CodeunitPath).ToList();
var uniqueProcedures = scenarioCache.Select(s => s.ToString()).Union(elementFunctionNames.Select(s => s.ToString()));
var existingFunctions = uniqueFunctionNames.Where(w => lines.Any(a => a.Contains(w.ToString())));
var newFunctions = uniqueProcedures.Except(existingFunctions);
var existingScenarios = scenarioCache.Where(s => lines.Any(a => a.Contains(s.ToString())));
var newScenarios = scenarioCache.Except(existingScenarios);
var newElementFunctionNames =
newScenarios
.SelectMany(s => s.Elements)
.Select(e => new { Element = e, FunctionName = GetElementFunctionName(e) })
.ToDictionary(o => o.Element, o => o.FunctionName);
var newUniqueFunctionNames =
newElementFunctionNames
.Values
.Distinct()
.OrderBy(f => f);
newScenarios.ForEach(e => WriteObject($"New Scenario: {e.ToString()}"));
newUniqueFunctionNames.ForEach(e => WriteObject($"New helper: {e.ToString()}"));
if (newScenarios.Count() == 0)
{
return;
}
WarnIfPlaceHolderMissing(GivenFunctionName);
WarnIfPlaceHolderMissing(WhenFunctionName);
WarnIfPlaceHolderMissing(ThenFunctionName);
// scenarios
using (var stringWriter = new StringWriter())
{
using (var writer = new IndentedTextWriter(stringWriter))
{
writer.Indent++;
writer.WriteLine();
newScenarios.ForEach(s => WriteALTestFunction(s, newElementFunctionNames, writer));
writer.Indent--;
}
var ti = lines.FindLastIndex(f => f.Contains("// [SCENARIO"));
var li = lines.FindIndex(ti, f => f.Contains("var"));
lines.Insert(li, stringWriter.ToString());
}
// helpers
using (var stringWriter = new StringWriter())
{
using (var writer = new IndentedTextWriter(stringWriter))
{
writer.Indent++;
writer.WriteLine();
newUniqueFunctionNames.ForEach(f => WriteDummyFunction(f, writer));
writer.Indent--;
}
var ti = lines.LastIndexOf("}");
lines.Insert(ti, stringWriter.ToString());
}
//WriteObject(lines.Join("\r\n"));
File.WriteAllLines(CodeunitPath, lines);
}
protected void WriteALTestFunction(TestScenario scenario, Dictionary<TestScenarioElement, string> elementFunctionNames, IndentedTextWriter writer)
{
writer.WriteLine("[Test]");
writer.WriteLine($"procedure {SanitizeName(scenario.Name)}()");
writer.WriteLine($"// {scenario.Feature.ToString()}");
writer.WriteLine("begin");
writer.Indent++;
writer.WriteLine($"// {scenario.ToString()}");
writer.WriteLineIf(InitializeFunction, "Initialize();");
writer.WriteLine();
writer.WriteLines(scenario.Elements.OfType<Given>().SelectMany(g => ElementLines(g, elementFunctionNames)));
writer.WriteLines(scenario.Elements.OfType<When>().SelectMany(w => ElementLines(w, elementFunctionNames)));
writer.WriteLines(scenario.Elements.OfType<Then>().SelectMany(t => ElementLines(t, elementFunctionNames)));
writer.WriteLines(scenario.Elements.OfType<Cleanup>().SelectMany(c => ElementLines(c, elementFunctionNames)));
writer.Indent--;
writer.WriteLine("end;");
writer.WriteLine();
}
protected IEnumerable<string> ElementLines(TestScenarioElement element, Dictionary<TestScenarioElement, string> elementFunctionNames)
{
yield return $"// {element.ToString()}";
yield return $"{elementFunctionNames[element]}();";
yield return "";
}
protected void WriteDummyFunction(string name, IndentedTextWriter writer)
{
writer.WriteLine($"local procedure {name}()");
writer.WriteLine("begin");
writer.WriteLine("end;");
writer.WriteLine();
}
protected string GetElementFunctionName(TestScenarioElement element)
{
switch (element)
{
case Given given: return FormatElement(element, GivenFunctionName);
case When @when: return FormatElement(element, WhenFunctionName);
case Then then: return FormatElement(element, ThenFunctionName);
default: return SanitizeName(element.Value);
}
}
protected string FormatElement(TestScenarioElement element, string format)
{
try
{
return SanitizeName(string.Format(format, element.Value));
}
catch (FormatException e)
{
throw new FormatException($"Function name format '{format}' should not contain placeholders other than '{{0}}'", e);
}
}
protected void WarnIfPlaceHolderMissing(string format)
{
if (!format.Contains("{0}"))
WriteWarning($"Function name format '{format}' does not contain placeholder '{{0}}'");
}
protected static string SanitizeName(string name) =>
Regex
.Split(name, @"\W", RegexOptions.CultureInvariant)
.Where(s => !string.IsNullOrEmpty(s))
.Select(s => Regex.Replace(s, "^.", m => m.Value.ToUpperInvariant()))
.Join("");
}
}