aboutsummaryrefslogtreecommitdiff
path: root/doc/testscript.cli
blob: 4708745af7cd2b2a543c972ea25060742b4f579b (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
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
// file      : doc/testscript.cli
// copyright : Copyright (c) 2014-2016 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

"\name=build2-testscript-language"
"\subject=Testscript language"
"\title=Testscript Language"

// NOTES
//
// - Maximum <pre> line is 70 characters.
//

// @@ Testscript vs testscript
//

"
\h0#preface|Preface|

This document describes the \c{build2} Testscript language. It begins with an
introduction that discusses the motivation for having a separate
domain-specific language and then introduces a number of Testscript concepts
with examples. The remainder of the document provides a more formal
specification of the language, including its integration into the build
system, parsing and execution model, lexical structure, as well as grammar and
semantics. The final chapter describes the Testscript style used in the
\c{build2} project.

In this document we use the term \i{Testscript} (capitalized) to refer to the
Testscript language. Just \i{testscript} means some code written in this
language. For example: \"We can pass addition information to testscripts using
target-specific variables.\" Finally, \c{testscript} refers to the file name.

We also use the equivalent distinction between \i{Buildfile} (language),
\i{buildfile} (code), and \c{buildfile} (file).

\h1#intro|Introduction|

The \c{build2} \c{test} module provides the ability to run an executable
target as a test, optionally passing options and arguments, providing
\c{stdin} input, as well as comparing the \c{stdout} output to the expected
result. For example:

\
exe{xml-parser}: test.options = --validate
exe{xml-parser}: test.input   = test.xml
exe{xml-parser}: test.output  = test.out
\

This works well for simple, single-run tests. If, however, your testing
requires multiple runs with varying input and/or analyzing output,
traditionally, you would resort to use a scripting language, for instance
Bash. This has a number of drawbacks. Firstly, this approach is usually not
portable (there is no Bash on Windows \i{out of the box}). It is also hard to
write concise tests in a general-purpose scripting language. The result is
often a test suite that has grown incomprehensible with everyone dreading
adding new tests. Finally, it is hard to run such tests in parallel without a
major effort (for example, by having a separate script for each test and
having some kind of \i{test driver}).

Testscript is a domain-specific language for running tests. It vaguely
resembles Bash and is optimized for concise test description by focusing on
the following functionality:

\ul|

\li|Supplying input via command line and \c{stdin}.|

\li|Comparing to expected exit status.|

\li|Comparing to expected output for \c{stdout}/\c{stderr}, including
    using regex.|

\li|Setup/teardown commands and automatic file/directory cleanups.|

\li|Simple (single-command) and compound (multi-command) tests.|

\li|Test groups with common setup/teardown.|

\li|Test isolation for parallel execution.|

\li|Portable POSIX-like builtins subset.|

\li|Test documentation.||

Note that Testscript is a \i{test runner}, not a testing framework for a
particular programming language. It does not concern itself with how the test
executables themselves are implemented. As a result, it is mostly geared
towards functional testing but can also be used for unit testing if external
input/output is required. Testscript is an extension of the \c{build2} build
system and is implemented by its \c{test} module.

As a quick introduction to Testscript's capabilities, let's test a \"Hello,
World\" program. For a simple implementation the corresponding \c{buildfile}
might look like this:

\
exe{hello}: cxx{hello}
\

We also assume that the project's \c{bootstrap.build} loads the \c{test}
module which implements the execution of testscripts.

To start, we create an empty file called \c{testscript}. To indicate that a
testscript file tests a specific target we simply list it as a target's
prerequisite, for example:

\
exe{hello}: cxx{hello} test{testscript}
\

Let's assume our \c{hello} program expects us to pass the name to greet on the
command line. And if we don't pass anything, it prints an error following by
usage and terminates with a non-zero exit status. We can test this failure
case by adding the following line to the \c{testscript} file:

\
$* 2>- != 0
\

While it sure is concise, it may look cryptic without some explanation. When
the \c{test} module runs tests, it (by default) passes to each testscript the
target path of which this testscript is a prerequisite. So in our case the
testscript will receive the path to our \c{hello} executable. The buildfile
can also pass along additional options and arguments. Inside the testscript,
all of this (target path, options, and arguments) are bound to the \c{$*}
variable. So in our case, if we expand the above line, it will be something
like this:

\
/tmp/hello/hello 2>- != 0
\

Or, if we are on Windows, something like this:

\
C:\projects\hello\hello.exe 2>- != 0
\

The \c{2>-} redirect is the Testscript equivalent of \c{2>/dev/null} that is
both portable and more concise (\c{2} here is the \c{stderr} file
descriptor). If we don't specify it and our program prints anything to
\c{stderr}, then the test will fail (unexpected output).

The remainder of the command (\c{!= 0}) is the exit status check. If we don't
specify it, then the test is expected to exit with zero status (which is
equivalent to specifying \c{== 0}).

If we run our test, it will pass provided our program behaves as expected.
One thing our test doesn't verify, however, is the diagnostics that gets
printed to \c{stderr} (remember, we ignored it with \c{2>-}). Let's fix that
assuming this is the code that prints it:

\
cerr << \"error: missing name\" << endl
     << \"usage: \" << argv[0] << \" <name>\" << endl;
\

In testscripts you can compare output to the expected result for both
\c{stdout} and \c{stderr}. We can supply the expected result as either
\i{here-string} or \i{here-document} both which can be either literal or
regex. The here-string approach works best for short, single-line output and
we will use it for another test in a minute. For this test let's use
here-document since the expected diagnostics has two lines:

\
$* 2>>EOE != 0
error: missing name
usage: hello <name>
EOE
\

Let's decrypt this: the \c{2>>EOE} is a here-document redirect with \c{EOE}
(stands for End-Of-Error) being the string we chose to mark the end of
here-document. Next comes the here-document fragment followed by the end
marker.

Now when executing this test the \c{test} module will check two things: it
will compare the \c{stderr} output to the expected result using the \c{diff}
tool and it will make sure the test exits with a non-zero status. Let's give
it a go:

\
$ b test
testscript:1:1: error: stderr doesn't match expected output
  info: produced stderr: test-hello/1/stderr
  info: expected stderr: test-hello/1/stderr.orig
  info: stderr diff (test-hello/1/stderr.diff):

--- test-hello/1/stderr.orig
+++ test-hello/1/stderr
@@ -1,2 +1,2 @@
 error: missing name
-usage: hello <name>
+usage: /tmp/hello/hello <name>
\

While not what we expected, at least the problem is clear: the program name
varies at runtime so we cannot just hardcode \c{hello} in our expected output.
How do we solve this? The best fix would be to use the actual path to the
target; after all, we know it's the first element in \c{$*}:

\
$* 2>>\"EOE\" != 0
error: missing name
usage: $0 <name>
EOE
\

You can probably guess what \c{$0} expands to. But did you notice another
change? Yes, those double quotes in \c{2>>\"EOE\"}. Here is what's going on:
similar to Bash, single-quoted strings (\c{'foo'}) are taken literaly while
double-quoted ones (\c{\"foo\"}) have variable expansion, escaping, etc. This
semantics is extended to here-documents in a curious way: if the end marker is
single-quoted then the here-document lines are taken literally and if it is
double-quoted, then there can be variable expansions, etc.  An unquoted end
marker is treated as single-quoted (note that this is unlike Bash where
here-documents always have variable expanion).

This example illustrated a fairly common testing problem: output variability.
In this case we could fix it perfectly since we could calculate the varying
parts exactly. But often figuring out the varying part is difficult of
outright impossible. A good example would be a system error message based
on the \c{errno} code, such as file not found. Different targets can phrase
the message slightly differently, or, worse, it can be a slightly different
error code, for example \c{ENOENT} vs \c{ENOTDIR}.

To handle output variability, Testscript allows us to specify the expected
output as regular expressions. For example, this is an alternative fix to our
usage problem that simply ignores the program name:

\
$* 2>>~/EOE/ != 0
error: missing name
/usage: .+ <name>/
EOE
\

To use a regex here-string or here-document we use the \c{~} redirect
modifier. In this case the here-document end marker must start and end with
the regex introducer character of your choice (\c{/} in our case). Any line
inside the here-document fragment that begins with this introducer is then
treated as a regular expression rather than a literal (@@ ref to regex).

Now that we have tested the failure case, let's test the normal functionality.
While we could have used here-document, in this case here-string will be more
concise:

\
$* 'World' >'Hello, World!'
\

It's a good idea to document our tests. Testscript has a formalized test
description that can capture the test \i{id}, \i{summary}, and
\i{details}. All three components are optional and how thoroughly you document
your tests is up to you.

The description lines precede the test command. They start with a colon
(\c{:}), and have the following layout:

\
: <id>
: <summary>
:
: <details>
: ...
\

The recommended format for \c{<id>} is \c{<keyword>-<keyword>...} with at
least two keywords. The id is used in diagnostics as well as to run individual
tests. The recommended style for \c{<summary>} is that of the \c{git(1)}
commit summary. The detailed description is free-form. Here are some
examples (\c{#} starts a comment):

\
# Only id.
#
: missing-name
$* 2>>\"EOE\" != 0
...

# Only summary.
#
: Test handling of missing name
...

# Both id and summary.
#
: missing-name
: Test handling of missing name
...

# All three: id, summary, and a detailed description.
#
: missing-name
: Test handling of missing name
:
: This test makes sure the program detects that the name to greet
: was not specified on the command line and both prints usage and
: exits with non-zero status.
...
\

The recommended way to come up with an id is to distill the summary to its
essential keywords by removing generic words like \"test\", \"handle\", and so
on. If you do this, then both the id and summary will convey essentially the
same information. As a result, to keep things concise, you may choose to drop
the summary and only have the id. This is what we often do in \c{build2}.
Note that if the id is not provided, the it will be automatically derived
from the line number in testscript.

Either the id or summary (but not both) can alternatively be specified inline
in the test command after a colon (\c{:}), for example:

\
$* 'World' >'Hello, World!' : command-name
\

Similar to handling output, Testscript provides a convenient way to supply
input to test's \c{stdin}. Let's say our \c{hello} program recognizes the
special \c{-} name as an instruction to read the names from \c{stdin}. This
is how we could test this functionality:

\
$* - <<EOI >>EOO : stdin-names
Jane
John
EOI
Hello, Jane!
Hello, John!
EOO
\

As you might suspect, we can also use here-string to supply \c{stdin}, for
example:

\
$* - <'World' >'Hello, World!' : stdin-name
\

Let's say our \c{hello} program has a configuration file that captures custom
name-to-greeting mappings. A path to this file can be passed as a second
command line argument. To test this functionality we first need to create a
sample configuration file. We do these non-test actions with \i{setup} and
\i{teardown} commands, for example:

\
+cat <<EOI >>>hello.conf;
John = Howdy
Jane = Good day
EOI
$* 'Jane' hello.conf >'Good day, Jane!' : config-greet
\

The setup commands start with the plus sign (\c{+}) while teardown \- with
minus (\c{-}). Notice also the semicolon (\c{;}) at the end of the setup
command: it indicates that the following command is part of the same test \-
what we call a multi-command or \i{compound} test.

Other than that it should all look familiar. You may be wondering why we don't
have a teardown command that removes \c{hello.conf}? It is not necessary
because this file will be automatically registered for cleanup that
happens at the end of the test. We can also register our own files and
directories for automatic cleanup. For example, if the \c{hello} program
created the \c{hello.log} file on unsuccessful runs, then here is how we could
have cleaned it up:

\
$* &hello.log != 0
\

What if we wanted to run two tests for this configuration file functionality?
For example, we may want to test the custom greeting as above but also make
sure the default greeting is not affected. One way to do this would be to
repeat the setup command in each test. But there is a better way to do it:
testscripts can define test groups. For example:

\
: config
{
  conf = $~/hello.conf

  +cat <<EOI >>>$conf
  John = Howdy
  Jane = Good day
  EOI

  $* 'John' $conf >'Howdy, John!' : custom-greet
  $* 'Jack' $conf >'Hello, Jack!' : default-greet
}
\

A test group is a scope that contains several test/setup/teardown commands.
Variables set inside a scope (like our \c{conf}) are only in effect until the
end of the scope. Plus, setup and teardown commands that are not part of any
test (notice the lack of \c{;} after \c{+cat}) are associated with the scope;
their automatic cleanup only happens at the end of the scope (so our
\c{hello.conf} will only be removed after all the tests in the group have
completed). Note also that a scope can have a description. In particular,
assigning a test group an id allows us to run tests only from this specific
group.

Other than that the two other things we need to discuss in this example are
\c{$~} and \c{cat}. The \c{$~} variable is easy: it stands for the test/group
working directory.

But what is \c{cat} exactly? While most POSIX systems will have a program with
this name, there is no such thing in vanilla Windows. To help with this
Testscript provides a subset (both in terms of the number and supported
features) of POSIX utilities, such as, \c{echo}, \c{touch}, \c{cat},
\c{mkdir}, \c{rm}, and so on (@@ ref builtins).

Besides explicit group scopes each test is automatically placed in its own
implicit test scope. However, we can make the test scope explicit, for
example, for better visual separation of complex tests:

\
: config-greet
{
  conf = hello.conf

  +cat <'Jane = Good day' >>>$conf;
  $* 'Jane' $conf >'Good day, Jane!'
}
\

We can conditionally exclude sections of testscripts using \c{if-else}
branching. This can be done both at the scope level to exclude test or
group scopes as well as at the command level to exclude individual
commands or variable assignments. Let's start with a scope example by
providing a Windows-specific implementation of a test:

\
: config-empty
:
if ($cxx.target.class != windows)
{
  $* 'Jane' /dev/null >'Hello, Jane!'
}
else
{
  $* 'Jane' nul >'Hello, Jane!'
}
\

Note the \c{if-else} chain is treated as variants of the same test thus
the single description at the beginning.

Let's now see an example of command-level \c{if-else} by reimplementing
the above as a single test with some branching and without using the
\c{nul} device on Windows (notice the semicolon after \c{end}):

\
: config-empty
:
if ($cxx.target.class != windows)
  conf = /dev/null
else
  conf = empty
  touch $conf
end;
$* 'Jane' $conf >'Hello, Jane!'
\

You may have noticed that in the above examples we referenced the
\c{cxx.target.class} variable as if we were in a buildfile. We could do that
because the testscript variable lookup continues in the buildfile starting
from the testscript target and continuing with the standard buildfile variable
lookup. In particular, this means we can pass arbitrary information to
testscripts using target-specific variables. For example, this how we can move
the above platform test to \c{buildfile}:

\
# buildfile

exe{hello}: cxx{hello} test{testscript}

test{*}: windows = ($cxx.target.class == windows)
\

\
# testscript

if! $windows
  conf = /dev/null
else
  ...
\

Note also that in cases when you simply need to conditionally pick a value for
a variable, the \c{build2} evaluation contex will often be more concise than
\c{if-else}. For example:

\
: config-empty
:
conf = ($windows ? nul : /dev/null);
$* 'Jane' $conf >'Hello, Jane!'
\

Similar to Bash, test commands can be chained with pipes (\c{|}) and combined
with logical operators (\c{||} and \c{&&}). Let's say our \c{hello} program
provides the \c{-o} option to write the result to a file instead of
\c{stdout}. Here is how we could test it:

\
$* -o hello.out - <<EOI &hello.out && cat hello.out >>EOO
John
Jane
EOI
Hello, John!
Hello, Jane!
EOO
\

Similarly, if it has the \c{-r} option to reverse the greetings back to
their names (as every \c{hello} program should), then we could write a
test like this:

\
$* - <<EOI | $* -d - >>EOO
John
Jane
EOI
John
Jane
EOO
\

To conclude, let's put all our (sensible) tests together so that we can have a
complete picure:

\
$* 'World' >'Hello, World!' : command-name

$* 'Jonh' 'Jane' >EOO       : command-names
Hello, Jane!
Hello, John!
EOO

$* - <<EOI >>EOO            : stdin-names
Jane
John
EOI
Hello, Jane!
Hello, John!
EOO

: config
{
  conf = $~/hello.conf

  +cat <<EOI >>>$conf
  John = Howdy
  Jane = Good day
  EOI

  $* 'John' $conf >'Howdy, John!' : custom-greet
  $* 'Jack' $conf >'Hello, Jack!' : default-greet
}

$* 2>>\"EOE\" != 0            : missing-name
error: missing name
usage: $0 <name>
EOE
\

The execution of these tests happens in parallel. Testscript will start
running all script-level tests as well as the \c{config} group immediately.
Inside \c{config}, once the setup command (\c{cat}) is performed, the two
inner tests are executed in parallel as well.

@@ temp directory structure (why ../)? term: 'test working directory'


\h1#integration|Build System Integration|

The integration of testscripts into buildfiles is done using the standard
\i{target-prerequisite} mechanism. In this sense, a testscript is a
prerequisite that describes how to test the target similar to how, for
example, the \c{INSTALL} file describes how to install it. For example:

\
exe{hello}: test{testscript} doc{INSTALL README}
\

By convention the testscript file should be either called \c{testscript} if
you only have one or have the \c{.test} extension, for example,
\c{basics.test}. The \c{test} module registers the \c{test{\}} target type
for testscript files.

A testscript prerequisite can be specified for any target. For example, if
our directory contains a bunch of shell scripts that we want to test together,
then it makes sense to specify the testscript prerequisite for the directory
target:

\
./: test{basics}
\

During variable lookup if a variable is not found in a testscript, then its
search continues in the buildfile starting with the target-specific variables
of the target being tested (e.g., \c{exe{hello\}}; called \i{test target}),
then target-specific variables of the the testscript target (e.g.,
\c{test{basics\}}; called \i{script target}), and the continuing with the
scopes starting from the one containing the testscript target. This means a
testscript can \"see\" all the existing buildfile variables plus we can use
target-specific variables to pass additional information to testscrips, for
example:

\
# basics.test

if ($cxx.target.class == windows)
  test.arguments += $foo
end

if $windows
  test.arguments += $bar
end
\

\
# buildfile

exe{hello}: test{basics}

# All testscripts in this scope.
#
test{*}: windows = ($cxx.target.class == windows)

# All testscripts for target exe{hello}.
#
exe{hello}: bar = BAR

# Only basics.test.
#
test{basics}@./: foo = FOO
\

Additionally, a number of \c{test.*} variables are used by convention to pass
commonly required information to testscripts. Unless set manually as a test or
script target-specific variable, the \c{test} variable is automatically set to
the target path being tested. For example, given this \c{buildfile}:

\
exe{hello}: test{testscript}
\

The value of \c{test} inside the testscript will be the absolute path to the
\c{hello} executable.

If the \c{test} variable is set manually to a name of a target, then it is
automatically converted to the target path. This can be usefult when testing
a program that is built in another subdirectory of a project. For example,
our \c{hello} may reside in the \c{hello/} subdirectory while we may want
to keep the tests in \c{tests/}:

\
hello/
├── hello/
│   └── hello*
└── tests/
    ├── buildfile
    └── testscript
\

This is how we can implement \c{tests/buildfile} for this setup:

\
hello = ../hello/exe{hello}

./: $hello test{testscript}
./: test = $hello

include ../hello/
\

The other \c{test.} variables are \c{test.options}, \c{test.arguments},
\c{test.redirects}, and \c{test.cleanups}. You can use them to pass additional
command line options, arguments, redirects, and cleanups to your test scripts
and together with \c{test} they form the test target command line which,
for conciseness, is bound to the following read-only variable aliases:

\
$* - $test $test.options $test.arguments $test.redirects $test.cleanups
$0 - $test
$N - (N-1)-th element in the {$test.options $test.arguments} array
\

Note that these aliases are read-only; if you need to modify any of these
values from within testscripts, then you should use the original variable
names, for example:

\
test.options += --foo

$* bar # Includes --foo.
\

Note also that the \c{test.} variables only establish a convention. You
could also put everything into, say \c{test.arguments}, and it will still
work as expected.

A testscript would normally contain multiple tests and sometimes it is
desirable to only run a specific test or a group of tests. For example, you
may be debugging a failing tests and would like to re-run it. Each test and
group in a testscript has an id. As a result each test has an \i{id path} that
uniquely identifies it. The id path starts with the testscript file name
(corresponds to the id of the implied outermost group, as described below),
may include a number of intermediate group ids, and ends with the test id. The
ids in a path are separated with a forward slash (\c{/}). Note that this also
happens to be the filesystem path to the temporary directory where the test is
executed (again, as discussed below). As an example, consider the following
testscript file called \c{basics.test}:

\
$* foo : foo

: fox
{
  $* fox bar : bar
  $* fox baz : baz
}
\

The id paths for the three test will then be:

\
basics/foo
basics/fox/bar
basics/fox/baz
\

To only run individual tests, test groups, or testscript files we can specify
their id paths in the \c{config.test} variable, for example:

\
$ b test config.test=basics     # Run all tests in basics.test.
$ b test config.test=basics/fox # Run bar and baz.
$ b test config.test=basics/foo # Run foo.
$ b test \"config.test=basics/foo basics/fox/bar\" # Run fox and bar.
\

@@ Maybe test.id instead of config.test?

@@ What about running from root, with multiple basics.test?

\h1#lexical|Lexical Structure|

Testscript is a line-oriented language with a context-dependent lexical
structure. It \"borrows\" several building blocks (for example, variable
expansion) from the Buildfile language. In a sense, testscripts are
specialized (for testing) continuations of buildfiles.

Except in here-document fragments, leading whitespaces and blank lines are
ignored except for the line/column counts. A non-empty testscript must
end with a newline.

The backslash (\c{\\}) character followed by a newline signals the line
continuation. Both this character and the newline are removed (note: not
replaced with a whitespace) and the following line is read as if it was part
of the first line. Note that \c{'\\'} followed by EOF is invalid. For example:

\
$* foo | \
$* bar
\

An unquoted and unescaped \c{'#'} character starts a comments; everything from
this character until the end of line is ignored. For example:

\
# Setup foo.
$* foo

$* bar # Setup bar.
\

Note that there is no line continuation in comments; the trailing \c{'\\'} is
ignored except in one case: if the comment is just \c{'#\\'} followed by the
newline, then it starts a multi-line comment that spans until the closing
\c{'#\\'} comment is encountered. For example:

\
#\
$* foo
$* bar
#\
\

Similar to Buildfile, the Testscript language supports two types of quoting:
single (\c{'}) and double (\c{\"}). Both can span multiple lines.

The single-quoted string does not recognize any escape sequences (not even for
the single quote itself or line continuations) with all the characters taken
literally until the closing single quote is encountered.

The double-quoted string recognizes escape sequences (including line
continuations) as well as expansions of variables and evaluations of contexts.
For example:

\
foo = FOO
bar = \"$foo ($foo == FOO)\" # 'FOO true'
\

Characters that have special syntactic meaning (for example \c{'$'}) can be
escaped with a backslash (\c{\\}) to preserve their literal meaning (to
specify literal backslash you need to escape it as well). For example:

\
foo = \$foo\\bar # '$foo\bar'
\

Note that quoting could often be a more readable way to achieve the same
result, for example:

\
foo = '$foo\bar'
\

Inside double-quoted strings only the \c{\"\\$(} character set needs to be
escaped.

A character is said to be \i{unquoted} and \i{unescaped} if it is not escaped
and is not part of a quoted string. A token is said to be unquoted and
unescaped if all its characters are unquoted and unescaped.

The lexical structure of the remainder of a line (that is, the \i{context}) is
determined by the leading (unquoted and unescaped) character after ignoring
any (unquoted and unescaped) leading whitespaces. The following characters are
context-introducing.

\
':'  - description line
'.'  - directive line
'{'  - block start
'}'  - block end
'+'  - setup command line
'-'  - teardown command line
\

For the here-document lines the context is implied by the preceding line. If
none of the above determinants apply, then the line is either a variable
assignment or a test command line. Distinguishing between the two is performed
during parsing and is described below.


\h1#grammar|Grammar and Semantics|

\h#grammar-notation|Notation|

The formal grammar of the Testscript language is specified using an EBNF-like
notation with the following elements:

\
foo: ...   - production rule
foo        - non-terminal
<foo>      - terminal
'foo'      - literal
foo*       - zero or more multiplier
foo+       - one or more multiplier
foo?       - zero or one multiplier
foo bar    - concatenation (foo then bar)
foo | bar  - alternation   (foo or bar)
(foo bar)  - grouping
{foo bar}  - grouping in any order (foo then bar or bar then foo)
foo \
bar        - line continuation
# foo      - comment
\

Rule right-hand-sides that start on a new line describe the line-level syntax
and ones that start on the same line describes the syntax inside the line. If
a multiplier appears in from on the line then it specifies the number of
repetitions for the whole line. For example, from the following three rules,
the first describes a single line of multiple literals (such as
\c{'foofoofoo'}), the second \- multiple lines of a single literal (such as
\c{'foo\\nfoo\\nfoo'}), and the third \- multiple lines of multiple literals
(such as \c{'foo\\nfoofoo\\nfoofoofoo'}).

\
text-line: 'foo'+

text-lines:
  +'foo'

text-lines:
  +('foo'+)
\

A newline in the grammar matches any standard newline separator sequence
(CR/LF combinations). An unquoted space in the grammar matches zero or more
non-newline whitespaces (spaces and tabs). A quoted space matches exactly one
non-newline whitespace. Note also that in some cases components within lines
may not be whitespace-separated in which case they will be written without any
spaces between them, for example:

\
foo: 'foo' ';'    # \"foo;\" or \"foo ;\" or \"foo      ;\"
bar: 'bar'';'     # \"bar;\"
baz: 'baz'' '+';' # \"baz ;\" or \"baz      ;\"

fox: bar''bar     # \"bar;bar;\"
\

You may also notice that several production rules below end with \c{-line}
while potentially spanning several physical lines. In such cases they
represent \i{logical lines}, for example, a test, its description, and its
here-document fragments.

\h#grammar-all|Grammar|

\
script:
  scope-body

scope-body:
  *setup
  *(directive|scope|test)
  *tdown

directive:
  include

include: '.include' (' '+'--once')*(' '+<path>)*

scope:
  ?description
  scope-block|scope-if

scope-block:
  '{'
  scope-body
  '}'

scope-if: ('if'|'if!') command-line
  scope-block
  *scope-elif
  ?scope-else

scope-elif: ('elif'|'elif!') command-line
  scope-block

scope-else: 'else'
  scope-block

description:
  +(':' <text>)

setup:
  variable-like|setup-line

tdown:
  variable-like|tdown-line

setup-line: '+' command-like
tdown-line: '-' command-like

test:
  ?description
  +(variable-line|command-like)

variable-like:
  variable-line|variable-if

variable-if: ('if'|'if!') command-line
  variable-if-body
  *variable-elif
  ?variable-else
  'end'

variable-elif: ('elif'|'elif!') command-line
  variable-if-body

variable-else: 'else'
  variable-if-body

variable-if-body:
  *variable-like

variable-line: <variable> ('='|'+='|'=+') value-attributes? <value>
value-attributes: '[' <key-value-pairs> ']'

command-like:
  command-line|command-if

# Note: ':' and ';' only valid directly in test.
#
command-line: command-expr (';'|(':' <text>))?
  *here-document

command-if: ('if'|'if!') command-line
  command-if-body
  *command-elif
  ?command-else
  'end' (';'|(':' <text>))?

command-elif: ('elif'|'elif!') command-line
  command-if-body

command-else: 'else'
  command-if-body

command-if-body:
  *(variable-line|command-like)

command-expr: command-pipe (('||'|'&&') command-pipe)*

command-pipe: command ('|' command)*

command: <path>(' '+(<arg>|redirect|cleanup))* command-exit?

redirect: stdin|stdout|stderr

stdin:  '0'?(in-redirect)
stdout: '1'?(out-redirect)
stderr: '2'(out-redirect)

in-redirect:  '<-'|\
              '<+'|\
              '<'{':'?} <text>|\
              '<<'{':'?} <here-end>|\
              '<<<' <file>

out-redirect: '>-'|\
              '>+'|\
              '>&' ('1'|'2')|\
              '>'{':'?'~'?} <text>|\
              '>>'{':'?'~'?} <here-end>|\
              '>>>'{'&'?} <file>

cleanup: ('&'|'&!'|'&?') (<file>|<dir>)

command-exit: ('=='|'!=') <exit-status>

here-document:
  *<text>
  <here-end>
\

Note that file descriptors must not be separated from the redirect operators
with whitespaces. And if leading text is not separated from the redirect
operators, then it is expected to be a file descriptor. As an example, the
first command below has \c{2} as an argument and redirects \c{stdout}, not
\c{stderr}. While the second is invalid since \c{a1} is not a valid file
descriptor.

\
$* 2 >!
$* a1>!
\

In merge redirects the left-hand-side descriptor (implied or explicit) must
not be the same as the right-hand-side. Having both merge redirects at the
same time is illegal.

Here-line is like double-quoted string but recognizes newlines.

It is an error to specify both leading and trailing descriptions.

\h#include|Inclusion|

While in the grammar the \c{include} directive is shown to only appear
interleaving with scopes and tests, it can be used anywhere in the scope
body. It can also contain several parts of a scope, for example, setup and
test lines.

The \c{--once} option signals that files that have already been included in
this scope should not be included again. The implementation is not required to
handle links when determining if two paths are to the same file. Relative
paths are assumed to be relative to the including testscript.

Note that \c{include} is a directive, not a command. It is performed during
parsing before any command is executed or testscript variable assigned. You
can, however, use variables assigned in the buildfile. For example:

\
include --once common-$(cxx.target.class).test
\


\h#grammar-script|Script|

\
script:
  (script-scope | script-line)*
\

A testscript file is a sequence of scopes and (logical) lines.

\h#grammar-scope|Scope|

\
script-scope:
  description-line?
  '{'
  script
  '}'
\

A block establishes a nested variable scope and a cleanup context. Any
variables set within the block will only have effect until the end of the
block. All registered cleanups are triggered at the end of the block.

Additionally, entering a block triggers the creation of a nested temporary
directory with the test/group id (see below) as its name. This directory then
becomes the current working directory (\c{CWD}). Unless instructed otherwise,
this temporary directory is removed at the end of the block and the previous
\c{CWD} value is restored. (@@ Should we expect it to be empty, i.e., no
unexpected output from the test?).

Test and test group blocks have the same semantics except that in a test block
each test line is considered to be part of the same test while in the test
group each test line is treated as an individual test. Individual test lines
in a group are treated \i{as if} they were in a test block consisting of just
that line. In particular, this means that a nested temporary directory is also
created for such individual tests and cleanup happens immediately after
executing the test line.

While test group blocks can contain other test group and test blocks, test
blocks cannot contain nested blocks of any kind.

A testscript execution starts in \c{out_base} as \c{CWD} and \i{as if} in an
implicit test group block with the testscript file name (without the
extension) as this group's id.

For example, consider the following testscript file which we assume is called
\c{basics.test}:

\
: group1
{{
  foo = bar

  + setup1
  + setup2 &out-setup2

  test1 &out-test1 ; test1

  : test2
  {
    bar = baz

    test2a $baz &out-test2
    test2b <out-test2
  }

  test3 $foo ; test3

  - teardown2
  - teardown1
}}
\

Below is its annotated version that shows all the \i{as if} transformations
as well as various actions performed during its execution:

\
# set CWD=$out_root/

: basics
{{ # Create basics/ temporary subdirectory, set CWD=basics/

  : group1
  {{ # Create group1/ temporary subdirectory, set CWD=group1/

    foo = bar

    + setup1
    + setup2 &out-setup2

    : test1
    { # Create test1/ temporary subdirectory, set CWD=test1/

      test1 &out-test1

    } # Remove out-test1, remove test1/, set CWD=group1/

    : test2
    { # Create test2/ temporary subdirectory, set CWD=test2/

      bar = baz

      test2a $baz &out-test2
      test2b <out-test2

    } # Variable bar is no longer in effect
      # Remove out-test2, remove test2/, set CWD=group1/

    : test3
    { # Create test3/ temporary subdirectory, set CWD=test3/

      test3 $foo

    } # Remove test3/, set CWD=group1/

    - teardown2
    - teardown1

  }} # Variable foo is no longer in effect
     # Remove out-setup2, group1/, set CWD=basics/

}} # Remove basics/, set CWD=$out_root/
\

Because of this nested directory structure, a test can use \c{..}-based
relative paths to refer to, for example, a file created by a group's setup
command. For example:

\
{{
  + setup &out-setup

  test ../out-setup
}}
\


\h#grammar-line|Line|

\
script-line:
  directive-line | \
  variable-line  | \
  test-line | setup-line | teardown-line
\

A testscript line is either a directive, a variable assignment, a
setup/teardown command, or a test command.

To distinguish between the variable assignment and test command line the
parsing and expansion is performed in the \i{chunking} mode, that is, the
parser parses a minimum amount of semantically complete input and stops.

If parsing the first chunk of the input resulted in a single simple name and
the following lexer token is one of \c{=}, \c{+=}, or \c{=+}, then this line
is treated as a variable assignment. Otherwise, it is a test command line.

Similar to the Buildfile language, this semantics supports indirect/computed
variable names, for example:

\
foo = bar
$bar = baz
\

\h#grammar-description|Description|

\
description-line: ': '<text>
  (': '<text>)*
\

Description lines start with a colon (\c{:}) and are used to document tests
(either single-line or compound) as well as test groups. In a sense, they are
formalized comments.

By convention the description has the following format with all three
components being optional.

\
: <id>
: <summary>
:
: <details>
\

If the first line in the description does not contain any whitespaces, then it
is assumed to be the test or test group id. If the next line is followed by a
blank line, then it is assume to be the test or test group summary. After the
blank line come optional details which are free-form.

If an id is not specified then it is automatically derived from the test or
test group location. If the test or test group is contained directly in the
top-level testscript file, then just its start line number is used as an id.
Otherwise, if the test or test group reside in an included file, then the
start line number (inside the included file) is prefixed with the line number
of the \c{.include} directive followed by the included file name (without the
extension) in the form \c{<line>-<file>-}. This process is repeated
recursively for nested inclusion.

The start line for a block (either test or group) is the line containing
opening brace (\c{{}) and for a simple test \- the test line itself.

\h#grammar-directives|Directives|

\
directive-line:
  include
  if-else
\

All directive lines start with a leading dot (\c{.}). To specify a
non-directive line that starts with a dot you can either escape or quote it,
for example:

\
\.include
'.include'
\

\h2#grammar-directives-include|\c{.include}|

\
include: '.include' (<path> )+
\

The \c{include} directive includes one or more testscript files into
another. If the specified path is not absolute, then it is interpreted as
being relative to the including file. The semantics of inclusion is \i{as if}
the contents of the included file appeared directly in the including file
except for deriving test/group ids and displaying locations in diagnostics.

The reminder of the line after the \c{'.include'} word is expanded as a
Buildfile variable value.


\h2#grammar-directives-if-else|\c{.if} \c{.else}|

\
if-else: ('.if' | '.if!') <condition>
  script
  elif*
  else?
  '.end'

elif: ('.elif' | '.elif!') <condition>
  script

else: '.else'
  script
\

The \c{if-else} directives allow for conditional exclusion of testscript
fragments. The body of the \c{if-else} directive can be either a single
(logical) line, a single block, or multiple lines/blocks. For example:

\
.if ($foo == FOO)
  bar = BAR

.if ($cxx.target.class != windows)
  $* foo

.if ($cxx.target.class != windows)
  {
    $* foo
    $* bar
  }

.if ($foo == FOO)
.{
  $* foo

  bar = BAR
  baz = BAZ

  {
    $* $bar
    $* $baz
  }
.}
\

Note that \c{if-else} operates on logical lines/blocks, for example:

\
.if ($foo == FOO)
  : foo-bar
  : Test foo bar combination
  $* foo bar >>EOO
  foo
  bar
  EOO


.if ($foo == FOO)
  : foo-bar
  : Test foo bar combination
  : foo-bar
  {
    $* foo
    $* bar
  }
\

The reminder of the line after the \c{'.if'} and \c{'.elif'} words is expanded
as a Buildfile variable value and should evaluate to either \c{'true'} or
\c{'false'} text literals.

\h#grammar-variable|Variable Assignment|

\
variable-line: <variable> ('=' | '+=' | '=+') value-attributes? <value>

value-attributes: '[' <key-value-pairs> ']'
\

The Testscript variable assignment semantics is equivalent to Buildfile except
that \c{<value>} is expanded as \"strings\", not \"names\" (@@ clarify) and
the default value type is \c{strings}. Note that unlike Buildfile no variable
attributes are supported.

\h#grammar-test|Test|

\
test-line:
  description-line?
  command-expr command-exit? (';' | ':' <text>)?
  here-document*

command-exit: ('==' | '!=') <exit-status>
\

The test command line can specify an optional exist status check. If omitted,
then the test is expected to succeed (0 exit status).

Variable expansion and context evaluation is performed (using chunked parsing)
in \c{command-expr} and \c{command-exit} but not in the inline test
description.

\h#grammar-setup-teardown|Setup/Teardown|

\
setup-line: '+' command-expr ';'?
  here-document*

teardown-line: '-' command-expr ';'?
  here-document*
\

The setup and teardown command lines are similar to the test command line
except that they cannot have a test description or exit status check (they are
always expected to succeed). The main motivation for distinguishing between
test and setup/teardown commands is the ability to ignore the teardown
commands in order to preserve the setup of test. For example, of a failed test
that you are debugging. Also, the setup/teardown and test commands are shown
at different verbosity levels (\c{3/-V} and \c{2/-v} respectively).

Setup and teardown commands associeted with the test group are executed
sequenctially in the order specified.

\h#grammar-command-expr|Command Expression|

\
command-expr: command-pipe (('||' | '&&') command-pipe)*
\

Multiple commands can be combination with AND and OR operators. Note that the
evaluation order is always from left to right (left-associative) and both
operators have the same precedence and are short-circuiting. Note, however,
that short-circuiting does not apply to variable expansion.

The result of the expression is the exit status of the last \c{command-pipe}
executed.


\h#grammar-command-pipe|Command Pipe|

\
command-pipe: command ('|' command)*
\

Commands can also be combined with a pipe. All the piped commands except that
last are expected to succeed with the last command's exit status being the
result of \c{command-pipe}.

\h#grammar-command|Command|

\
command: <path> <arg>* {stdin? stdout? stderr? merge? cleanup*}
\

A command starts with a command path following by options and arguments, if
any. We can also redirect/merge standard streams as well as register for
automatic cleanup files and directories that may be created by the command.
Note that redirects, merge, and cleanups can appear in any order but must
come after the arguments.

\h#grammar-redirect-merge-cleanup|Redirect, Merge, Cleanup|

\
stdin:  '0'?('<'<text> | '<<'<here-end> | '<<<'<file>     | '<!' | '<?')
stdout: '1'?('>'<text> | '>>'<here-end> | '>>>''&'?<file> | '>!' | '>?')
stderr: '2'('>'<text>  | '>>'<here-end> | '>>>''&'?<file> | '>!' | '>?')

merge: '1>&2' | '2>&1'

cleanup: '&'(<file> | <dir>)
\

The \c{stdin} stream data can come from a pipe, string, the here-document
fragment, file, or \c{/dev/null} (\c{<!}). Specifying both pipe and redirect
is an error.

If no \c{stdin} redirect is specified and the test tries to read any data, it
is considered to have failed. If you need to allow reading from the default
\c{stdin} (for instance if the test is really an example), specify \c{<?}.

The \c{stdout} and \c{stderr} stream data can go to a pipe (\c{stdout} only),
file (append if \c{>>>&}), or \c{/dev/null} (\c{>!}). It can also be
compared to a string or the here-document fragment. For \c{stdout} specifying
both pipe and redirect is an error. If no explicit \c{stderr} redirect is
specified and the test is expected to fail (non-zero exit status), then an
implicit \c{2>!} redirect is assumed.

If no \c{stdout} or \c{stderr} redirect is specified and the test tries to
write any data to either stream, it is considered to have failed. If you need
to allow writing to the default \c{stdout} or \c{stderr}, specify \c{>?} and
\c{2>?}, respectively.

We can also merge \c{stderr} to \c{stdout} (\c{2>&1}) or vice versa
(\c{1>&2}).

If a command creates extra files or directories then we can register them for
automatic cleanup at the end of the test. Files mentioned in redirects are
registered automatically.

Note that unlike shell no whitespaces around \c{<} and \c{>} redirects
or after the \c{&} cleanups are allowed.

A here-document redirect must be specified \i{literally} on test command
line. Specifically, it must not be the result of a variable expansion or
context evaluation, which rarely makes sense anyway since the following
here-document fragment itself cannot be the result of the
expansion/evaluation either; in a sense they both are part of the syntax.

This requirement is imposed in order to be able to skip test lines and their
associated here-document fragments in the \c{if-else} directives without
performing any expansions/evaluations (which may not be valid).

The skipping procedure for a line that is either a variable assignment or a
test command is as follows: The line is lexed until the newline or EOF which
checking each token either for one of the variable assignment operators or
here-document redirects. If both kinds are present then this is an ambiguity
error which can be resolved by quoting either of the token, depending on the
desired semantics (variable assignment or test command). Otherwise, all the
here-document redirects are noted and the corresponding number of here-document
fragments is skipped (which \c{here-end} match/order validation).

Note also that this procedure is applied even in case of \c{if-else} with
\c{directive-block} since the block end (\c{.\}}) may appears literally in
one of the here-document fragments.

\h#grammar-here-document|Here-Document|

\
here-document:
  <text>*
  <here-end>
\

The here-document fragments can be used to supply data to \c{stdin} or to
compare output to the expected result for \c{stdout} and \c{stderr}. Note that
the order of here-document fragments must match the order of redirects, for
example:

\
: select-no-table-error
$* --interactive >>EOO <<EOI 2>>EOE
enter query:
EOO
SELECT * FROM no_such_table
EOI
error: no such table 'no_such_table'
EOE
\

Here-strings can be single-quoted literals or double-quoted with expansion.
This semantics is extended to here-documents as follows. If the end marker
on the command line is single-quoted, then the here-document lines are
parsed as if they were single-quoted except that the single quote itself
is not treated as special. In this mode there are no expansions, escape
sequences, not even line continuations \- each line is taken literally.

If the end marker on the command line is double-quoted, then the here-document
lines are parsed as if they were double-quoted except that the double quote
itself is not treated as special. In this mode we can use variables
expansions, function calls, and evaluation contexts. However, we have to
escape the \c{$(\\} character set.

If the end marker is not quoted then it is treated as if it were
single-quoted. Note also that quoted end markers must be quoted \i{wholly},
that is, from the beginning and until the end and without any interruptions.

If the preceding command line starts with leading whitespaces, then the
equivalent number is stripped (if present) from each here-document line
(including the end marker). For example, the following two testscript
fragments are equivalent:

\
{
  $* <<EOI
  foo
  bar
  EOI
}
\

\
{
  $* <<EOI
foo
bar
EOI
}
\

The leading whitespace stripping does not apply to line continuations.

\h#here-regex|Output Regex|

The expected result in output here-strings and here-documents can be specified
as a regular expression instead of plain text. To signal the use of regular
expressions the redirect must include the \c{~} modifier, for example:

\
$* >~'/fo+/' 2>>~/EOE/
/ba+r/
baz
EOE
\

The regular expression used for output matching has two levels. At the outer
level the expression is over lines with each line treated as a single
character. We will refer to this outer expression as \i{line-regex} and
to its characters as \i{line-char}.

A line-char can be a literal line (like \c{baz} in the example above) in
which case it will only be equal to an identical line in the output. Or a
line-char can be an inner level regex (like \c{ba+r} above) in which
case it will be equal to any line in the output that matches this regex.
Where not clear from context we will refer to this inner expression as
\i{char-regex} and its characters as \i{char}.

A line is treated as literal unless it starts with the \i{regex introducer
character} (\c{/} in the above example). In contrast, the line-regex is always
in effect (in a sense, the \c{~} modifier is its introducer). Note that the
here-string regex naturally must always start with an introducer.

A char-regex line that starts with an introducer must also end with one
optionally followed by \i{match flags}. Currently the only supported flag is
\c{i} for case-insensitive match. For example:

\
$* >>~/EOO/
/ba+r/i
/ba+z/i
EOO
\

Any character can act as a regex introducer. For here-strings it is the first
character in the string. For here-documents the introducer is specified as
part of the end marker. In this case the first character is the introducer,
everything after that and until the second occurrence of the introducer is the
actual end marker, and everything after that are global match flags. Global
match flags apply to every char-regex (but not literal line) in this
here-document. Note that there is no way to escape the introducer character
inside the regex.

As an example, here is a shorter version of the previous example that also
uses a different introducer character.

\
$* >>~%EOO%i
%ba+r%
%ba+z%
EOO
\

By default a line-char is treated as an ordinary, non-syntax character with
regards to line-regex. Lines that start with a regex introducer but do not end
with one are used to specify syntax line-chars. Such syntax line-chars can
also be specified after (or instead of) match flags. For example:

\
$* >>~/EOO/
/(
/fo+x/|
/ba+r/|
/ba+z/
/)+
EOO
\

As an illustration, if we call the \c{/fo+x/} expression \c{A}, \c{/ba+r/} \-
\c{B}, and \c{/ba+z/} \- C, then we can represent the above line-regex in
the following more traditional form:

\
(A|B|C)+
\

Only characters from the \c{.()|*+?{\}\\0123456789,=!} set are allowed as
syntax line-chars with presence of any other character being an error.

A blank line as well as the \c{//} sequence (assuming \c{/} is the introducer)
are treated as an empty line-char. For the purpose of matching, newlines are
viewed as separators rather than being part of a line. In particular, in this
model, the customary trailing newline at the end of the output introduces a
trailing empty line-char. As a result, unless the \c{:} (no newline) redirect
modifier is used, an empty line-char is implicitly added to line-regex.


\h1#style|Style Guide|

This section describes the Testscript style that is used in the \c{build2}
project. The primary goal of testing in \c{build2} is not to exhaustively
test every possible situation. Rather, it is to keep tests comprehensible
and maintainable in the long run.

To this effect, don't try to test every possible combination; this striving
will quickly lead to everyone drowning in hundreds of tests that are only
slight variations of each other. Sometimes combination tests are useful but
generally keep things simple and test one thing at a time. The believe here is
that real-world usage will uncover much more interesting interactions that you
would never have thought of yourself.To quote a famous physicist, \"\i{... the
imagination of nature is far, far greater than the imagination of man.}\"

To expand on combination tests, don't confuse them with corner case tests. As
an example, say you have tests for feature A and B. Now you wonder what if for
some reason they don't work together. Note that you don't have a clear
understanding of why they might not work together; you just want to add one
more test, \i{for good measure}. We don't do that. To put it another way, for
each test you should have a clear understanding of what logic in the code you
are testing.

One approach that we found works well is to look at the changes you would like
to commit and make sure you have a test that exercises each \i{logic
branch}. It is also a good idea to keep testing in mind as you implement
things. When tempted to add a small special case just to make the result
\i{nicer}, remember that you will also have to test this special case. Given a
choice, always prefer functional to unit tests since the former test the end
result rather than something intermediate and possibly mocked.

Documentation-wise, each test should at least include explicit id that
adequately summarizes what it tests. Add summary or even details for more
complex tests. Failure tests almost always fall into this category.

Use the leading description for multi-line tests, for example:

\
: multi-name
:
$* John Jane >>EOO
Hello, John!
Hello, Jane!
EOO
\

Here is an example of a description that includes all three components:

\
: multi-name
: Test multiple name arguments
:
: This test makes sure we properly handle multiple names passed as
: separate command line arguments.
:
$* John Jane >>EOO
Hello, John!
Hello, Jane!
EOO
\

Separate multi-line tests with blank lines. You may want to place larger tests
into explicit test scopes for better visual separation (this is especially
helpful if the test contains blank lines, for example, in here-document
fragments). In this case the description should come before the scope. Note
that here-documents are indented as well. For example:

\
: multi-name
:
{
  $* John Jane >>EOO
  Hello, John!

  Hello, Jane!

  EOO
}
\

One-line tests may use the trailing description (which must always be
the test id). Within a test block (one-liners without a blank between
them), the ids should be aligned, for example:

\
$* John >\"Hi, John!\"       : custom-john
$* World >\"Hello, World!\"  : custom-world
\

Note that you are free to put multiple spaces between the end of the command
line and the trailing description. But don't try to align ids between blocks
\- this is a maintenance pain.

If multiple tests belong to the same group, consider placing them into an
explicit group scope. A good indication that tests form a group is if their
ids start with the same prefix, as in the above example. If placing tests into
a group scope, use the prefix as the group's id and don't repeat it in the
tests. It is also a good idea to give the summary of the group, for example:

\
: custom
: Test custom greetings
:
{
  $* John >\"Hi, John!\"       : john
  $* World >\"Hello, World!\"  : world
}
\

In the same vein, don't repeat the testscript id in group or test ids. For
example, if the above tests were in the \c{greeting.test} testscript, then
using \c{custom-greeting} as the group id would be unnecessarily repetitive
since the id path would become, for example,
\c{greeting/custom-greeting/john}.

"