File: UnitTest.sc

package info (click to toggle)
supercollider 1%3A3.13.0%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 80,292 kB
  • sloc: cpp: 476,363; lisp: 84,680; ansic: 77,685; sh: 25,509; python: 7,909; makefile: 3,440; perl: 1,964; javascript: 974; xml: 826; java: 677; yacc: 314; lex: 175; objc: 152; ruby: 136
file content (546 lines) | stat: -rw-r--r-- 13,711 bytes parent folder | download | duplicates (3)
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
UnitTest {

	var currentMethod, debug = "";
	const <brief = 1, <full = 2;
	classvar <failures, <passes, routine, <>reportPasses = true, <>passVerbosity;
	classvar <allTestClasses;

	*initClass {
		passVerbosity = full;
	}

	*findTestClasses {
		allTestClasses = UnitTest.allSubclasses.collectAs({ |class|
			var classkey = class.asString[4..]; // drop Meta_
			var methtests = class.findTestMethods.collectAs({ | method |
				method.name.asString -> {
					class.prRunWithinSetUpClass {
						class.new.runTestMethod(method);
					}
				}
			}, Dictionary);
			methtests.add(" run all in this class" -> { class.run });
			classkey -> methtests;
		}, Dictionary);
		// err there may be some empty classes hanging around
		allTestClasses = allTestClasses.reject { | class | class.size == 1 };
		allTestClasses.add("...All..." -> Dictionary["Run all" -> { UnitTest.runAll }]);

	}

	// run a single test in the name format "TestPolyPlayerPool:test_prepareChildrenToBundle"
	*runTest { | methodName |
		var class, method, unitTest;
		# class, method = methodName.split($:);
		class = class.asSymbol.asClass;
		method = class.findMethod(method.asSymbol);
		if(method.isNil) {
			Error("Test method not found " + methodName).throw
		};
		class.prRunWithinSetUpClass {
			class.new.runTestMethod(method);
		}
	}

	// called before running tests in a unit test class
	*setUpClass {}

	// called after running tests in a unit test class
	*tearDownClass {}

	// called before each test
	setUp {}

	// called after each test
	tearDown {}

	// run all tests of this UnitTest
	*run { | reset = true, report = true |
		if(reset) { this.reset };
		this.prRunAllTestMethods(report)
	}


	// run all tests of all subclasses of this UnitTest
	*runAll {
		if(this === UnitTest, {
			^this.forkIfNeeded {
				this.reset;
				this.allSubclasses.do { |testClass|
					testClass.run(false, false);
					0.1.wait;
				};
				this.report
			}
		}, {
			^this.shouldNotImplement(thisMethod)
		});
	}

	// run a single test method of this class
	// this assumes that setUpClass has been called
	// and that tearDownClass is called afterwards
	runTestMethod { | method, report = true |
		this.class.forkIfNeeded {
			this.setUp;
			currentMethod = method;
			this.perform(method.name);
			this.tearDown;
			if(report) { this.class.report };
		}
	}


	*prRunAllTestMethods { |report = true|
		"RUNNING UNIT TEST '%'".format(this.name).inform;
		this.forkIfNeeded {
			this.prRunWithinSetUpClass {
				this.findTestMethods.do { |method|
					this.new.runTestMethod(method, false)
				};
				if(report) { this.report };
			}
		}
	}

	// call a function in the context of this test class
	*prRunWithinSetUpClass { |func|
		this.forkIfNeeded {
			this.setUpClass;
			func.value(this);
			this.tearDownClass;
		}
	}

	*gui {
		this.findTestClasses;
		^UnitTestGUI.new(this.allTestClasses)
	}

	///////////////////////////////////////////////////////////////////////
	// call these in your test_ methods to check conditions and pass or fail

	assert { | boolean, message, report = true, onFailure, details |
		if(boolean.not) {
			this.failed(currentMethod, message, report, details);
			if(onFailure.notNil) {
				{ onFailure.value }.defer;
				Error("UnitTest halted with onFailure handler.").throw;
			};
		} {
			this.passed(currentMethod, message, report, details)
		};
		^boolean
	}

	assertEquals { |a, b, message = "", report = true, onFailure |
		var details = "Is:\n\t % \nShould be:\n\t %".format(a, b);
		this.assert(a == b, message, report, onFailure, details);
	}

	assertFloatEquals { |a, b, message = "", within = 0.0001, report = true, onFailure|
		var details = ("Is:\n\t % \nShould equal (within range %):\n\t %").format(a, within, b);
		this.assert((a - b).abs <= within, message, report, onFailure, details);
	}

	assertArrayFloatEquals { |a, b, message = "", within = 0.0001, report = true, onFailure|
		var results, startFrom, someHaveFailed;
		a = a.asArray;

		// Check whether all in array meet the condition.
		results = (a - b).abs <= within;
		someHaveFailed = results.includes(false);

		if(someHaveFailed) {
			startFrom = results.indexOf(false);
			// Add failure details:
			message = message ++
			"\n% of % items in array failed to match."
			" Displaying arrays from index of first failure"
			" (%) onwards:\n%\n! = \n%\n"
			.format(
				results.count(_ == false),
				results.size,
				startFrom,
				a[startFrom..],
				if(b.isArray) { b[startFrom..] } { b }
			);
			this.failed(currentMethod, message, report);

			if(onFailure.notNil) {
				{ onFailure.value }.defer;
				Error("UnitTest halted with onFailure handler.").throw;
			};
		} {
			this.passed(currentMethod, message, report)
		}
		^someHaveFailed.not
	}

	assertException { | func, errorClass, message, report = true, onFailure, details |
		var moreDetails = nil;
		var passed = false;
		errorClass = errorClass.asClass;

		func.try { |error|
			if(error.isKindOf(errorClass)) {
				// Add extra info in case the class was an unexpected child type.
				moreDetails = "Received exception of class '%', with message: '%'".format(
					error.class.name,
					error.errorString
				);
				passed = true;
			} {
				moreDetails = "Received exception of class '%', with message: '%'\nExpected class '%'".format(
					error.class.name,
					error.errorString,
					errorClass.name
				);
			}
		};

		moreDetails = moreDetails ?? { "Function did not throw an exception" };
		if(details.isNil) { details = moreDetails } { details = details ++ "\n" ++ moreDetails };
		^this.assert(passed, message, report, onFailure, details);
	}

	assertNoException { | func, message, report = true, onFailure, details |
		var moreDetails;
		var passed = true;

		func.try { |error|
			moreDetails = "Function threw an exception of class '%', with message: '%'".format(
				error.class.name,
				error.errorString
			);
			if(details.isNil) { details = moreDetails } { details = details ++ "\n" ++ moreDetails };
			passed = false;
		};
		^this.assert(passed, message, report, onFailure, details)
	}


	// make a further assertion only if it passed, or only if it failed
	ifAsserts { | boolean, message, ifPassedFunc, ifFailedFunc, report = true|
		if(boolean.not) {
			this.failed(currentMethod, message, report);
			ifFailedFunc.value;
		} {
			this.passed(currentMethod,message, report);
			ifPassedFunc.value;
		};
		^boolean
	}

	// this method should be avoided if at all possible
	// it's better to use CondVar directly in tests instead
	wait { |predicate, failureMessage = "", maxTime = 10.0|
		var condvar = CondVar();
		var waitDur = 0.1;
		var limit = max(1.0, maxTime / waitDur);

		while {
			(limit >= 0) and: { condvar.waitFor(waitDur, predicate).not }
		} {
			limit = limit - 1;
		};

		// consider test failed if limit is surpassed
		if(limit < 0) {
			this.failed(currentMethod, failureMessage)
		}
	}

	// wait is better
	asynchAssert { |waitConditionBlock, testBlock, timeoutMessage = "", timeout = 10|
		var limit = timeout / 0.1;

		while {
			waitConditionBlock.value.not and:
			{ (limit = limit - 1) > 0 }
		} {
			0.1.wait;
		};

		if(limit == 0) {
			this.failed(currentMethod,"Timeout:" + timeoutMessage)
		} {
			testBlock.value
		};
	}

	// if already booted, then freeAll and create new allocators
	// if this is called inside a routine, the routine waits until server is booted

	bootServer { | server |
		server = server ? Server.default;
		if(server.serverRunning.not) {
			server.bootSync
		} {
			server.freeAll;
		};
		server.newAllocators; // new nodes, busses regardless
	}

	debug { |text|
		debug = debug ++ text;
	}

	// call failure directly
	failed { | method, message, report = true, details |
		var r = UnitTestResult(this, method, message, details, debug);
		failures = failures.add(r);

		if(report) {
			Post << Char.nl << "FAIL: ";
			r.report;
			Post << Char.nl;
		};
	}

	// call pass directly
	passed { | method, message, report = true, details |
		var r = UnitTestResult(this, method, message, details, debug);
		passes = passes.add(r);

		if(report and: { reportPasses }) {
			Post << "PASS: ";
			r.report(passVerbosity == brief);
		};
	}

	// PRIVATE IMPLEMENTATION
	// these are mostly private
	// don't use this directly,
	// use TestClass.run

	*runTestClassForClass { | class, reset = true, report = true |
		var testClass;
		if(class.isNil) {
			"No class supplied for testing".die;
		};
		testClass = ("Test" ++ class.name.asString).asSymbol.asClass;
		if(testClass.isNil) {
			("No test class found for " + class).inform;
			^this
		};
		if(testClass.respondsTo(\run).not) {
			("Attempting to run UnitTests on class that is not a subclass of UnitTest"
				+ testClass).error;
			^this
		};
		testClass.run(reset,report)
	}

	*findTestClass { | forClass |
		^("Test" ++ forClass.name.asString).asSymbol.asClass
	}

	*report {
		Post.nl;
		"UNIT TESTS FOR '%' COMPLETED".format(this.name).inform;
		if(failures.size > 0) {
			"There were failures:".inform;
			failures.do { arg results;
				results.report(true);
			};
		} {
			"There were no failures".inform;
		}
	}

	// private - use TestYourClass.run

	*forkIfNeeded { |function|
		function.forkIfNeeded(AppClock)
	}

	// returns the methods named test_
	findTestMethods {
		^this.class.findTestMethods
	}

	*findTestMethods {
		^methods.select { |m|
			m.name.asString.beginsWith("test_")
		}
	}

	*classesWithTests { | package = 'Common'|
		^Quarks.classesInPackage(package).select { |c|
			UnitTest.findTestClass(c).notNil
		}
	}

	*classesWithoutTests { |package = 'Common'|
		^Quarks.classesInPackage(package).difference(UnitTest.classesWithTests(package))
	}

	// whom I am testing
	// removing "Test" by copyToEnd(4)
	*findTestedClass {
		^this.name.asString.copyToEnd(4).asSymbol.asClass
	}

	// methods in the tested class that do not have test_ methods written
	*untestedMethods {
		var testedClass,testMethods,testedMethods,untestedMethods;
		testedClass = this.findTestedClass;
		// what methods in the target class do not have tests written for them ?
		testMethods = this.findTestMethods;
		testedMethods = testMethods.collect { |meth|
			testedClass.findMethod(meth.name.asString.copyToEnd(5).asSymbol)
		}.reject(_.isNil);

		if(testedMethods.isNil or: { testedMethods.isEmpty }) {
			untestedMethods = testedClass.methods
		} {
			untestedMethods = testedClass.methods.select { |meth|
				testedMethods.includes(meth).not
			}
		};

		// reject getters,setters, empty methods
		untestedMethods = untestedMethods.reject { |meth| meth.code.isNil };
		^untestedMethods
	}

	*listUntestedMethods { | forClass |
		this.findTestClass(forClass).untestedMethods.do {|m| m.name.postln }
	}

	// private
	*reset {
		failures = [];
		passes = [];
		routine.stop;
	}

	s {
		^Server.default; // for convenient translation to/from example code
	}

}


