This repository has been archived by the owner on May 17, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNUnitAppAction.cs
213 lines (180 loc) · 8.17 KB
/
NUnitAppAction.cs
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
209
210
211
212
213
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Xml.Linq;
using Inedo.Agents;
using Inedo.BuildMaster;
using Inedo.BuildMaster.Extensibility.Actions;
using Inedo.BuildMaster.Extensibility.Actions.Testing;
using Inedo.BuildMaster.Web;
using Inedo.Documentation;
using Inedo.Serialization;
using Inedo.Web;
namespace Inedo.BuildMasterExtensions.NUnit
{
[DisplayName("Execute NUnit Tests")]
[Description("Runs NUnit unit tests on a specified project, assembly, or NUnit file.")]
[Tag(Tags.UnitTests)]
[CustomEditor(typeof(NUnitActionEditor))]
[RequiresInterface(typeof(IFileOperationsExecuter))]
[ConvertibleToOperation(typeof(NUnitActionImporter))]
public sealed class NUnitAppAction : UnitTestActionBase
{
/// <summary>
/// Gets or sets the test runner exe path
/// </summary>
[Persistent]
public string ExePath { get; set; }
/// <summary>
/// Gets or sets the file nunit will test against (could be dll, proj, or config file based on test runner)
/// </summary>
[Persistent]
public string TestFile { get; set; }
/// <summary>
/// Gets or sets the additional arguments.
/// </summary>
[Persistent]
public string AdditionalArguments { get; set; }
/// <summary>
/// Gets or sets the path of the output XML generated by NUnit.
/// </summary>
[Persistent]
public string CustomXmlOutputPath { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to treat inconclusive tests as failures.
/// </summary>
[Persistent]
public bool TreatInconclusiveAsFailure { get; set; } = true;
public override ExtendedRichDescription GetActionDescription()
{
var longActionDescription = new RichDescription();
if (!string.IsNullOrWhiteSpace(this.AdditionalArguments))
{
longActionDescription.AppendContent(
"with additional arguments: ",
new Hilite(this.AdditionalArguments)
);
}
return new ExtendedRichDescription(
new RichDescription(
"Run NUnit on ",
new DirectoryHilite(this.OverriddenSourceDirectory, this.TestFile)
),
longActionDescription
);
}
/// <summary>
/// Runs a unit test against the target specified in the action.
/// After the test is run, use the <see cref="M:RecordResult" /> method
/// to save the test results to the database.
/// </summary>
protected override void RunTests()
{
var fileOps = this.Context.Agent.GetService<IFileOperationsExecuter>();
var nunitExePath = this.GetNUnitExePath(fileOps);
var tmpFileName = this.GetXmlOutputPath(fileOps);
var startTime = DateTime.UtcNow;
this.ExecuteCommandLine(
nunitExePath,
string.Format("\"{0}\" /xml:\"{1}\" {2}", this.TestFile, tmpFileName, this.AdditionalArguments),
this.Context.SourceDirectory
);
XDocument xdoc;
using (var stream = fileOps.OpenFile(tmpFileName, FileMode.Open, FileAccess.Read))
{
xdoc = XDocument.Load(stream);
}
var testResultsElement = xdoc.Element("test-results");
startTime = this.TryParseStartTime((string)testResultsElement.Attribute("date"), (string)testResultsElement.Attribute("time")) ?? startTime;
foreach (var testCaseElement in xdoc.Descendants("test-case"))
{
var testName = (string)testCaseElement.Attribute("name");
// skip tests that weren't actually run
if (string.Equals((string)testCaseElement.Attribute("executed"), "False", StringComparison.OrdinalIgnoreCase))
{
this.LogInformation("NUnit test: {0} (skipped)", testName);
continue;
}
bool nodeResult = string.Equals((string)testCaseElement.Attribute("success"), "True", StringComparison.OrdinalIgnoreCase)
|| (!this.TreatInconclusiveAsFailure && string.Equals((string)testCaseElement.Attribute("result"), "Inconclusive", StringComparison.OrdinalIgnoreCase));
var testDuration = this.TryParseTestTime((string)testCaseElement.Attribute("time"));
this.LogInformation(
"NUnit Test: {0}, Result: {1}, Test Length: {2}",
testName,
nodeResult,
testDuration
);
this.RecordResult(
testName,
nodeResult,
testCaseElement.ToString(),
startTime,
startTime + testDuration
);
startTime += testDuration;
}
}
private string GetNUnitExePath(IFileOperationsExecuter fileOps)
{
if (!string.IsNullOrWhiteSpace(this.ExePath))
return fileOps.CombinePath(this.Context.SourceDirectory, this.ExePath);
var configurer = (NUnitConfigurer)this.GetExtensionConfigurer();
if (string.IsNullOrWhiteSpace(configurer.NUnitConsoleExePath))
throw new InvalidOperationException("The path to NUnit was not specified in either the action or the selected NUnit extension's configuration.");
return fileOps.CombinePath(this.Context.SourceDirectory, configurer.NUnitConsoleExePath);
}
private string GetXmlOutputPath(IFileOperationsExecuter fileOps)
{
if (string.IsNullOrWhiteSpace(this.CustomXmlOutputPath))
return fileOps.CombinePath(this.Context.TempDirectory, Guid.NewGuid().ToString() + ".xml");
return fileOps.CombinePath(this.Context.SourceDirectory, this.CustomXmlOutputPath);
}
private DateTime? TryParseStartTime(string date, string time)
{
try
{
if (string.IsNullOrWhiteSpace(date))
{
DateTime result;
if (DateTime.TryParse(time, out result))
return result.ToUniversalTime();
}
if (!string.IsNullOrWhiteSpace(date) && !string.IsNullOrWhiteSpace(time))
{
var dateParts = date.Split('-');
var timeParts = time.Split(':');
return new DateTime(
year: int.Parse(dateParts[0]),
month: int.Parse(dateParts[1]),
day: int.Parse(dateParts[2]),
hour: int.Parse(timeParts[0]),
minute: int.Parse(timeParts[1]),
second: int.Parse(timeParts[2])
).ToUniversalTime();
}
}
catch
{
}
this.LogWarning("Unable to parse start time; using current time instead.");
return null;
}
private TimeSpan TryParseTestTime(string time)
{
if (string.IsNullOrWhiteSpace(time))
return TimeSpan.Zero;
var mungedTime = time.Replace(',', '.');
double doubleTime;
bool parsed = double.TryParse(
mungedTime,
NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent,
CultureInfo.InvariantCulture,
out doubleTime
);
if (!parsed)
this.LogWarning("Could not parse {0} as a time in seconds.", time);
return TimeSpan.FromSeconds(doubleTime);
}
}
}