fluentasserts.core.results 205/396(51%) 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
500
510
520
530
540
550
560
570
580
590
600
610
620
639
649
659
669
679
680
690
709
719
720
739
749
759
769
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
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1837
1840
1857
1860
1870
188556
1890
1900
19114
1920
1930
1940
195556
1960
197556
198556
1990
200556
2010
2020
2030
204560
2050
2060
2070
2080
2090
2100
2110
212553
2130
2140
2150
2162815
2170
2180
2190
2202815
2210
2220
2230
2247
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
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
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3894
3904
3914
3920
3930
3940
3950
3960
3970
3980
3990
4008
4010
4020
4030
4048
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4968
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
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
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
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
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6512
6520
6532
6542
6550
6560
6570
6580
6594
6604
6614
6624
6630
6644
6654
6660
6670
6688
6694
6700
6710
6724
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
691554
6920
69317944
6945642
695748
6960
6976922
6980
6990
7000
701554
7020
7030
7040
705558
706558
707558
708558
7090
710558
711558
712558
7130
7146697990
7151674358
7160
7171674358
71828903
71928903
7200
7210
7221674358
72328816
7240
7250
7261674358
7278848
7280
7290
7301674358
731127626
7323549
7333549
7340
7350
73633733
737558
738558
7390
740558
7410
7420
7430
7440
745558
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
790558
791558
7920
7930
79416522
7953991
7960
7973991
798108
7990
8000
8013991
802108
8030
8040
8054549
806550
807550
8080
8090
8103541
8118
8120
8130
8140
815550
8160
817341594
81885261
8190
82085261
821638
8220
8230
82485261
825638
8260
827638
828550
829550
8300
8310
8320
8330
834550
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8871123
8881123
8890
8901123
8911123
8920
89322333
8947070
8957070
8960
8977070
898139
8990
9000
9017070
902128
9030
9040
9057070
90611
9070
9080
9097059
910875
9110
9120
9136184
914509
9150
9160
91711305
91860
9190
9200
9215615
922543
9230
9240
9255072
9260
9270
9280
9295072
930646
9310
9320
9336239
9340
9350
9360
9370
9385072
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10002
10010
1002143
10030
10040
10050
10062
10072
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
1101556
11020
110388591
11042845
11050
11060
1107556
11082
11090
11100
1111554
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
1145558
1146558
1147558
11480
1149558
11500
11510
11520
11530
11540
1155558
1156558
11570
1158558
1159558
11600
1161558
11620
11630
11640
11650
11660
1167558
116827
116927
11700
11710
11720
11730
1174556
1175556
1176556
11770
1178556
1179556
11800
1181556
1182556
1183556
11840
1185556
1186554
11870
1188554
11890
11900
11912
11920
11932
11940
11950
11960
11970
11980
11990
12002
12010
12020
12030
12040
12054
12064
12070
12084
12090
12100
12110
12124
12134
12144
12150
1216662
1217144
12180
1219528
122050
122128
12220
12234
12240
12250
12260
1227144
122826
12290
12300
1231144
123246
12330
12340
1235288
12360
1237144
12380
1239144
1240144
1241144
12420
1243262
124412
12450
12460
12470
12484
12490
12500
12510
12520
12530
12540
12550
12560
12570
12580
12590
12600
12610
12620
12630
12640
12650
12660
12670
12680
12690
12700
12710
12720
12730
12740
12750
12760
12770
12780
12790
12800
12810
12820
12830
12840
12850
12860
12870
12880
12890
12900
12910
12920
12930
12940
12950
12960
12970
12980
12990
13000
13010
13020
13030
13040
13050
13060
13070
13080
13090
13100
13110
13120
13130
13140
13150
13160
13170
13180
13190
13200
13210
13220
13230
13240
13250
13260
13270
13280
13290
13300
13310
13320
13330
13340
13350
13360
13370
13380
13390
13400
13410
13420
13430
13440
13450
13460
134776
134838
134938
13500
135138
13520
13530
13540
135576
13560
135738
135838
135938
136038
13610
136238
136338
13640
1365125378
13660
13670
13680
13690
13700
13710
13720
13730
13740
13750
13760
13770
13780
13790
13800
13810
13820
13830
13840
13850
13860
13870
13880
13890
13900
13910
13920
13930
13940
13950
13960
13970
13980
13990
14000
14010
14020
14030
14040
14050
14060
14070
14080
14090
14100
14110
14120
14130
14140
14150
14160
14170
14180
14190
14200
14210
14220
14230
14240
14250
14260
14270
14280
14290
14300
14310
14320
14330
14340
14350
14360
14370
14380
14390
14400
14410
14420
14430
14440
14450
14460
14470
14480
14490
14500
14510
14520
14530
14540
14550
14560
14570
14580
14590
14600
14610
14620
14630
14640
14650
14660
14670
14680
14690
14700
14710
14720
14730
14740
14750
14760
14770
14780
14790
14800
14810
14820
14830
14840
14850
1486201777
148767232
14880
148967232
149059421
14910
14927811
14937811
14940
149577427
149617998
149717998
149817998
14990
15000
15010
15020
15030
15040
15050
15060
15070
15080
15090
15100
15110
15120
15130
15140
15150
15160
15170
15180
15190
15200
15210
15220
15230
15240
15250
15260
15270
15280
15290
15300
15310
15320
15330
15340
15350
15360
15370
15380
15390
15400
15410
15420
15430
15440
15450
15460
15470
15480
15490
15500
15510
15520
15530
15540
15550
15560
15570
15580
15590
15600
15610
15620
15630
15640
15650
15660
15670
15680
15690
15700
15710
15720
15730
15740
15750
15760
15770
15780
15790
15800
15810
15820
15830
15840
15850
15860
15870
15880
15890
15900
15910
15920
15930
15940
15950
15960
15970
15980
15990
16000
16010
16020
16030
16040
16050
16060
16070
16080
16090
16100
16110
16120
16130
16140
16150
16160
16170
16180
16190
16200
16210
16220
16230
16240
16250
16260
16270
16280
16290
16300
16310
16320
16330
16340
16350
16360
16370
16380
16390
16400
16410
16420
16430
module fluentasserts.core.results; import std.stdio; import std.file; import std.algorithm; import std.conv; import std.range; import std.string; import std.exception; import std.typecons; import dparse.lexer; import dparse.parser; @safe: /// Glyphs used to display special chars in the results struct ResultGlyphs { static { /// Glyph for the tab char string tab; /// Glyph for the \r char string carriageReturn; /// Glyph for the \n char string newline; /// Glyph for the space char string space; /// Glyph for the \0 char string nullChar; /// Glyph that indicates the error line string sourceIndicator; /// Glyph that sepparates the line number string sourceLineSeparator; /// Glyph for the diff begin indicator string diffBegin; /// Glyph for the diff end indicator string diffEnd; /// Glyph that marks an inserted text in diff string diffInsert; /// Glyph that marks deleted text in diff string diffDelete; } /// Set the default values. The values are static resetDefaults() { version(windows) { ResultGlyphs.tab = `\t`; ResultGlyphs.carriageReturn = `\r`; ResultGlyphs.newline = `\n`; ResultGlyphs.space = ` `; ResultGlyphs.nullChar = `␀`; } else { ResultGlyphs.tab = `¤`; ResultGlyphs.carriageReturn = `←`; ResultGlyphs.newline = `↲`; ResultGlyphs.space = `᛫`; ResultGlyphs.nullChar = `\0`; } ResultGlyphs.sourceIndicator = ">"; ResultGlyphs.sourceLineSeparator = ":"; ResultGlyphs.diffBegin = "["; ResultGlyphs.diffEnd = "]"; ResultGlyphs.diffInsert = "+"; ResultGlyphs.diffDelete = "-"; } } /// interface ResultPrinter { void primary(string); void info(string); void danger(string); void success(string); void dangerReverse(string); void successReverse(string); } version(unittest) { class MockPrinter : ResultPrinter { string buffer; void primary(string val) { buffer ~= "[primary:" ~ val ~ "]"; } void info(string val) { buffer ~= "[info:" ~ val ~ "]"; } void danger(string val) { buffer ~= "[danger:" ~ val ~ "]"; } void success(string val) { buffer ~= "[success:" ~ val ~ "]"; } void dangerReverse(string val) { buffer ~= "[dangerReverse:" ~ val ~ "]"; } void successReverse(string val) { buffer ~= "[successReverse:" ~ val ~ "]"; } } } struct WhiteIntervals { size_t left; size_t right; } WhiteIntervals getWhiteIntervals(string text) { auto stripText = text.strip; if(stripText == "") { return WhiteIntervals(0, 0); } return WhiteIntervals(text.indexOf(stripText[0]), text.lastIndexOf(stripText[stripText.length - 1])); } /// This is the most simple implementation of a ResultPrinter. /// All the plain data is printed to stdout class DefaultResultPrinter : ResultPrinter { void primary(string text) { write(text); } void info(string text) { write(text); } void danger(string text) { write(text); } void success(string text) { write(text); } void dangerReverse(string text) { write(text); } void successReverse(string text) { write(text); } } interface IResult { string toString(); void print(ResultPrinter); } /// A result that prints a simple message to the user class MessageResult : IResult { private { struct Message { bool isValue; string text; } Message[] messages; } this(string message) nothrow { add(false, message); } this() nothrow { } override string toString() { return messages.map!"a.text".join.to!string; } void startWith(string message) @safe nothrow { Message[] newMessages; newMessages ~= Message(false, message); newMessages ~= this.messages; this.messages = newMessages; } void add(bool isValue, string message) nothrow { this.messages ~= Message(isValue, message .replace("\r", ResultGlyphs.carriageReturn) .replace("\n", ResultGlyphs.newline) .replace("\0", ResultGlyphs.nullChar) .replace("\t", ResultGlyphs.tab)); } void addValue(string text) @safe nothrow { add(true, text); } void addText(string text) @safe nothrow { if(text == "throwAnyException") { text = "throw any exception"; } this.messages ~= Message(false, text); } void prependText(string text) @safe nothrow { this.messages = Message(false, text) ~ this.messages; } void prependValue(string text) @safe nothrow { this.messages = Message(true, text) ~ this.messages; } void print(ResultPrinter printer) { foreach(message; messages) { if(message.isValue) { printer.info(message.text); } else { printer.primary(message.text); } } } } version (unittest) { import fluentasserts.core.base; } @("Message result should return the message") unittest { auto result = new MessageResult("Message"); result.toString.should.equal("Message"); } @("Message result should replace the special chars") unittest { auto result = new MessageResult("\t \r\n"); result.toString.should.equal(`¤ ←↲`); } @("Message result should replace the special chars with the custom glyphs") unittest { scope(exit) { ResultGlyphs.resetDefaults; } ResultGlyphs.tab = `\t`; ResultGlyphs.carriageReturn = `\r`; ResultGlyphs.newline = `\n`; auto result = new MessageResult("\t \r\n"); result.toString.should.equal(`\t \r\n`); } @("Message result should return values as string") unittest { auto result = new MessageResult("text"); result.addValue("value"); result.addText("text"); result.toString.should.equal(`textvaluetext`); } @("Message result should print a string as primary") unittest { auto result = new MessageResult("\t \r\n"); auto printer = new MockPrinter; result.print(printer); printer.buffer.should.equal(`[primary:¤ ←↲]`); } @("Message result should print values as info") unittest { auto result = new MessageResult("text"); result.addValue("value"); result.addText("text"); auto printer = new MockPrinter; result.print(printer); printer.buffer.should.equal(`[primary:text][info:value][primary:text]`); } class DiffResult : IResult { import ddmp.diff; protected { string expected; string actual; } this(string expected, string actual) { this.expected = expected.replace("\0", ResultGlyphs.nullChar); this.actual = actual.replace("\0", ResultGlyphs.nullChar); } private string getResult(const Diff d) { final switch(d.operation) { case Operation.DELETE: return ResultGlyphs.diffBegin ~ ResultGlyphs.diffDelete ~ d.text ~ ResultGlyphs.diffEnd; case Operation.INSERT: return ResultGlyphs.diffBegin ~ ResultGlyphs.diffInsert ~ d.text ~ ResultGlyphs.diffEnd; case Operation.EQUAL: return d.text; } } override string toString() @trusted { return "Diff:\n" ~ diff_main(expected, actual).map!(a => getResult(a)).join; } void print(ResultPrinter printer) @trusted { auto result = diff_main(expected, actual); printer.info("Diff:"); foreach(diff; result) { if(diff.operation == Operation.EQUAL) { printer.primary(diff.text); } if(diff.operation == Operation.INSERT) { printer.successReverse(diff.text); } if(diff.operation == Operation.DELETE) { printer.dangerReverse(diff.text); } } printer.primary("\n"); } } /// DiffResult should find the differences unittest { auto diff = new DiffResult("abc", "asc"); diff.toString.should.equal("Diff:\na[-b][+s]c"); } /// DiffResult should use the custom glyphs unittest { scope(exit) { ResultGlyphs.resetDefaults; } ResultGlyphs.diffBegin = "{"; ResultGlyphs.diffEnd = "}"; ResultGlyphs.diffInsert = "!"; ResultGlyphs.diffDelete = "?"; auto diff = new DiffResult("abc", "asc"); diff.toString.should.equal("Diff:\na{?b}{!s}c"); } class KeyResult(string key) : IResult { private immutable { string value; size_t indent; } this(string value, size_t indent = 10) { this.value = value.replace("\0", ResultGlyphs.nullChar); this.indent = indent; } bool hasValue() { return value != ""; } override string toString() { if(value == "") { return ""; } return rightJustify(key ~ ":", indent, ' ') ~ printableValue; } void print(ResultPrinter printer) { if(value == "") { return; } printer.info(rightJustify(key ~ ":", indent, ' ')); auto lines = value.split("\n"); auto spaces = rightJustify(":", indent, ' '); int index; foreach(line; lines) { if(index > 0) { printer.info(ResultGlyphs.newline); printer.primary("\n"); printer.info(spaces); } printLine(line, printer); index++; } } private { struct Message { bool isSpecial; string text; } void printLine(string line, ResultPrinter printer) { Message[] messages; auto whiteIntervals = line.getWhiteIntervals; foreach(size_t index, ch; line) { bool showSpaces = index < whiteIntervals.left || index >= whiteIntervals.right; auto special = isSpecial(ch, showSpaces); if(messages.length == 0 || messages[messages.length - 1].isSpecial != special) { messages ~= Message(special, ""); } messages[messages.length - 1].text ~= toVisible(ch, showSpaces); } foreach(message; messages) { if(message.isSpecial) { printer.info(message.text); } else { printer.primary(message.text); } } } bool isSpecial(T)(T ch, bool showSpaces) { if(ch == ' ' && showSpaces) { return true; } if(ch == '\r' || ch == '\t') { return true; } return false; } string toVisible(T)(T ch, bool showSpaces) { if(ch == ' ' && showSpaces) { return ResultGlyphs.space; } if(ch == '\r') { return ResultGlyphs.carriageReturn; } if(ch == '\t') { return ResultGlyphs.tab; } return ch.to!string; } pure string printableValue() { return value.split("\n").join("\\n\n" ~ rightJustify(":", indent, ' ')); } } } /// KeyResult should not dispaly spaces between words with special chars unittest { auto result = new KeyResult!"key"(" row1 row2 "); auto printer = new MockPrinter(); result.print(printer); printer.buffer.should.equal(`[info: key:][info:᛫][primary:row1 row2][info:᛫]`); } /// KeyResult should dispaly spaces with special chars on space lines unittest { auto result = new KeyResult!"key"(" "); auto printer = new MockPrinter(); result.print(printer); printer.buffer.should.equal(`[info: key:][info:᛫᛫᛫]`); } /// KeyResult should display no char for empty lines unittest { auto result = new KeyResult!"key"(""); auto printer = new MockPrinter(); result.print(printer); printer.buffer.should.equal(``); } /// KeyResult should display special characters with different contexts unittest { auto result = new KeyResult!"key"("row1\n \trow2"); auto printer = new MockPrinter(); result.print(printer); printer.buffer.should.equal(`[info: key:][primary:row1][info:↲][primary:` ~ "\n" ~ `][info: :][info:᛫¤][primary:row2]`); } /// KeyResult should display custom glyphs with different contexts unittest { scope(exit) { ResultGlyphs.resetDefaults; } ResultGlyphs.newline = `\n`; ResultGlyphs.tab = `\t`; ResultGlyphs.space = ` `; auto result = new KeyResult!"key"("row1\n \trow2"); auto printer = new MockPrinter(); result.print(printer); printer.buffer.should.equal(`[info: key:][primary:row1][info:\n][primary:` ~ "\n" ~ `][info: :][info: \t][primary:row2]`); } /// class ExpectedActualResult : IResult { protected { string title; KeyResult!"Expected" expected; KeyResult!"Actual" actual; } this(string title, string expected, string actual) nothrow @safe { this.title = title; this(expected, actual); } this(string expected, string actual) nothrow @safe { this.expected = new KeyResult!"Expected"(expected); this.actual = new KeyResult!"Actual"(actual); } override string toString() { auto line1 = expected.toString; auto line2 = actual.toString; string glue; string prefix; if(line1 != "" && line2 != "") { glue = "\n"; } if(line1 != "" || line2 != "") { prefix = title == "" ? "\n" : ("\n" ~ title ~ "\n"); } return prefix ~ line1 ~ glue ~ line2; } void print(ResultPrinter printer) { auto line1 = expected.toString; auto line2 = actual.toString; if(actual.hasValue || expected.hasValue) { printer.info(title == "" ? "\n" : ("\n" ~ title ~ "\n")); } expected.print(printer); if(actual.hasValue && expected.hasValue) { printer.primary("\n"); } actual.print(printer); } } @("ExpectedActual result should be empty when no data is provided") unittest { auto result = new ExpectedActualResult("", ""); result.toString.should.equal(""); } @("ExpectedActual result should be empty when null data is provided") unittest { auto result = new ExpectedActualResult(null, null); result.toString.should.equal(""); } @("ExpectedActual result should show one line of the expected and actual data") unittest { auto result = new ExpectedActualResult("data", "data"); result.toString.should.equal(` Expected:data Actual:data`); } @("ExpectedActual result should show one line of the expected and actual data") unittest { auto result = new ExpectedActualResult("data\ndata", "data\ndata"); result.toString.should.equal(` Expected:data\n :data Actual:data\n :data`); } /// A result that displays differences between ranges class ExtraMissingResult : IResult { protected { KeyResult!"Extra" extra; KeyResult!"Missing" missing; } this(string extra, string missing) { this.extra = new KeyResult!"Extra"(extra); this.missing = new KeyResult!"Missing"(missing); } override string toString() { auto line1 = extra.toString; auto line2 = missing.toString; string glue; string prefix; if(line1 != "" || line2 != "") { prefix = "\n"; } if(line1 != "" && line2 != "") { glue = "\n"; } return prefix ~ line1 ~ glue ~ line2; } void print(ResultPrinter printer) { if(extra.hasValue || missing.hasValue) { printer.primary("\n"); } extra.print(printer); if(extra.hasValue && missing.hasValue) { printer.primary("\n"); } missing.print(printer); } } string toString(const(Token)[] tokens) { string result; foreach(token; tokens.filter!(a => str(a.type) != "comment")) { if(str(token.type) == "whitespace" && token.text == "") { result ~= "\n"; } else { result ~= token.text == "" ? str(token.type) : token.text; } } return result; } auto getScope(const(Token)[] tokens, size_t line) nothrow { bool foundScope; bool foundAssert; size_t beginToken; size_t endToken = tokens.length; int paranthesisCount = 0; int scopeLevel; size_t[size_t] paranthesisLevels; foreach(i, token; tokens) { string type = str(token.type); if(type == "{") { paranthesisLevels[paranthesisCount] = i; paranthesisCount++; } if(type == "}") { paranthesisCount--; } if(line == token.line) { foundScope = true; } if(foundScope) { if(token.text == "should" || token.text == "Assert" || type == "assert" || type == ";") { foundAssert = true; scopeLevel = paranthesisCount; } if(type == "}" && paranthesisCount <= scopeLevel) { beginToken = paranthesisLevels[paranthesisCount]; endToken = i + 1; break; } } } return const Tuple!(size_t, "begin", size_t, "end")(beginToken, endToken); } /// Get the spec function and scope that contains a lambda unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto result = getScope(tokens, 101); auto identifierStart = getPreviousIdentifier(tokens, result.begin); tokens[identifierStart .. result.end].toString.strip.should.equal("it(\"should throw an exception if we request 2 android devices\", { ({ auto result = [ device1.idup, device2.idup ].filterBy(RunOptions(\"\", \"android\", 2)).array; }).should.throwException!DeviceException.withMessage.equal(\"You requested 2 `androdid` devices, but there is only 1 healthy.\"); }"); } /// Get the a method scope and signature unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/class.d"), tokens); auto result = getScope(tokens, 10); auto identifierStart = getPreviousIdentifier(tokens, result.begin); tokens[identifierStart .. result.end].toString.strip.should.equal("void bar() { assert(false); }"); } /// Get the a method scope without assert unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/class.d"), tokens); auto result = getScope(tokens, 14); auto identifierStart = getPreviousIdentifier(tokens, result.begin); tokens[identifierStart .. result.end].toString.strip.should.equal("void bar2() { enforce(false); }"); } size_t getFunctionEnd(const(Token)[] tokens, size_t start) { int paranthesisCount; size_t result = start; // iterate the parameters foreach(i, token; tokens[start .. $]) { string type = str(token.type); if(type == "(") { paranthesisCount++; } if(type == ")") { paranthesisCount--; } if(type == "{" && paranthesisCount == 0) { result = start + i; break; } if(type == ";" && paranthesisCount == 0) { return start + i; } } paranthesisCount = 0; // iterate the scope foreach(i, token; tokens[result .. $]) { string type = str(token.type); if(type == "{") { paranthesisCount++; } if(type == "}") { paranthesisCount--; if(paranthesisCount == 0) { result = result + i; break; } } } return result; } /// Get the end of a spec function with a lambda unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto result = getScope(tokens, 101); auto identifierStart = getPreviousIdentifier(tokens, result.begin); auto functionEnd = getFunctionEnd(tokens, identifierStart); tokens[identifierStart .. functionEnd].toString.strip.should.equal("it(\"should throw an exception if we request 2 android devices\", { ({ auto result = [ device1.idup, device2.idup ].filterBy(RunOptions(\"\", \"android\", 2)).array; }).should.throwException!DeviceException.withMessage.equal(\"You requested 2 `androdid` devices, but there is only 1 healthy.\"); })"); } /// Get the end of an unittest function with a lambda unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto result = getScope(tokens, 81); auto identifierStart = getPreviousIdentifier(tokens, result.begin); auto functionEnd = getFunctionEnd(tokens, identifierStart) + 1; tokens[identifierStart .. functionEnd].toString.strip.should.equal("unittest { ({ ({ }).should.beNull; }).should.throwException!TestException.msg; }"); } /// Get tokens from a scope that contains a lambda unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto result = getScope(tokens, 81); tokens[result.begin .. result.end].toString.strip.should.equal(`{ ({ ({ }).should.beNull; }).should.throwException!TestException.msg; }`); } size_t getPreviousIdentifier(const(Token)[] tokens, size_t startIndex) { enforce(startIndex > 0); enforce(startIndex < tokens.length); int paranthesisCount; bool foundIdentifier; foreach(i; 0..startIndex) { auto index = startIndex - i - 1; auto type = str(tokens[index].type); if(type == "(") { paranthesisCount--; } if(type == ")") { paranthesisCount++; } if(paranthesisCount < 0) { return getPreviousIdentifier(tokens, index - 1); } if(paranthesisCount != 0) { continue; } if(type == "unittest") { return index; } if(type == "{" || type == "}") { return index + 1; } if(type == ";") { return index + 1; } if(type == "=") { return index + 1; } if(type == ".") { foundIdentifier = false; } if(type == "identifier" && foundIdentifier) { foundIdentifier = true; continue; } if(foundIdentifier) { return index; } } return 0; } /// Get the the previous unittest identifier from a list of tokens unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto scopeResult = getScope(tokens, 81); auto result = getPreviousIdentifier(tokens, scopeResult.begin); tokens[result .. scopeResult.begin].toString.strip.should.equal(`unittest`); } /// Get the the previous paranthesis identifier from a list of tokens unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto scopeResult = getScope(tokens, 63); auto end = scopeResult.end - 11; auto result = getPreviousIdentifier(tokens, end); tokens[result .. end].toString.strip.should.equal(`(5, (11))`); } /// Get the the previous function call identifier from a list of tokens unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto scopeResult = getScope(tokens, 75); auto end = scopeResult.end - 11; auto result = getPreviousIdentifier(tokens, end); tokens[result .. end].toString.strip.should.equal(`found(4)`); } /// Get the the previous map!"" identifier from a list of tokens unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto scopeResult = getScope(tokens, 85); auto end = scopeResult.end - 12; auto result = getPreviousIdentifier(tokens, end); tokens[result .. end].toString.strip.should.equal(`[1, 2, 3].map!"a"`); } size_t getAssertIndex(const(Token)[] tokens, size_t startLine) { auto assertTokens = tokens .enumerate .filter!(a => a[1].text == "Assert") .filter!(a => a[1].line <= startLine) .array; if(assertTokens.length == 0) { return 0; } return assertTokens[assertTokens.length - 1].index; } /// Get the index of the Assert structure identifier from a list of tokens unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto result = getAssertIndex(tokens, 55); tokens[result .. result + 4].toString.strip.should.equal(`Assert.equal(`); } auto getParameter(const(Token)[] tokens, size_t startToken) { size_t paranthesisCount; foreach(i; startToken..tokens.length) { string type = str(tokens[i].type); if(type == "(" || type == "[") { paranthesisCount++; } if(type == ")" || type == "]") { if(paranthesisCount == 0) { return i; } paranthesisCount--; } if(paranthesisCount > 0) { continue; } if(type == ",") { return i; } } return 0; } /// Get the first parameter from a list of tokens unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto begin = getAssertIndex(tokens, 57) + 4; auto end = getParameter(tokens, begin); tokens[begin .. end].toString.strip.should.equal(`(5, (11))`); } /// Get the first list parameter from a list of tokens unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto begin = getAssertIndex(tokens, 89) + 4; auto end = getParameter(tokens, begin); tokens[begin .. end].toString.strip.should.equal(`[ new Value(1), new Value(2) ]`); } /// Get the previous array identifier from a list of tokens unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto scopeResult = getScope(tokens, 4); auto end = scopeResult.end - 13; auto result = getPreviousIdentifier(tokens, end); tokens[result .. end].toString.strip.should.equal(`[1, 2, 3]`); } /// Get the previous array of instances identifier from a list of tokens unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto scopeResult = getScope(tokens, 90); auto end = scopeResult.end - 16; auto result = getPreviousIdentifier(tokens, end); tokens[result .. end].toString.strip.should.equal(`[ new Value(1), new Value(2) ]`); } size_t getShouldIndex(const(Token)[] tokens, size_t startLine) { auto shouldTokens = tokens .enumerate .filter!(a => a[1].text == "should") .filter!(a => a[1].line <= startLine) .array; if(shouldTokens.length == 0) { return 0; } return shouldTokens[shouldTokens.length - 1].index; } /// Get the index of the should call unittest { const(Token)[] tokens = []; splitMultilinetokens(fileToDTokens("test/values.d"), tokens); auto result = getShouldIndex(tokens, 4); auto token = tokens[result]; token.line.should.equal(3); token.text.should.equal(`should`); str(token.type).text.should.equal(`identifier`); } /// An alternative to SourceResult that uses // DParse to get the source code class SourceResult : IResult { static private { const(Token)[][string] fileTokens; } immutable { string file; size_t line; } private const { Token[] tokens; } this(string fileName = __FILE__, size_t line = __LINE__, size_t range = 6) nothrow @trusted { this.file = fileName; this.line = line; if (!fileName.exists) { return; } try { updateFileTokens(fileName); auto result = getScope(fileTokens[fileName], line); auto begin = getPreviousIdentifier(fileTokens[fileName], result.begin); auto end = getFunctionEnd(fileTokens[fileName], begin) + 1; this.tokens = fileTokens[fileName][begin .. end]; } catch (Throwable t) { } } static void updateFileTokens(string fileName) { if(fileName !in fileTokens) { fileTokens[fileName] = []; splitMultilinetokens(fileToDTokens(fileName), fileTokens[fileName]); } } string getValue() { size_t startIndex = 0; size_t possibleStartIndex = 0; size_t endIndex = 0; size_t lastStartIndex = 0; size_t lastEndIndex = 0; int paranthesisCount = 0; size_t begin; size_t end = getShouldIndex(tokens, line); if(end != 0) { begin = tokens.getPreviousIdentifier(end - 1); return tokens[begin .. end - 1].toString.strip; } auto beginAssert = getAssertIndex(tokens, line); if(beginAssert > 0) { begin = beginAssert + 4; end = getParameter(tokens, begin); return tokens[begin .. end].toString.strip; } return ""; } override string toString() nothrow { auto separator = leftJustify("", 20, '-'); string result = "\n" ~ separator ~ "\n" ~ file ~ ":" ~ line.to!string ~ "\n" ~ separator; if(tokens.length == 0) { return result ~ "\n"; } size_t line = tokens[0].line - 1; size_t column = 1; bool afterErrorLine = false; foreach(token; this.tokens.filter!(token => token != tok!"whitespace")) { string prefix = ""; foreach(lineNumber; line..token.line) { if(lineNumber < this.line -1 || afterErrorLine) { prefix ~= "\n" ~ rightJustify((lineNumber+1).to!string, 6, ' ') ~ ": "; } else { prefix ~= "\n>" ~ rightJustify((lineNumber+1).to!string, 5, ' ') ~ ": "; } } if(token.line != line) { column = 1; } if(token.column > column) { prefix ~= ' '.repeat.take(token.column - column).array; } auto stringRepresentation = token.text == "" ? str(token.type) : token.text; auto lines = stringRepresentation.split("\n"); result ~= prefix ~ lines[0]; line = token.line; column = token.column + stringRepresentation.length; if(token.line >= this.line && str(token.type) == ";") { afterErrorLine = true; } } return result; } void print(ResultPrinter printer) { if(tokens.length == 0) { return; } printer.primary("\n"); printer.info(file ~ ":" ~ line.to!string); size_t line = tokens[0].line - 1; size_t column = 1; bool afterErrorLine = false; foreach(token; this.tokens.filter!(token => token != tok!"whitespace")) { foreach(lineNumber; line..token.line) { printer.primary("\n"); if(lineNumber < this.line -1 || afterErrorLine) { printer.primary(rightJustify((lineNumber+1).to!string, 6, ' ') ~ ":"); } else { printer.dangerReverse(">" ~ rightJustify((lineNumber+1).to!string, 5, ' ') ~ ":"); } } if(token.line != line) { column = 1; } if(token.column > column) { printer.primary(' '.repeat.take(token.column - column).array); } auto stringRepresentation = token.text == "" ? str(token.type) : token.text; if(token.text == "" && str(token.type) != "whitespace") { printer.info(str(token.type)); } else if(str(token.type).indexOf("Literal") != -1) { printer.success(token.text); } else { printer.primary(token.text); } line = token.line; column = token.column + stringRepresentation.length; if(token.line >= this.line && str(token.type) == ";") { afterErrorLine = true; } } printer.primary("\n"); } } @("TestException should read the code from the file") unittest { auto result = new SourceResult("test/values.d", 26); auto msg = result.toString; msg.should.equal("\n--------------------\ntest/values.d:26\n--------------------\n" ~ " 23: unittest {\n" ~ " 24: /++/\n" ~ " 25: \n" ~ "> 26: [1, 2, 3]\n" ~ "> 27: .should\n" ~ "> 28: .contain(4);\n" ~ " 29: }"); } @("TestException should print the lines before multiline tokens") unittest { auto result = new SourceResult("test/values.d", 45); auto msg = result.toString; msg.should.equal("\n--------------------\ntest/values.d:45\n--------------------\n" ~ " 40: unittest {\n" ~ " 41: /*\n" ~ " 42: Multi line comment\n" ~ " 43: */\n" ~ " 44: \n" ~ "> 45: `multi\n" ~ "> 46: line\n" ~ "> 47: string`\n" ~ "> 48: .should\n" ~ "> 49: .contain(`multi\n" ~ "> 50: line\n" ~ "> 51: string`);\n" ~ " 52: }"); } /// Converts a file to D tokens provided by libDParse. /// All the whitespaces are ignored const(Token)[] fileToDTokens(string fileName) nothrow @trusted { try { auto f = File(fileName); immutable auto fileSize = f.size(); ubyte[] fileBytes = new ubyte[](fileSize.to!size_t); if(f.rawRead(fileBytes).length != fileSize) { return []; } StringCache cache = StringCache(StringCache.defaultBucketCount); LexerConfig config; config.stringBehavior = StringBehavior.source; config.fileName = fileName; config.commentBehavior = CommentBehavior.intern; auto lexer = DLexer(fileBytes, config, &cache); const(Token)[] tokens = lexer.array; return tokens.map!(token => const Token(token.type, token.text.idup, token.line, token.column, token.index)).array; } catch(Throwable) { return []; } } @("TestException should ignore missing files") unittest { auto result = new SourceResult("test/missing.txt", 10); auto msg = result.toString; msg.should.equal("\n" ~ `-------------------- test/missing.txt:10 --------------------` ~ "\n"); } @("Source reporter should find the tested value on scope start") unittest { auto result = new SourceResult("test/values.d", 4); result.getValue.should.equal("[1, 2, 3]"); } @("Source reporter should find the tested value after a statment") unittest { auto result = new SourceResult("test/values.d", 12); result.getValue.should.equal("[1, 2, 3]"); } @("Source reporter should find the tested value after a */ comment") unittest { auto result = new SourceResult("test/values.d", 20); result.getValue.should.equal("[1, 2, 3]"); } @("Source reporter should find the tested value after a +/ comment") unittest { auto result = new SourceResult("test/values.d", 28); result.getValue.should.equal("[1, 2, 3]"); } @("Source reporter should find the tested value after a // comment") unittest { auto result = new SourceResult("test/values.d", 36); result.getValue.should.equal("[1, 2, 3]"); } @("Source reporter should find the tested value from an assert utility") unittest { auto result = new SourceResult("test/values.d", 55); result.getValue.should.equal("5"); result = new SourceResult("test/values.d", 56); result.getValue.should.equal("(5+1)"); result = new SourceResult("test/values.d", 57); result.getValue.should.equal("(5, (11))"); } @("Source reporter should get the value from multiple should asserts") unittest { auto result = new SourceResult("test/values.d", 61); result.getValue.should.equal("5"); result = new SourceResult("test/values.d", 62); result.getValue.should.equal("(5+1)"); result = new SourceResult("test/values.d", 63); result.getValue.should.equal("(5, (11))"); } @("Source reporter should get the value after a scope") unittest { auto result = new SourceResult("test/values.d", 71); result.getValue.should.equal("found"); } @("Source reporter should get a function call value") unittest { auto result = new SourceResult("test/values.d", 75); result.getValue.should.equal("found(4)"); } @("Source reporter should parse nested lambdas") unittest { auto result = new SourceResult("test/values.d", 81); result.getValue.should.equal("({ ({ }).should.beNull; })"); } /// Source reporter should print the source code unittest { auto result = new SourceResult("test/values.d", 36); auto printer = new MockPrinter(); result.print(printer); auto lines = printer.buffer.split("[primary:\n]"); lines[1].should.equal(`[info:test/values.d:36]`); lines[2].should.equal(`[primary: 31:][info:unittest][primary: ][info:{]`); lines[7].should.equal(`[dangerReverse:> 36:][primary: ][info:.][primary:contain][info:(][success:4][info:)][info:;]`); } /// split multiline tokens in multiple single line tokens with the same type void splitMultilinetokens(const(Token)[] tokens, ref const(Token)[] result) nothrow @trusted { try { foreach(token; tokens) { auto pieces = token.text.idup.split("\n"); if(pieces.length <= 1) { result ~= const Token(token.type, token.text.dup, token.line, token.column, token.index); } else { size_t line = token.line; size_t column = token.column; foreach(textPiece; pieces) { result ~= const Token(token.type, textPiece, line, column, token.index); line++; column = 1; } } } } catch(Throwable) {} } /// A new line sepparator class SeparatorResult : IResult { override string toString() { return "\n"; } void print(ResultPrinter printer) { printer.primary("\n"); } } class ListInfoResult : IResult { private { struct Item { string singular; string plural; string[] valueList; string key() { return valueList.length > 1 ? plural : singular; } MessageResult toMessage(size_t indentation = 0) { auto printableKey = rightJustify(key ~ ":", indentation, ' '); auto result = new MessageResult(printableKey); string glue; foreach(value; valueList) { result.addText(glue); result.addValue(value); glue = ","; } return result; } } Item[] items; } void add(string key, string value) { items ~= Item(key, "", [value]); } void add(string singular, string plural, string[] valueList) { items ~= Item(singular, plural, valueList); } private size_t indentation() { auto elements = items.filter!"a.valueList.length > 0"; if(elements.empty) { return 0; } return elements.map!"a.key".map!"a.length".maxElement + 2; } override string toString() { auto indent = indentation; auto elements = items.filter!"a.valueList.length > 0"; if(elements.empty) { return ""; } return "\n" ~ elements.map!(a => a.toMessage(indent)).map!"a.toString".join("\n"); } void print(ResultPrinter printer) { auto indent = indentation; auto elements = items.filter!"a.valueList.length > 0"; if(elements.empty) { return; } foreach(item; elements) { printer.primary("\n"); item.toMessage(indent).print(printer); } } } /// convert to string the added data to ListInfoResult unittest { auto result = new ListInfoResult(); result.add("a", "1"); result.add("ab", "2"); result.add("abc", "3"); result.toString.should.equal(` a:1 ab:2 abc:3`); } /// print the added data to ListInfoResult unittest { auto printer = new MockPrinter(); auto result = new ListInfoResult(); result.add("a", "1"); result.add("ab", "2"); result.add("abc", "3"); result.print(printer); printer.buffer.should.equal(`[primary: ][primary: a:][primary:][info:1][primary: ][primary: ab:][primary:][info:2][primary: ][primary: abc:][primary:][info:3]`); } /// convert to string the added data lists to ListInfoResult unittest { auto result = new ListInfoResult(); result.add("a", "as", ["1", "2","3"]); result.add("ab", "abs", ["2", "3"]); result.add("abc", "abcs", ["3"]); result.add("abcd", "abcds", []); result.toString.should.equal(` as:1,2,3 abs:2,3 abc:3`); } IResult[] toResults(Exception e) nothrow @trusted { try { return [ new MessageResult(e.message.to!string) ]; } catch(Exception) { return [ new MessageResult("Unknown error!") ]; } }