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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
|
//
// NUnitService.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using MonoDevelop.Core;
using MonoDevelop.Core.Execution;
using Mono.Addins;
using MonoDevelop.Projects;
using MonoDevelop.Ide.Gui;
using MonoDevelop.Ide;
using System.Threading.Tasks;
using System.Linq;
using MonoDevelop.Ide.TypeSystem;
using System.IO;
using MonoDevelop.Ide.Gui.Components;
namespace MonoDevelop.UnitTesting
{
public static class UnitTestService
{
static ArrayList providers = new ArrayList ();
static UnitTest[] rootTests;
static UnitTestService ()
{
IdeApp.Workspace.WorkspaceItemOpened += OnWorkspaceChanged;
IdeApp.Workspace.WorkspaceItemClosed += OnWorkspaceChanged;
IdeApp.Workspace.ActiveConfigurationChanged += OnWorkspaceChanged;
IdeApp.Workspace.ItemAddedToSolution += OnItemsChangedInSolution;;
IdeApp.Workspace.ItemRemovedFromSolution += OnItemsChangedInSolution;
IdeApp.Workspace.ReferenceAddedToProject += OnReferenceChangedInProject;;
IdeApp.Workspace.ReferenceRemovedFromProject += OnReferenceChangedInProject;
Mono.Addins.AddinManager.AddExtensionNodeHandler ("/MonoDevelop/UnitTesting/TestProviders", OnExtensionChange);
RebuildTests ();
}
static void OnExtensionChange (object s, ExtensionNodeEventArgs args)
{
if (args.Change == ExtensionChange.Add) {
ProjectService ps = MonoDevelop.Projects.Services.ProjectService;
ITestProvider provider = args.ExtensionObject as ITestProvider;
providers.Add (provider);
}
else {
ITestProvider provider = args.ExtensionObject as ITestProvider;
providers.Remove (provider);
provider.Dispose ();
}
}
public static UnitTest CurrentSelectedTest {
get {
var pad = IdeApp.Workbench.GetPad<TestPad> ();
pad.BringToFront ();
TestPad testPad = (TestPad)pad.Content;
ITreeNavigator nav = testPad.TreeView.GetSelectedNode ();
if (nav != null)
return nav.DataItem as UnitTest;
return null;
}
set {
var pad = IdeApp.Workbench.GetPad<TestPad> ();
pad.BringToFront ();
var content = (TestPad)pad.Content;
content.SelectTest (value);
}
}
public static AsyncOperation RunTest (UnitTest test, MonoDevelop.Projects.ExecutionContext context)
{
var result = RunTest (test, context, IdeApp.Preferences.BuildBeforeRunningTests);
result.Task.ContinueWith (t => OnTestSessionCompleted (), TaskScheduler.FromCurrentSynchronizationContext ());
return result;
}
public static AsyncOperation RunTest (UnitTest test, MonoDevelop.Projects.ExecutionContext context, bool buildOwnerObject)
{
var cs = new CancellationTokenSource ();
return new AsyncOperation (RunTest (test, context, buildOwnerObject, true, cs), cs);
}
internal static async Task RunTest (UnitTest test, MonoDevelop.Projects.ExecutionContext context, bool buildOwnerObject, bool checkCurrentRunOperation, CancellationTokenSource cs)
{
string testName = test.FullName;
if (buildOwnerObject) {
IBuildTarget bt = test.OwnerObject as IBuildTarget;
if (bt != null) {
if (!IdeApp.ProjectOperations.CurrentRunOperation.IsCompleted) {
MonoDevelop.Ide.Commands.StopHandler.StopBuildOperations ();
await IdeApp.ProjectOperations.CurrentRunOperation.Task;
}
var res = await IdeApp.ProjectOperations.Build (bt, cs.Token).Task;
if (res.HasErrors)
return;
await RefreshTests (cs.Token);
test = SearchTest (testName);
if (test != null)
await RunTest (test, context, false, checkCurrentRunOperation, cs);
return;
}
}
if (checkCurrentRunOperation && !IdeApp.ProjectOperations.ConfirmExecutionOperation ())
return;
Pad resultsPad = IdeApp.Workbench.GetPad <TestResultsPad>();
if (resultsPad == null) {
resultsPad = IdeApp.Workbench.ShowPad (new TestResultsPad (), "MonoDevelop.UnitTesting.TestResultsPad", GettextCatalog.GetString ("Test results"), "Bottom", "md-solution");
}
// Make the pad sticky while the tests are runnig, so the results pad is always visible (even if minimized)
// That's required since when running in debug mode, the layout is automatically switched to debug.
resultsPad.Sticky = true;
resultsPad.BringToFront ();
TestSession session = new TestSession (test, context, (TestResultsPad) resultsPad.Content, cs);
OnTestSessionStarting (new TestSessionEventArgs { Session = session, Test = test });
if (checkCurrentRunOperation)
IdeApp.ProjectOperations.CurrentRunOperation = session;
try {
await session.Start ();
} finally {
resultsPad.Sticky = false;
}
}
/// <summary>
/// For each node already in the test tree, it checks if there is any change. If there is, it reloads the test.
/// </summary>
public static Task RefreshTests (CancellationToken ct)
{
return Task.WhenAll (RootTests.Select (t => t.Refresh (ct)));
}
/// <summary>
/// Reloads the test tree, creating new test branches if necessary
/// </summary>
public static void ReloadTests ()
{
foreach (var t in RootTests.OfType<UnitTestGroup> ())
t.UpdateTests ();
}
public static UnitTest SearchTest (string fullName)
{
foreach (UnitTest t in RootTests) {
UnitTest r = SearchTest (t, fullName);
if (r != null)
return r;
}
return null;
}
public static UnitTest SearchTestById (string id)
{
foreach (UnitTest t in RootTests) {
UnitTest r = SearchTestById (t, id);
if (r != null)
return r;
}
return null;
}
static UnitTest SearchTest (UnitTest test, string fullName)
{
if (test == null)
return null;
if (test.FullName == fullName)
return test;
UnitTestGroup group = test as UnitTestGroup;
if (group != null) {
foreach (UnitTest t in group.Tests) {
UnitTest result = SearchTest (t, fullName);
if (result != null)
return result;
}
}
return null;
}
static UnitTest SearchTestById (UnitTest test, string id)
{
if (test == null)
return null;
if (test.TestId == id)
return test;
UnitTestGroup group = test as UnitTestGroup;
if (group != null) {
foreach (UnitTest t in group.Tests) {
UnitTest result = SearchTestById (t, id);
if (result != null)
return result;
}
}
return null;
}
public static UnitTest FindRootTest (WorkspaceObject item)
{
return FindRootTest (RootTests, item);
}
public static UnitTest FindRootTest (IEnumerable<UnitTest> tests, WorkspaceObject item)
{
foreach (UnitTest t in tests) {
if (t.OwnerObject == item)
return t;
UnitTestGroup tg = t as UnitTestGroup;
if (tg != null) {
UnitTest ct = FindRootTest (tg.Tests, item);
if (ct != null)
return ct;
}
}
return null;
}
static void OnWorkspaceChanged (object sender, EventArgs e)
{
RebuildTests ();
}
static void OnReferenceChangedInProject (object sender, ProjectReferenceEventArgs e)
{
if (!IsSolutionGroupPresent (e.Project.ParentSolution, rootTests))
RebuildTests ();
}
static void OnItemsChangedInSolution (object sender, SolutionItemChangeEventArgs e)
{
if (!IsSolutionGroupPresent (e.Solution, rootTests))
RebuildTests ();
}
static bool IsSolutionGroupPresent (Solution sol, IEnumerable<UnitTest> tests)
{
foreach (var t in tests) {
var tg = t as SolutionFolderTestGroup;
if (tg != null && ((SolutionFolder)tg.OwnerObject).ParentSolution == sol)
return true;
var g = t as UnitTestGroup;
if (g != null && g.HasTests) {
if (IsSolutionGroupPresent (sol, g.Tests))
return true;
}
}
return false;
}
static void RebuildTests ()
{
if (rootTests != null) {
foreach (IDisposable t in rootTests)
t.Dispose ();
}
List<UnitTest> list = new List<UnitTest> ();
foreach (WorkspaceItem it in IdeApp.Workspace.Items) {
UnitTest t = BuildTest (it);
if (t != null)
list.Add (t);
}
rootTests = list.ToArray ();
NotifyTestSuiteChanged ();
}
public static UnitTest BuildTest (WorkspaceObject entry)
{
foreach (ITestProvider p in providers) {
try {
UnitTest t = p.CreateUnitTest (entry);
if (t != null)
return t;
} catch {
}
}
return null;
}
public static string GetTestResultsDirectory (string baseDirectory)
{
var newCache = TypeSystemService.GetCacheDirectory (baseDirectory, false);
if (newCache == null) {
newCache = TypeSystemService.GetCacheDirectory (baseDirectory, true);
var oldDirectory = Path.Combine (baseDirectory, "test-results");
var newDirectory = Path.Combine (newCache, "test-results");
try {
Directory.CreateDirectory (newDirectory);
if (Directory.Exists (oldDirectory)) {
foreach (string file in Directory.GetFiles(oldDirectory, "*.*"))
File.Copy (file, file.Replace (oldDirectory, newDirectory));
}
} catch (Exception e) {
LoggingService.LogError ("Error while copying old test-results", e);
}
return newDirectory;
}
return Path.Combine (newCache, "test-results");
}
public static UnitTest[] RootTests {
get { return rootTests; }
}
static void NotifyTestSuiteChanged ()
{
Runtime.RunInMainThread (() => {
if (TestSuiteChanged != null)
TestSuiteChanged (null, EventArgs.Empty);
});
}
public static void ResetResult (UnitTest test)
{
if (test == null)
return;
test.ResetLastResult ();
UnitTestGroup group = test as UnitTestGroup;
if (group == null)
return;
foreach (UnitTest t in new List<UnitTest> (group.Tests))
ResetResult (t);
}
public static event EventHandler TestSuiteChanged;
static void OnTestSessionCompleted ()
{
var handler = TestSessionCompleted;
if (handler != null)
handler (null, EventArgs.Empty);
}
public static event EventHandler TestSessionCompleted;
static void OnTestSessionStarting (TestSessionEventArgs args)
{
if (TestSessionStarting != null)
TestSessionStarting (null, args);
}
/// <summary>
/// Occurs just before a test session is started
/// </summary>
public static event EventHandler<TestSessionEventArgs> TestSessionStarting;
}
class TestSession: AsyncOperation
{
UnitTest test;
TestMonitor monitor;
MonoDevelop.Projects.ExecutionContext context;
TestResultsPad resultsPad;
public TestSession (UnitTest test, MonoDevelop.Projects.ExecutionContext context, TestResultsPad resultsPad, CancellationTokenSource cs)
{
this.test = test;
this.context = new Projects.ExecutionContext (context.ExecutionHandler, new CustomConsoleFactory (context.ConsoleFactory, cs), context.ExecutionTarget);
CancellationTokenSource = cs;
this.monitor = new TestMonitor (resultsPad, CancellationTokenSource);
this.resultsPad = resultsPad;
resultsPad.InitializeTestRun (test, cs);
Task = new Task ((Action)RunTests);
}
public Task Start ()
{
Task.Start ();
return Task;
}
void RunTests ()
{
try {
UnitTestService.ResetResult (test);
TestContext ctx = new TestContext (monitor, resultsPad, context, DateTime.Now);
test.Run (ctx);
test.SaveResults ();
} catch (Exception ex) {
LoggingService.LogError (ex.ToString ());
monitor.ReportRuntimeError (null, ex);
} finally {
monitor.FinishTestRun ();
}
}
}
public class TestSessionEventArgs: EventArgs
{
public AsyncOperation Session { get; set; }
public UnitTest Test { get; set; }
}
class CustomConsoleFactory : OperationConsoleFactory
{
OperationConsoleFactory factory;
CancellationTokenSource cancelSource;
public CustomConsoleFactory (OperationConsoleFactory factory, CancellationTokenSource cs)
{
this.factory = factory;
cancelSource = cs;
}
protected override OperationConsole OnCreateConsole (CreateConsoleOptions options)
{
return factory.CreateConsole (options.WithBringToFront (false)).WithCancelCallback (cancelSource.Cancel);
}
}
}
|