trial.interfaces 179/185(96%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
50225
51224
520
530
541
550
561
571
581
591
601
610
621
630
640
650
660
671
682
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
14864
1490
1500
1510
1520
1536
1540
1550
1560
1570
1581
1590
1601
1610
1620
1630
1640
1650
1662
1670
1680
1690
1700
1711
1720
1732
1742
1750
1760
1770
1780
1791
1800
1812
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2011
2021
2030
2041
2050
2061
2071
2080
2090
2101
2110
2120
2130
2140
2151
2161
2171
2180
2191
2200
2211
2221
2230
2240
2251
2260
2270
2280
2290
2306
2316
2326
2336
2340
2356
2360
2370
2380
2390
2400
2411
2422
2432
2440
2452
2460
2470
2480
2490
2502
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
26570
2660
2670
2680
2690
2700
2710
2722
2730
2740
2750
276839
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3068
3078
3088
3098
3108
3118
3120
31324
3140
3150
3160
3170
3180
31935
32035
32135
3220
3230
3240
325312
326312
3270
3280
3290
330488
331488
332488
333488
334488
3350
3360
3370
33869
3390
34069
34169
34277
34369
3440
34569
3460
3470
3480
3490
3500
3510
3520
3531
3541
3550
3562
3570
3580
3590
3600
3610
3620
363231
3640
365231
366231
367231
368231
369231
3700
371231
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
40053
40153
40253
40353
4040
4050
4060
4070
4080
4090
4100
4110
4120
41351
41451
41551
41651
4170
4180
4190
4201
4211
4221
4231
4241
4250
4260
4270
4281
4291
4301
4311
4321
4331
4340
4350
4360
4370
43845
43945
44045
44145
442269
44346
4440
44545
4460
4470
4480
4490
4501
4510
4520
4530
4540
4550
4562
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
479339
480339
481339
4820
4830
4840
485229
4860
487229
488229
489229
490233
491233
4920
493229
4940
4950
4960
4970
4985
4990
5000
5010
5020
5030
5041
5051
5061
5071
5081
5091
5100
5112
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
559304
5600
561304
562304
5630
5640
5650
5660
567224
5680
569224
570224
571224
572227
573224
5740
575224
5760
5770
5780
5790
5800
5810
5820
5830
5840
5856
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
59712
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6231
6240
6252
6260
6270
6280
6290
6300
6310
6321
6331
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6621
6630
6640
6650
6660
6671
6680
6690
6700
6710
6720
6734
6740
6750
6760
6770
6780
67929
68074
6810
6820
6830
68429
68583
6860
6870
6880
68929
69079
6910
6920
6930
69429
69589
6960
6970
6980
69929
70016
7010
7020
7030
7040
70529
70661
7070
7080
7090
71029
71163
7120
7130
7140
7150
7160
71712
7180
7190
7200
7210
722299151
7230
7240
7250
7260
72726
7280
7290
7300
7310
73226
7330
7340
7350
7360
737231
7380
7390
7400
7410
742230
7430
7440
7450
7460
747238
7481570
7490
7500
7510
7520
753238
7541570
7550
7560
7570
7580
75918
76064
7610
7620
7630
7640
76518
76664
7670
7680
7690
7700
771236
772236
773236
7740
7750
7760
7770
77814
77914
7800
7810
7820
7830
78414
7850
7860
/++ A module containing the interfaces used for extending the test runner Copyright: © 2017 Szabo Bogdan License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Szabo Bogdan +/ module trial.interfaces; import std.datetime; import std.algorithm; import std.array; import std.functional; import std.conv; import std.file; import std.path; import std.uuid; import std.exception; import std.json; import std.algorithm; version(unittest) { version(Have_fluent_asserts) { import fluent.asserts; } } /// Alias to a Test Case function type alias TestCaseDelegate = void delegate() @system; alias TestCaseFunction = void function() @system; /// A Listener for the main test events interface ILifecycleListener { /// This method is trigered when before the test start void begin(ulong testCount); /** This method is triggered when you can perform some updates. The frequency varries by the test executor that you choose */ void update(); /// This method is trigered when your tests are ended void end(SuiteResult[]); } /// Convert a Throwable to a json string string toJsonString(Throwable throwable) { if(throwable is null) { return "{}"; } string fields; fields ~= `"file":"` ~ throwable.file.escapeJson ~ `",`; fields ~= `"line":"` ~ throwable.line.to!string.escapeJson ~ `",`; fields ~= `"msg":"` ~ throwable.msg.escapeJson ~ `",`; fields ~= `"info":"` ~ throwable.info.to!string.escapeJson ~ `",`; fields ~= `"raw":"` ~ throwable.toString.escapeJson ~ `"`; return "{" ~ fields ~ "}"; } /// convert a Throwable to json unittest { auto exception = new Exception("some message", __FILE__, 58); exception.toJsonString.should.equal(`{"file":"lifecycle/trial/interfaces.d","line":"58","msg":"some message","info":"null","raw":"object.Exception@lifecycle/trial/interfaces.d(58): some message"}`); } /// A listener that provides test cases to be executed interface ITestDiscovery { /// Get the test cases from the compiled source code TestCase[] getTestCases(); } /// A listener that provides test cases contained in a certain file interface ITestDescribe { /// Get the test cases by parsing the source code TestCase[] discoverTestCases(string file); } /** A Listener that can run tests. During the test execution can be used only one instance of this listance. After all the tests were executed the result of all three methods are concatenated and passed to `ILifecycleListener.end(SuiteResult[])` */ interface ITestExecutor { /// Called before all tests were discovered and they are ready to be executed SuiteResult[] beginExecution(ref const(TestCase)[]); /// Run a particullary test case SuiteResult[] execute(ref const(TestCase)); /// Called when there is no more test to be executed SuiteResult[] endExecution(); } /// A Listener for the suite events interface ISuiteLifecycleListener { /// Called before a suite execution void begin(ref SuiteResult); /// Called after a suite execution void end(ref SuiteResult); } /// A Listener for handling attachments interface IAttachmentListener { /// Called when an attachment is ready void attach(ref const Attachment); } /// A Listener for the test case events interface ITestCaseLifecycleListener { /// Called before a test execution void begin(string suite, ref TestResult); // Called after a test execution void end(string suite, ref TestResult); } /// A Listener for the step events interface IStepLifecycleListener { /// Called before a step begins void begin(string suite, string test, ref StepResult); /// Called after a step ended void end(string suite, string test, ref StepResult); } /// A struct representing a label for test results struct Label { /// The label name string name; /// The label value string value; /// Convert the struct to a JSON string string toString() inout { return `{ "name": "` ~ name.escapeJson ~ `", "value": "` ~ value.escapeJson ~ `" }`; } /// static Label[] fromJsonArray(string value) { return parseJSON(value).array.map!(a => Label(a["name"].str, a["value"].str)).array; } /// static Label fromJson(string value) { auto parsedValue = parseJSON(value); return Label(parsedValue["name"].str, parsedValue["value"].str); } } /// Label string representation should be in Json format unittest { Label("name", "value").toString.should.equal(`{ "name": "name", "value": "value" }`); } /// create a label from a json object unittest { auto label = Label.fromJson(`{ "name": "name", "value": "value" }`); label.name.should.equal("name"); label.value.should.equal("value"); } /// create a label list from a json array unittest { auto labels = Label.fromJsonArray(`[{ "name": "name1", "value": "value1" }, { "name": "name2", "value": "value2" }]`); labels.should.equal([ Label("name1", "value1"), Label("name2", "value2") ]); } /// A struct representing an attachment for test steps struct Attachment { /// The attachment name string name; /// The absolute path to the attachment string file; /// The file mime path string mime; /// The attachement destination. All the attached files will be copied in this folder if /// it is not allready inside static string destination; /// Add a file to the current test or step static Attachment fromFile(const string name, const string path, const string mime) { auto fileDestination = buildPath(destination, randomUUID.toString ~ "." ~ path.baseName); copy(path, fileDestination); auto a = const Attachment(name, fileDestination, mime); if(LifeCycleListeners.instance !is null) { LifeCycleListeners.instance.attach(a); } return a; } /// Create an attachment from a string static Attachment fromString(const string content) { ulong index; string fileDestination = buildPath(destination, randomUUID.toString ~ ".txt"); fileDestination.write(content); auto a = const Attachment("unknown", fileDestination, "text/plain"); if(LifeCycleListeners.instance !is null) { LifeCycleListeners.instance.attach(a); } return a; } /// string toString() inout { string fields; fields ~= `"name":"` ~ name ~ `",`; fields ~= `"file":"` ~ file ~ `",`; fields ~= `"mime":"` ~ mime ~ `"`; return "{" ~ fields ~ "}"; } } /// Create an attachement from string unittest { auto a = Attachment.fromString("content"); a.name.should.equal("unknown"); a.mime.should.equal("text/plain"); readText(a.file).should.equal("content"); } /// Convert an attachement to Json string unittest { Attachment("dub", "dub.json", "text/json").toString.should.equal( `{"name":"dub","file":"dub.json","mime":"text/json"}` ); } /// Represents a line of code in a certain file. struct SourceLocation { /// string fileName; /// size_t line; /// Converts the structure to a JSON string string toString() inout { return `{ "fileName": "` ~ fileName.escapeJson ~ `", "line": ` ~ line.to!string ~ ` }`; } } /// SourceLocation string representation should be a JSON string unittest { SourceLocation("file.d", 10).toString.should.equal(`{ "fileName": "file.d", "line": 10 }`); } private string escapeJson(string value) { return value.replace(`"`, `\"`).replace("\r", `\r`).replace("\n", `\n`).replace("\t", `\t`); } /// A test case that will be executed struct TestCase { /** The test case suite name. It can contain `.` which is treated as a separator for nested suites */ string suiteName; /// The test name string name; /** The function that must be executed to check if the test passes or not. In case of failure, an exception is thrown. */ TestCaseDelegate func; /** A list of labels that will be added to the final report */ Label[] labels; /// The test location SourceLocation location; /// this(const TestCase testCase) { suiteName = testCase.suiteName.dup; name = testCase.name.dup; func = testCase.func; location = testCase.location; labels.length = testCase.labels.length; foreach(key, val; testCase.labels) { labels[key] = val; } } /// this(T)(string suiteName, string name, T func, Label[] labels, SourceLocation location) { this(suiteName, name, func.toDelegate, labels); this.location = location; } /// this(string suiteName, string name, TestCaseFunction func, Label[] labels = []) { this(suiteName, name, func.toDelegate, labels); } /// this(string suiteName, string name, TestCaseDelegate func, Label[] labels = []) { this.suiteName = suiteName; this.name = name; this.func = func; this.labels = labels; } string toString() const { string jsonRepresentation = "{ "; jsonRepresentation ~= `"suiteName": "` ~ suiteName.escapeJson ~ `", `; jsonRepresentation ~= `"name": "` ~ name.escapeJson ~ `", `; jsonRepresentation ~= `"labels": [ ` ~ labels.map!(a => a.toString).join(", ") ~ ` ], `; jsonRepresentation ~= `"location": ` ~ location.toString; return jsonRepresentation ~ " }"; } } /// TestCase string representation should be a JSON string unittest { void MockTest() {} auto testCase = TestCase("some suite", "some name", &MockTest, [ Label("label1", "value1"), Label("label2", "value2") ]); testCase.location = SourceLocation("file.d", 42); testCase.toString.should.equal(`{ "suiteName": "some suite", "name": "some name", ` ~ `"labels": [ { "name": "label1", "value": "value1" }, { "name": "label2", "value": "value2" } ], ` ~ `"location": { "fileName": "file.d", "line": 42 } }`); } /// TestResult toTestResult(const TestCase testCase) { auto testResult = new TestResult(testCase.name.dup); testResult.begin = Clock.currTime; testResult.end = testResult.begin; testResult.labels = testCase.labels.dup; testResult.fileName = testCase.location.fileName; testResult.line = testCase.location.line; return testResult; } /// A suite result struct SuiteResult { /** The suite name. It can contain `.` which is treated as a separator for nested suites */ string name; /// when the suite started SysTime begin; /// when the suite ended SysTime end; /// the tests executed for the current suite TestResult[] tests; /// The list of attached files Attachment[] attachments; /// @disable this(); /// this(string name) { this.name = name; begin = SysTime.fromUnixTime(0); end = SysTime.fromUnixTime(0); } /// this(string name, SysTime begin) { this.name = name; this.begin = begin; } /// this(string name, SysTime begin, SysTime end) { this.name = name; this.begin = begin; this.end = end; } /// this(string name, SysTime begin, SysTime end, TestResult[] tests) { this.name = name; this.begin = begin; this.end = end; this.tests = tests; } /// this(string name, SysTime begin, SysTime end, TestResult[] tests, Attachment[] attachments) { this.name = name; this.begin = begin; this.end = end; this.tests = tests; this.attachments = attachments; } /// Convert the struct to a json string string toString() { string fields; fields ~= `"name":"` ~ name.escapeJson ~ `",`; fields ~= `"begin":"` ~ begin.toISOExtString ~ `",`; fields ~= `"end":"` ~ end.toISOExtString ~ `",`; fields ~= `"tests":[` ~ tests.map!(a => a.toString).join(",") ~ `],`; fields ~= `"attachments":[` ~ attachments.map!(a => a.toString).join(",") ~ `]`; return "{" ~ fields ~ "}"; } } unittest { auto result = SuiteResult("suite name", SysTime.fromISOExtString("2000-01-01T00:00:00Z"), SysTime.fromISOExtString("2000-01-01T01:00:00Z"), [ new TestResult("test name") ], [ Attachment() ]); result.toString.should.equal( `{"name":"suite name","begin":"2000-01-01T00:00:00Z","end":"2000-01-01T01:00:00Z","tests":[{"name":"test name","begin":"-29227-04-19T21:11:54.5224192Z","end":"-29227-04-19T21:11:54.5224192Z","steps":[],"attachments":[],"fileName":"","line":"0","status":"created","labels":[],"throwable":{}}],"attachments":[{"name":"","file":"","mime":""}]}` ); } /// A step result class StepResult { /// The step name string name; /// When the step started SysTime begin; /// When the step ended SysTime end; /// The list of the child steps StepResult[] steps; /// The list of attached files Attachment[] attachments; this() { begin = SysTime.min; end = SysTime.min; } protected string fields() { string result; result ~= `"name":"` ~ name.escapeJson ~ `",`; result ~= `"begin":"` ~ begin.toISOExtString ~ `",`; result ~= `"end":"` ~ end.toISOExtString ~ `",`; result ~= `"steps":[` ~ steps.map!(a => a.toString).join(",") ~ `],`; result ~= `"attachments":[` ~ attachments.map!(a => a.toString).join(",") ~ `]`; return result; } /// Convert the result to a json string override string toString() { return "{" ~ fields ~ "}"; } } /// Convert a step result to a json unittest { auto step = new StepResult(); step.name = "step name"; step.begin = SysTime.fromISOExtString("2000-01-01T00:00:00Z"); step.end = SysTime.fromISOExtString("2000-01-01T01:00:00Z"); step.steps = [ new StepResult() ]; step.attachments = [ Attachment() ]; step.toString.should.equal(`{"name":"step name","begin":"2000-01-01T00:00:00Z","end":"2000-01-01T01:00:00Z","steps":` ~ `[{"name":"","begin":"-29227-04-19T21:11:54.5224192Z","end":"-29227-04-19T21:11:54.5224192Z","steps":[],"attachments":`~ `[]}],"attachments":[{"name":"","file":"","mime":""}]}`); } /// A test result class TestResult : StepResult { /// The states that a test can have. enum Status { /// created, /// failure, /// skip, /// started, /// success, /// pending, /// unknown } /// The file that contains this test string fileName; /// The line where this test starts size_t line; /// Represents the test status Status status = Status.created; /** A list of labels that will be added to the final report */ Label[] labels; /** The reason why a test has failed. This value must be set only if the tests has the `failure` state */ Throwable throwable; /// Convenience constructor that sets the test name this(string name) { this.name = name; super(); } /// Convert the result to a json string override string toString() { string result = fields ~ ","; result ~= `"fileName":"` ~ fileName.escapeJson ~ `",`; result ~= `"line":"` ~ line.to!string ~ `",`; result ~= `"status":"` ~ status.to!string ~ `",`; result ~= `"labels":[` ~ labels.map!(a => a.toString).join(",") ~ `],`; result ~= `"throwable":` ~ throwable.toJsonString; return "{" ~ result ~ "}"; } } /// Attribute that marks the test as flaky. Different reporters will interpret this information /// in different ways. struct Flaky { /// Returns the labels that set the test a flaky static Label[] labels() { return [Label("status_details", "flaky")]; } } /// Attribute that links an issue to a test. Some test reporters can display links, so the value can be also /// a link. struct Issue { private string name; /// Returns the labels that set the issue label Label[] labels() { return [ Label("issue", name) ]; } } /// Attribute that sets the feaure label struct Feature { private string name; /// Returns the labels that set the feature label Label[] labels() { return [ Label("feature", name) ]; } } /// Attribute that sets the story label struct Story { private string name; /// Returns the labels that set the feature label Label[] labels() { return [ Label("story", name) ]; } } /// Attach the readme file unittest { auto attachment = Attachment.fromFile("readme file", "README.md", "text/plain"); attachment.file.exists.should.equal(true); } /// An exception that should be thrown by the pending test cases class PendingTestException : Exception { /// this(string file = __FILE__, size_t line = __LINE__, Throwable next = null) { super("You cannot run pending tests", file, line, next); } } /// The lifecycle listeners collections. You must use this instance in order /// to extend the runner. You can have as many listeners as you want. The only restriction /// is for ITestExecutor, which has no sense to have more than one instance for a run class LifeCycleListeners { /// The global instange. static LifeCycleListeners instance; private { ISuiteLifecycleListener[] suiteListeners; ITestCaseLifecycleListener[] testListeners; IStepLifecycleListener[] stepListeners; ILifecycleListener[] lifecycleListeners; ITestDiscovery[] testDiscoveryListeners; IAttachmentListener[] attachmentListeners; ITestExecutor executor; string currentTest; bool started; } @property { /// Return an unique name for the current running test. If there is no test running it /// will return an empty string string runningTest() const nothrow { return currentTest; } /// True if the tests are being executed bool isRunning() { return started; } } /// TestCase[] getTestCases() { return testDiscoveryListeners.map!(a => a.getTestCases).join; } /// Add a listener to the collection void add(T)(T listener) { static if(!is(CommonType!(ISuiteLifecycleListener, T) == void)) { suiteListeners ~= cast(ISuiteLifecycleListener) listener; suiteListeners = suiteListeners.filter!(a => a !is null).array; } static if(!is(CommonType!(ITestCaseLifecycleListener, T) == void)) { testListeners ~= cast(ITestCaseLifecycleListener) listener; testListeners = testListeners.filter!(a => a !is null).array; } static if(!is(CommonType!(IStepLifecycleListener, T) == void)) { stepListeners ~= cast(IStepLifecycleListener) listener; stepListeners = stepListeners.filter!(a => a !is null).array; } static if(!is(CommonType!(ILifecycleListener, T) == void)) { lifecycleListeners ~= cast(ILifecycleListener) listener; lifecycleListeners = lifecycleListeners.filter!(a => a !is null).array; } static if(!is(CommonType!(ITestExecutor, T) == void)) { if(cast(ITestExecutor) listener !is null) { executor = cast(ITestExecutor) listener; } } static if(!is(CommonType!(ITestDiscovery, T) == void)) { testDiscoveryListeners ~= cast(ITestDiscovery) listener; testDiscoveryListeners = testDiscoveryListeners.filter!(a => a !is null).array; } static if(!is(CommonType!(IAttachmentListener, T) == void)) { attachmentListeners ~= cast(IAttachmentListener) listener; attachmentListeners = attachmentListeners.filter!(a => a !is null).array; } } /// Send the attachment to all listeners void attach(ref const Attachment attachment) { attachmentListeners.each!(a => a.attach(attachment)); } /// Send the update event to all listeners void update() { lifecycleListeners.each!"a.update"; } /// Send the begin run event to all listeners void begin(ulong testCount) { lifecycleListeners.each!(a => a.begin(testCount)); } /// Send the end runer event to all listeners void end(SuiteResult[] result) { lifecycleListeners.each!(a => a.end(result)); } /// Send the begin suite event to all listeners void begin(ref SuiteResult suite) { suiteListeners.each!(a => a.begin(suite)); } /// Send the end suite event to all listeners void end(ref SuiteResult suite) { suiteListeners.each!(a => a.end(suite)); } /// Send the begin test event to all listeners void begin(string suite, ref TestResult test) { currentTest = suite ~ "." ~ test.name; testListeners.each!(a => a.begin(suite, test)); } /// Send the end test event to all listeners void end(string suite, ref TestResult test) { currentTest = ""; testListeners.each!(a => a.end(suite, test)); } /// Send the begin step event to all listeners void begin(string suite, string test, ref StepResult step) { currentTest = suite ~ "." ~ test ~ "." ~ step.name; stepListeners.each!(a => a.begin(suite, test, step)); } /// Send the end step event to all listeners void end(string suite, string test, ref StepResult step) { currentTest = ""; stepListeners.each!(a => a.end(suite, test, step)); } /// Send the execute test to the executor listener SuiteResult[] execute(ref const(TestCase) func) { started = true; scope(exit) started = false; return executor.execute(func); } /// Send the begin execution with the test case list to the executor listener SuiteResult[] beginExecution(ref const(TestCase)[] tests) { enforce(executor !is null, "The test executor was not set."); return executor.beginExecution(tests); } /// Send the end execution the executor listener SuiteResult[] endExecution() { return executor.endExecution(); } }