Welcome to mirror list, hosted at ThFree Co, Russian Federation.

AbstractResultsStore.cs « Services « MonoDevelop.UnitTesting « addins « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 62b40b80b608e1ec47d153c8073cfe03739926f5 (plain)
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
//
// AbstractResultsStore.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.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using MonoDevelop.Core;

namespace MonoDevelop.UnitTesting
{
	public abstract class AbstractResultsStore: IResultsStore
	{
		Hashtable fileCache = new Hashtable ();
		string basePath;
		string storeId;
		Hashtable cachedRootList = new Hashtable ();

		IResultsStoreSerializer serializer;

		public AbstractResultsStore (IResultsStoreSerializer serializer, string directory, string storeId)
		{
			this.serializer = serializer;
			this.basePath = directory;
			this.storeId = storeId;
		}
		
		public void RegisterResult (string configuration, UnitTest test, UnitTestResult result)
		{
			//This method can be called from multiple threads when remote process(test runner) is responding
			//This lock is protecting collections fileCache, record.Tests and record.Results
			lock (fileCache) {
				string aname = test.StoreRelativeName;

				TestRecord root = GetRootRecord (configuration, result.TestDate);
				if (root == null) {
					root = new TestRecord ();
					fileCache [GetRootFileName (configuration, result.TestDate)] = root;
				}
				root.Modified = true;
				TestRecord record = root;

				if (aname.Length > 0) {
					string [] path = test.StoreRelativeName.Split ('.');
					foreach (string p in path) {
						TestRecord ctr = record.Tests != null ? record.Tests [p] : null;
						if (ctr == null) {
							ctr = new TestRecord ();
							ctr.Name = p;
							if (record.Tests == null)
								record.Tests = new TestRecordCollection ();
							record.Tests.Add (ctr);
						}
						record = ctr;
					}
				}

				if (record.Results == null)
					record.Results = new UnitTestResultCollection ();
				record.Results.Add (result);
			}
		}

		public UnitTestResult GetNextResult (string configuration, UnitTest test, DateTime date)
		{
			DateTime currentDate = date;
			lock (fileCache) {
				TestRecord root = GetRootRecord (configuration, currentDate);
				if (root == null)
					root = GetNextRootRecord (configuration, ref currentDate);

				while (root != null) {
					TestRecord tr = FindRecord (root, test.StoreRelativeName);
					if (tr != null && tr.Results != null) {
						foreach (UnitTestResult res in tr.Results) {
							if (res.TestDate > date)
								return res;
						}
					}
					root = GetNextRootRecord (configuration, ref currentDate);
				}
			}
			return null;
		}
		
		public UnitTestResult GetPreviousResult (string configuration, UnitTest test, DateTime date)
		{
			DateTime currentDate = date;
			lock (fileCache) {
				TestRecord root = GetRootRecord (configuration, currentDate);
				if (root == null)
					root = GetPreviousRootRecord (configuration, ref currentDate);

				while (root != null) {
					TestRecord tr = FindRecord (root, test.StoreRelativeName);
					if (tr != null && tr.Results != null) {
						for (int n = tr.Results.Count - 1; n >= 0; n--) {
							UnitTestResult res = (UnitTestResult)tr.Results [n];
							if (res.TestDate < date)
								return res;
						}
					}
					root = GetPreviousRootRecord (configuration, ref currentDate);
				}
			}
			return null;
		}
		
		public UnitTestResult GetLastResult (string configuration, UnitTest test, DateTime date)
		{
			return GetPreviousResult (configuration, test, date.AddTicks (1));
		}
		
		public UnitTestResult[] GetResults (string configuration, UnitTest test, DateTime startDate, DateTime endDate)
		{
			ArrayList list = new ArrayList ();
			DateTime firstDay = new DateTime (startDate.Year, startDate.Month, startDate.Day);
			
			DateTime[] dates = GetStoreDates (configuration);

			lock (fileCache) {
				foreach (DateTime date in dates) {
					if (date < firstDay)
						continue;
					if (date > endDate)
						break;

					TestRecord root = GetRootRecord (configuration, date);
					if (root == null) continue;

					TestRecord tr = FindRecord (root, test.StoreRelativeName);
					if (tr != null && tr.Results != null) {
						foreach (UnitTestResult res in tr.Results) {
							if (res.TestDate >= startDate && res.TestDate <= endDate)
								list.Add (res);
						}
					}
				}
			}
			
			return (UnitTestResult[]) list.ToArray (typeof(UnitTestResult));
		}
		