UnitTestResult {

	var <testClass, <testMethod, <message, <details, <debug;

	*new { |testClass, testMethod, message = "", details, debug|
		^super.newCopyArgs(testClass ? this, testMethod ? thisMethod, message, details, debug)
	}

	report { |brief=false|
		var name = if(testMethod.notNil) { testMethod.name } { "unit test result" };
		Post << testClass.asString << ": " << name;
		if (message.size > 0) {
			Post << " - " << message;
		};
		if (brief.not) {
			if (debug.size > 0) {
				Post << Char.nl << debug;
			};
			if (details.notNil) {
				Post << Char.nl << details;
			};
		};
		Post << Char.nl;
	}
}

// scripts may be located next to the class or one folder below
// they should have a unique name and end with "_unittest.scd"
// the scripts are listed under this test class: UnitTestScript

// UnitTestScript mimics the behavior of Method,
// in order to sneak into the anthill without getting eaten

UnitTestScript : UnitTest {

	var <>name, <>path;

	classvar <allScripts;
	classvar fileEnd = "_unittest.scd";
	classvar scriptDict;

	*new { |name, path|
		^super.new.init(name, path)
	}

	init { |argName, argPath|
		name = argName;
		path = argPath;
	}

	*initClass {
		scriptDict = ();
	}

	*runTest { | scriptName |
		var script;
		allScripts ?? { this.findTestScripts };
		script = allScripts[scriptName.asSymbol];
		if(script.isNil) { ("UnitTestScript: script not found: "+ scriptName ).warn } {
			script.runScript
		}
	}

	*findTestScripts {
		var classPaths;
		var func = { |path|
			var scriptPaths,fileNames, scriptNames;
			scriptPaths = pathMatch(path ++"/*" ++ fileEnd);
			scriptPaths = scriptPaths ++ pathMatch(path ++"/*/*" ++ fileEnd);
			scriptPaths = scriptPaths.as(Set).as(Array); // remove duplicates
			fileNames = scriptPaths.collect(_.basename);
			scriptNames = fileNames.collect { |x| x.replace(fileEnd, "").asSymbol };
			scriptNames.do { |name, i|
				var oldPath = scriptDict.at(name);
				if(oldPath.notNil and: { oldPath != scriptPaths[i] }) {
					Error(
						"duplicate script name:\n%\n%\n\npath:%\n\n"
						.format(scriptPaths[i], scriptDict[name], path)
					);
				};
				scriptDict.put(name, scriptPaths[i]);
				if(oldPath.notNil) { allScripts.add(this.new(name, scriptPaths[i])) };
			};
		};

		classPaths = Class.allClasses.collectAs({ |class| class.filenameSymbol.asString.dirname }, Set);
		allScripts = List.new;
		classPaths.do(func);

	}

	*findTestMethods {
		this.findTestScripts;
		^allScripts
	}

	runTestMethod { |testScript|

		testScript.runScript;

	}

	runScript {
		("RUNNING UNIT TEST SCRIPT" + name ++ " path:" ++ path ++ "\n\n").inform;
		this.class.forkIfNeeded {
			currentMethod = this;
			path.load.value(this);
			this.class.report;
		}
	}

	run {
		allScripts ?? { this.class.findTestScripts };
		Routine {
			allScripts.do { |testScript|
				this.runTestMethod(testScript)
			}
		}.play(AppClock);
	}

}