		public UnitTestResult[] GetResultsToDate (string configuration, UnitTest test, DateTime endDate, int count)
		{
			ArrayList list = new ArrayList ();
			DateTime[] dates = GetStoreDates (configuration);

			lock (fileCache) {
				for (int n = dates.Length - 1; n >= 0 && list.Count < count; n--) {
					if (dates [n] > endDate)
						continue;

					TestRecord root = GetRootRecord (configuration, dates [n]);
					if (root == null) continue;

					TestRecord tr = FindRecord (root, test.StoreRelativeName);
					if (tr != null && tr.Results != null) {
						for (int m = tr.Results.Count - 1; m >= 0 && list.Count < count; m--) {
							UnitTestResult res = (UnitTestResult)tr.Results [m];
							if (res.TestDate <= endDate)
								list.Add (res);
						}
					}
				}
			}
			
			UnitTestResult[] array = (UnitTestResult[]) list.ToArray (typeof(UnitTestResult));
			Array.Reverse (array);
			return array;
		}
		
		public void Save ()
		{
			if (!Directory.Exists (basePath))
				Directory.CreateDirectory (basePath);

			lock (fileCache) {
				foreach (DictionaryEntry entry in fileCache) {
					TestRecord record = (TestRecord)entry.Value;
					if (!record.Modified)
						continue;

					string filePath = Path.Combine (basePath, (string)entry.Key);
					try {
						serializer.Serialize (filePath, record);
						record.Modified = false;
					} catch (Exception ex) {
						LoggingService.LogError (ex.ToString ());
					}
				}
			}
			lock (cachedRootList)
				cachedRootList.Clear ();
		}
		
		TestRecord FindRecord (TestRecord root, string aname)
		{
			if (aname.Length == 0)
				return root;
			else {
				string[] path = aname.Split ('.');
				TestRecord tr = root;
				foreach (string p in path) {
					if (tr.Tests == null)
						return null;
					tr = tr.Tests [p];
					if (tr == null)
						return null;
				}
				return tr;
			}
		}

		TestRecord GetRootRecord (string configuration, DateTime date)
		{
			string file = GetRootFileName (configuration, date);
			TestRecord res = (TestRecord) fileCache [file];
			if (res != null)
				return res;
			string filePath;
			try {
				filePath = Path.Combine (basePath, file);
			} catch (Exception) {
				return null;
			}
			
			try {
				res = (TestRecord) serializer.Deserialize (filePath);
			} catch (Exception ex) {
				LoggingService.LogError (ex.ToString ());
				return null;
			}
			
			if (res != null) {
				fileCache [file] = res;
			}
			return res;
		}
		
		TestRecord GetNextRootRecord (string configuration, ref DateTime date)
		{
			DateTime[] dates = GetStoreDates (configuration);
			foreach (DateTime d in dates) {
				if (d > date) {
					date = d;
					return GetRootRecord (configuration, d);
				}
			}
			return null;
		}
		
		TestRecord GetPreviousRootRecord (string configuration, ref DateTime date)
		{
			date = new DateTime (date.Year, date.Month, date.Day);
			DateTime[] dates = GetStoreDates (configuration);
			for (int n = dates.Length - 1; n >= 0; n--) {
				if (dates [n] < date) {
					date = dates [n];
					return GetRootRecord (configuration, dates [n]);
				}
			}
			return null;
		}

		// Filter out all invalid path characters in the file name
		// Bug 3023 - Running NUnit tests throws ArgumentException: Illegal Characters in path
		static string EscapeFilename (string str)
		{
			var pc = FilePath.GetInvalidPathChars ();
			char[] specialCharacters = new char[pc.Length + 1];
			pc.CopyTo (specialCharacters, 0);
			specialCharacters [specialCharacters.Length - 1] = '%';

			int i = str.IndexOfAny (specialCharacters);
			while (i != -1) {
				str = str.Substring (0, i) + '%' + ((int) str [i]).ToString ("X") + str.Substring (i + 1);
				i = str.IndexOfAny (specialCharacters, i + 3);
			}
			return str;
		}
		
		string GetRootFileName (string configuration, DateTime date)
		{
			var filteredConfiguration = EscapeFilename (configuration);
			return storeId + "-" + filteredConfiguration + "-" + date.ToString ("yyyy-MM-dd", CultureInfo.InvariantCulture) + ".xml";
		}
		
		DateTime ParseFileNameDate (string configuration, string fileName)
		{
			fileName = Path.GetFileNameWithoutExtension (fileName);
			fileName = fileName.Substring (storeId.Length + configuration.Length + 2);
			return DateTime.ParseExact (fileName, "yyyy-MM-dd", CultureInfo.InvariantCulture);
		}
		
		DateTime[] GetStoreDates (string configuration)
		{
			if (!Directory.Exists (basePath))
				return Array.Empty<DateTime> ();

			lock (cachedRootList) {
				DateTime [] res = (DateTime [])cachedRootList [configuration];
				if (res != null)
					return res;

				var dates = new List<(string File, DateTime Date)> ();
				var escapedConfiguration = EscapeFilename (configuration);
				foreach (string file in Directory.GetFiles (basePath, storeId + "-" + escapedConfiguration + "-*")) {
					try {
						DateTime t = ParseFileNameDate (escapedConfiguration, Path.GetFileName (file));
						dates.Add ((file, t));
					} catch { }
				}

				// prune items from the list
				// items are sorted due to how the file name is generated
				const int maxStoreItems = 30;
				int overflow = dates.Count - maxStoreItems;
				int toRemove = Math.Max (0, overflow);
				if (toRemove != 0) {
					for (int i = 0; i < toRemove; ++i)
						File.Delete (dates [i].File);
					dates.RemoveRange (0, toRemove);
				}

				res = dates.Select (x => x.Date).ToArray ();
				cachedRootList [configuration] = res;
				return res;
			}
		}
	}
	
	/// <summary>
	/// Encapsulates serialization/deserialization logic
	/// </summary>
	public interface IResultsStoreSerializer
	{
		/// <summary>
		/// Serialize the record into the specified path.
		/// </summary>
		void Serialize(string filePath, TestRecord testRecord);
		
		/// <summary>
		/// Deserialize the TestRecord from the sepcified path if possible.
		/// Return null if deserialization is impossible.
		/// </summary>
		TestRecord Deserialize(string filePath);
	}
	
	[Serializable]
	public class TestRecord
	{
		string name;
		UnitTestResultCollection results;
		TestRecordCollection tests;
		internal bool Modified;
		
		[XmlAttribute]
		public string Name {
			get { return name; }
			set { name = value; }
		}
		
		public UnitTestResultCollection Results {
			get { return results; }
			set { results = value; }
		}
		
		public TestRecordCollection Tests {
			get { return tests; }
			set { tests = value; }
		}
	}
	
	[Serializable]
	public class TestRecordCollection: CollectionBase
	{
		public new TestRecord this [int n] {
			get { return (TestRecord) ((IList)this) [n]; }
		}
		
		public new TestRecord this [string name] {
			get {
				for (int n=0; n<List.Count; n++)
					if (((TestRecord)List [n]).Name == name)
						return (TestRecord) List [n];
				return null;
			}
		}
		
		public void Add (TestRecord test)
		{
			((IList)this).Add (test);
		}
	}
	
	[Serializable]
	public class UnitTestResultCollection: CollectionBase
	{
		public new UnitTestResult this [int n] {
			get { return (UnitTestResult) ((IList)this) [n]; }
		}
		
		public void Add (UnitTestResult test)
		{
			((IList)this).Add (test);
		}
	}	
}