summaryrefslogtreecommitdiff
path: root/subplot.md
blob: c340763135bbff95fd1c6c2fe4ea697b009e81d7 (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
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
# Introduction

Subplot is software to help capture and communicate acceptance
criteria for software and systems, and how they are verified, in a way
that's understood by all project stakeholders. The current document
contains the acceptance criteria for Subplot itself, and its
architecture.

The acceptance criteria are expressed as _scenarios_, which roughly
correspond to use cases. The scenario as accompanied by explanatory
text to explain things to the reader. Scenarios use a given/when/then
sequence of steps, where each step is implemented by code provided by
the developers of the system under test. This is very similar to the
[Cucumber][] tool, but with more emphasis of producing a standalone
document.

[Cucumber]: https://en.wikipedia.org/wiki/Cucumber_(software)

## Subplot architecture

Subplot reads an input document, in Markdown, and generates a typeset
output document, as PDF or HTML, for all stakeholders to understand.
Subplot also generates a test program, in Python, that verifies the
acceptance criteria are met, for developers and testers and auditors
to verify the sustem under test meets its acceptance criteria. The
generated program uses code written by the Subplot user to implement
the verification steps. The graph below illustrates this and shows how
data flows through the system.

```dot
digraph "architecture" {
md [label="foo.md \n (document, Markdown)"];
md [shape=box];

bindings [label="foo.myaml \n (bindings, YAML)"];
bindings [shape=box];

impl [label="foo.py \n (step implemenations, Python)"]
impl [shape=box];

subplot [label="Subplot"];
subplot [shape=ellipse];

pdf [label="foo.pdf \n PDF (generated)"]
pdf [shape=note];

html [label="foo.html \n HTML (generated)"]
html [shape=note];

testprog [label="test.py \n test program\n(generated)"]
testprog [shape=note];

report [label="Test report \n (stdout of test.py)"]
report [shape=note];

md -> subplot;
bindings -> subplot;
impl -> subplot;
subplot -> pdf;
subplot -> html;
subplot -> testprog;
testprog -> report;
}
```

[Pandoc]: https://pandoc.org/

Subplot uses the [Pandoc][] software for generating PDF and HTML
output documents. In fact, any output format supported by Pandoc can
be requested by the user. Depending on the output format, Pandoc may
use, for example, LaTeX. Subplot interprets parts of the Markdown
input file itself.

Subplot actually consists mainly of two separate programs: 
**sp-docgen** for generating output documents, and **sp-codegen** for
generating the test program. There are a couple of additional tools
(**sp-meta** for reporting meta data about a Subplot document, and
**sp-filter** for doing the document generation as a Pandoc filter).

Thus a more detailed architecture view is shown below.

```dot
digraph "architecture2" {
md [label="foo.md \n (document, Markdown)"];
md [shape=box];

bindings [label="foo.myaml \n (bindings, YAML)"];
bindings [shape=box];

impl [label="foo.py \n (step implemenations, Python)"]
impl [shape=box];

docgen [label="sp-docgen"];
docgen [shape=ellipse];

codegen [label="sp-codegen"];
codegen [shape=ellipse];

pdf [label="foo.pdf \n PDF (generated)"]
pdf [shape=note];

html [label="foo.html \n HTML (generated)"]
html [shape=note];

testprog [label="test.py \n test program\n(generated)"]
testprog [shape=note];

report [label="Test report \n (stdout of test.py)"]
report [shape=note];

md -> docgen;
bindings -> docgen;
md -> codegen;
bindings -> codegen;
impl -> codegen;
docgen -> pdf;
docgen -> html;
codegen -> testprog;
testprog -> report;
}
```

## A fairy tale of acceptance testing

The king was upset. This naturally meant the whole court was in a
tizzy and chattering excitedly at each other, while trying to avoid
the royal wrath.

"Who will rid me of this troublesome chore?" shouted the king, and
quaffed a flagon of wine. "And no killing of priests, this time!"

The grand hall's doors were thrown open. The grand wizard stood in the
doorway, robe, hat, and staff everything, but quite still. After the
court became silent, the wizard strode confidently to stand before the
king.

"What ails you, my lord?"

The king looked upon the wizard, and took a deep breath. It does not
do to shout at wizards, for they control dragons, and even kings are
tasty morsels to the great beasts.

"I am tired of choosing what to wear every day. Can't you do
something?"

The wizard stoke his long, grey beard. He turned around, looked at the
magnificent outfits worn by members of the court. He turned back, and
looked at the king.

"I believe I can fix this. Just to be clear, your beef is with having
to choose clothing, yes?"

"Yes", said the king, "that's what I said. When will you be done?"

The wizard raised his staff and brought it back down again, with a
loud bang.

"Done" said the wizard, smugly.

The king was amazed and started smiling, until he noticed that
everyone, including himself, was wearing identical burlap sacks and
nothing on their feet. His voice was high, whiny, like that of a
little child.

"Oh no, that's not at all what I wanted! Change it back! Change it
back now!"

The morale of this story is to be clear and precise in your acceptance
criteria, or you might get something other than what you really, really
wanted.


## Motivation for Subplot

Keeping track of requirements and acceptance criteria is necessary for
all but the simplest of software projects. Having all stakeholders in
a project agree to them is crucial, as is that all agree how it is
verified that the software meets the acceptance criteria. Subplot
provides a way for documenting the shared understanding of what the
acceptance criteria are and how they can be checked automatically.

Stakeholders in a project may include:

* those who pay for the work to be done; this may be the employer of
  the developers for in-house projects ("*customer*")
* those who use the resulting systems, whether they pay for it or not
  ("*user*")
* those who install and configure the systems and keep them functional
  ("*sysadmin*")
* those who support the users ("*support*")
* those who test the project for acceptability ("*tester*")
* those who develop the system in the first place ("*developer*")

The above list is incomplete and simplistic, but suffices as an
example.

All stakeholders need to understand the acceptance criteria, and how
the system is evaluated against the criteria. In the simplest case,
the customer and the developer need to both understand and agree so
that the developer knows when the job is done, and the customer knows
when they need to pay their bill.

However, even when the various stakeholder roles all fall upon the
same person, or only on people who act as developers, the Subplot
tooling can be useful. A developer would understand acceptance
criteria expressed only in code, but doing so may take time and energy
that are not always available. The Subplot approach aims to encourage
hiding unnecessary detail and documenting things in a way that is easy
to understand with little effort.

Unfortunately, this does mean that for a Subplot output document to
be good and helpful, writing it will require effort and skill. No tool
can replace that.


# Requirements

This chapter lists requirements for Subplot. These requirements are
not meant to be automatically verifiable. For specific, automatically
testable acceptance criteria, see the later [chapter with acceptance
tests for Subplot](#acceptance).

Each requirement here is given a unique mnemnoic id for easier
reference in discussions.

**UnderstandableTests**

:   Acceptance tests should be possible to express in a way that's
    easily understood by all stakeholders, includcing those who are
    not software developers.

    _Done_ but requires the Subplot document to be written with care.

**EasyToWriteDocs**

:   The markup language for writing documentation should be easy to
    write.

    _Done_ by using Markdown.

**AidsComprehension**

:   The formatted human-readable documentation should use good layout
    and typography to enhance comprension.

    _In progress_ — typesetting via Pandoc works, but may need
    review and improvement.

**CodeSeparately**

:   The code to implement the acceptance criteria should not be
    embedded in the documentation source, but be in separate files.
    This makes it easier to edit without specialised tooling.

    _Done_ by keeping scenario step implementations in a separate
    file.

**AnyProgammingLanguage**

:   The developers implementing the acceptance tests should be free to
    use a language they're familiar and comfortable with. Subplot
    should not require them to use a specific language.

    _Not done_ — only Python supported at the moment.

**FastTestExecution**

:   Executing the acceptance tests should be fast.

    _Not done_ &mash; the generated Python test program is simplistic
    and linear.

**NoDeployment**

:   The acceptance test tooling should assume the system under test is
    already deployed and available. Deploying is too big of a problem
    space to bring into the scope of acceptance testing, and there are
    already good tools for deployment.

    _Done_ by virtue of letting those who implement the scenario steps
    worry about it.

**MachineParseableResults**

:   The tests should produce a machine parseable result that can be
    archived, post-processed, and analyzed in ways that are of
    interest to the project using Subplot. For example, to see trends
    in how long tests take, how often tests fail, to find regressions,
    and to find tests that don't provide value.

    _Not done_ — the generated test program is simplistic.


# Subplot input language

Subplot reads three input files, each in a different format:

* The document file, which uses the Markdown dialect understood by
  Pandoc.
* The bindings file, in YAML.
* The functions file, in Python.

Subplot interprets specially marked parts of the input document
specially. It does this via the Pandoc abstract syntax tree, rather
than text manipulation, and thus anything that Pandoc understands is
understood by Subplot. We will not specify Pandoc's dialect of
Markdown here, only the parts Subplot pays attention to.


## Document metadata

Pandoc supports, and Subplot makes use of, a [YAML metadata block][] in a
Markdown document. This can and should be used to set the document
title, authors, date (version), and can be used to control some of the
typesetting. Crucially for Subplot, the bindings and functions files
are named in the metadata block, rather than Subplot deriving them
from the input file name.

[YAML metadata block]: https://pandoc.org/MANUAL.html#extension-yaml_metadata_block

As an example, the metadata block for the Subplot document might look
as follows. The `---` before and `...` after the block are mandatory:
they are how Pandoc recongizes the block.

~~~{.yaml .numberLines}
---
title: "Subplot"
author: The Subplot project
date: work in progress
bindings: subplot.yaml
functions: subplot.py
...
~~~


## Document markup

[fenced code blocks]: https://pandoc.org/MANUAL.html#fenced-code-blocks

Subplot understands certain tags for [fenced code blocks][] specially.
A scenario, for example, would look like this:

~~~~~~{.markdown .numberLines}
```scenario
given a standard setup
when peace happens
then everything is OK
```
~~~~~~

The `scenario` tag on the code block is recognized by Subplot, which
will typeset the scenario (in output documents) or generate code (for
the test program) accordingly. Scenario blocks do not need to be
complete scenario. Subplot will collect all the snippets into one
block for the test program. Snippets under the same heading belong
together; the next heading of the same or a higher level ends the
scenario.

For embedding test data files in the Markdown document, Subplot
understands the `file` tag:

~~~~~~~~markdown
~~~{#filename .file}
This data is accessible to the test program as 'filename'.
~~~
~~~~~~~~

The `.file` attribute is necessary, as is the identifier, here
`#filename`. The generated test program can access the data using the
identifier (without the #). The mechanism used is generic to Pandoc,
and can be used to affect the typesetting by adding more attributes.
For example, Pandoc can typeset the data in the code block using
syntax highlighting, if the language is specified: `.markdown`,
`.yaml`, or `.python`, for example.

Subplot also understands the `dot` and `roadmap` tags, and can use the
Graphviz dot program, or the [roadmap][] Rust crate, to produce
graphs. These can useful for describing things visually.

[roadmap]: https://crates.io/search?q=roadmap


## Bindings file

The bindings file binds scenario steps to Python functions that
implement the steps. The YAML file is a list of objects (also known as
dicts or hashmaps or key/value pairs), specifying a step kind (given,
when, then), a regular expression matching the text of the step and
optionally capturing interesting parts of the text, and the name of a
function that implements the step.

~~~{.yaml .numberLines}
- given: a standard setup
  function: create_standard_setup
- when: (?<thing>\S+) happens
  function: make_thing_happen
- then: everything is OK
  function: check_everything_is_ok
~~~

In the example above, there are three bindings:

* A binding for a "given a standard setup" step. The binding captures
  no part of the text, and causes the `create_standard_setup` function
  to be called.
* A binding for a "when" step consisting of one word followed by
  "happens". For example, "peace", as in "then peace happens". The
  word is captured as "thing", and given to the `make_thing_happen`
  function as an argument when it is called.
* A binding for a "then everthing is OK" step, which captures nothing,
  and calls the `check_everything_is_ok` function.

The regular expressions use [PCRE][] syntax as implemented by the Rust
[regex][] crate. The `(?P<name>pattern)` syntax is used to capture
parts of the step. The captured parts are given to the bound function
as arguments, when it's called.

[PCRE]: https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions
[regex]: https://crates.io/crates/regex



## Functions file

The functions file is not parsed by Subplot at all. Subplot merely
copies it to the output. All parsing and validation of the file is
done by the Python implementation.

The Python functions must accept a "context" argument, and a keyword
argument for each part of the step the corresponding regular
expression captures. The capture name and the keyword argument name
must be the same.

The context argument is a dict-like object, which the generated
program creates automatically. The context is carried from function
call to function call, to allow functions to manage state between
themselves. Typically, one step might do something, and record the
results into the context, and another step might check the results by
inspecting the context. This decouples functions from each other, and
avoids having them use global variables for state.



# Acceptance criteria for Subplot {#acceptance}


Add the acceptance criteria test scenarios for Subplot here.


## Test data shared between scenarios

The scenarios below test Subplot by running it against specific input
files. This section specifies the bindings and functions files.
They're separate from the scenarios so that the scenarios are shorter
and clearer, but also so that the input files do no need to be
duplicated for each scenario.

~~~~{#simple.md .file .markdown .numberLines}
---
title: Test scenario
bindings: b.yaml
functions: f.py
...

# Simple
This is the simplest possible test scenario

```scenario
given precondition foo
when I do bar
then bar was done
```
~~~~

~~~{#b.yaml .file .yaml .numberLines}
- given: precondition foo
  function: precond_foo
- when: I do bar
  function: do_bar
- when: I do foobar
  function: do_foobar
- then: bar was done
  function: bar_was_done
- then: foobar was done
  function: foobar_was_done
~~~


~~~{#f.py .file .python .numberLines}
def precond_foo(ctx):
    ctx['bar_done'] = False
    ctx['foobar_done'] = False
def do_bar(ctx):
    ctx['bar_done'] = True
def bar_was_done(ctx):
    assert_eq(ctx['bar_done'], True)
def do_foobar(ctx):
    ctx['foobar_done'] = True
def foobar_was_done(ctx):
    assert_eq(ctx['foobar_done'], True)
~~~


## Smoke test

This tests that Subplot can build a PDF and an HTML document, and
execute a simple scenario successfully. The test is based on
generating the test program from an input file, running the test
program, and examining the output.

~~~scenario
given file simple.md
and file b.yaml
and file f.py
when I run sp-docgen simple.md -o simple.pdf
then file simple.pdf exists
when I run sp-docgen simple.md -o simple.html
then file simple.html exists
when I run sp-codegen --run simple.md -o test.py
then scenario "Simple" was run
and step "given precondition foo" was run
and step "when I do bar" was run
and step "then bar was done" was run
and program finished successfully
~~~


## Keywords

Subplot supports the keywords **given**, **when**, and **then**, and
the aliases **and** and **but**. The aliases stand for the same
(effective) keyword as the previous step in the scenario. This chapter
has scenarios to check the keywords and aliases in various
combinations.

### All the keywords

~~~scenario
given file allkeywords.md
and file b.yaml
and file f.py
when I run sp-docgen allkeywords.md -o foo.pdf
then file foo.pdf exists
when I run sp-codegen --run allkeywords.md -o test.py
then scenario "All keywords" was run
and step "given precondition foo" was run
and step "when I do bar" was run
and step "then bar was done" was run
and program finished successfully
~~~

~~~{#allkeywords.md .file .markdown .numberLines}
---
title: All the keywords scenario
bindings: b.yaml
functions: f.py
...

# All keywords

This uses all the keywords.

```scenario
given precondition foo
when I do bar
and I do foobar
then bar was done
but foobar was done
```
~~~

### Keyword aliases

~~~scenario
given file aliases.md
and file b.yaml
and file f.py
when I run sp-docgen aliases.md -o aliases.html
then file aliases.html matches /given<[^>]*> precondition foo/
and file aliases.html matches /when<[^>]*> I do bar/
and file aliases.html matches /and<[^>]*> I do foobar/
and file aliases.html matches /then<[^>]*> bar was done/
and file aliases.html matches /but<[^>]*> foobar was done/
and program finished successfully
~~~

~~~{#aliases.md .file .markdown .numberLines}
---
title: Keyword aliasesG
bindings: b.yaml
functions: f.py
...

# Aliases

```scenario
given precondition foo
when I do bar
and I do foobar
then bar was done
but foobar was done
```
~~~

### Misuse of continuation keywords

When continuation keywords (`and` and `but`) are used, they have to not be
the first keyword in a scenario.  Any such scenario will fail to parse because
subplot will be unable to determine what kind of keyword they are meant to
be continuing.

~~~scenario
given file continuationmisuse.md
and file b.yaml
and file f.py
when I run sp-docgen continuationmisuse.md -o foo.pdf
then file foo.pdf exists
when I try to run sp-codegen --run continuationmisuse.md -o test.py
then exit code is non-zero
~~~

~~~{#continuationmisuse.md .file .markdown .numberLines}
---
title: Continuation keyword misuse
bindings: b.yaml
functions: f.py
...

# Continuation keyword misuse

This scenario should fail to parse because we misuse a
continuation keyword at the start.

```scenario
and precondition foo
when I do bar
then bar was done
```
~~~


## Empty lines in scenarios

This scenario verifies that empty lines in scenarios are ignored.

~~~scenario
given file emptylines.md
and file b.yaml
and file f.py
when I run sp-docgen emptylines.md -o emptylines.pdf
then file emptylines.pdf exists
when I run sp-docgen emptylines.md -o emptylines.html
then file emptylines.html exists
when I run sp-codegen --run emptylines.md -o test.py
then scenario "Simple" was run
and step "given precondition foo" was run
and step "when I do bar" was run
and step "then bar was done" was run
and program finished successfully
~~~

~~~~{#emptylines.md .file .markdown .numberLines}
---
title: Test scenario
bindings: b.yaml
functions: f.py
...

# Simple
This is the simplest possible test scenario

```scenario
given precondition foo

when I do bar

then bar was done

```
~~~~


## Automatic cleanup in scenarios

A binding can define a cleanup function, which gets called at the end
of the scenario in reverse order for the successful steps. If a step
fails, all the cleanups for the successful steps are still called. We
test this for every language templat we support.

~~~{#cleanup.yaml .file .yaml .numberLines}
- given: foo
  function: foo
  cleanup: foo_cleanup
- given: bar
  function: bar
  cleanup: bar_cleanup
- given: failure
  function: failure
  cleanup: failure_cleanup
~~~

~~~{#cleanup.py .file .python .numberLines}
def foo(ctx):
   pass
def foo_cleanup(ctx):
   pass
def bar(ctx):
   pass
def bar_cleanup(ctx):
   pass
def failure(ctx):
   assert 0
def failure_cleanup(ctx):
   pass
~~~

~~~{#cleanup.sh .file .bash .numberLines}
foo() {
    true
}
foo_cleanup() {
    true
}
bar() {
    true
}
bar_cleanup() {
    true
}
failure() {
   return 1
}
failure_cleanup() {
   true
}
~~~


### Cleanup functions gets called on success (Python)

~~~scenario
given file cleanup-success-python.md
and file cleanup.yaml
and file cleanup.py
when I run sp-codegen --run cleanup-success-python.md -o test.py
then scenario "Cleanup" was run
and step "given foo" was run, and then step "given bar"
and cleanup for "given bar" was run, and then for "given foo"
and program finished successfully
~~~


~~~~~{#cleanup-success-python.md .file .markdown .numberLines}
---
title: Cleanup
bindings: cleanup.yaml
functions: cleanup.py
template: python
...

# Cleanup

~~~scenario
given foo
given bar
~~~
~~~~~


### Cleanup functions get called on failure (Python)

~~~scenario
given file cleanup-fail-python.md
and file cleanup.yaml
and file cleanup.py
when I try to run sp-codegen --run cleanup-fail-python.md -o test.py
then scenario "Cleanup" was run
and step "given foo" was run, and then step "given bar"
and cleanup for "given bar" was run, and then for "given foo"
and cleanup for "given failure" was not run
and exit code is non-zero
~~~

~~~~~{#cleanup-fail-python.md .file .markdown .numberLines}
---
title: Cleanup
bindings: cleanup.yaml
functions: cleanup.py
template: python
...

# Cleanup

~~~scenario
given foo
given bar
given failure
~~~
~~~~~


### Cleanup functions gets called on success (Bash)

~~~scenario
given file cleanup-success-bash.md
and file cleanup.yaml
and file cleanup.sh
when I run sp-codegen --run cleanup-success-bash.md -o test.sh
then scenario "Cleanup" was run
and step "given foo" was run, and then step "given bar"
and cleanup for "given bar" was run, and then for "given foo"
and program finished successfully
~~~

~~~~~{#cleanup-success-bash.md .file .markdown .numberLines}
---
title: Cleanup
bindings: cleanup.yaml
functions: cleanup.sh
template: bash
...

# Cleanup

~~~scenario
given foo
given bar
~~~
~~~~~


### Cleanup functions get called on failure (Bash)

If a step fails, all the cleanups for the preceding steps are still
called, in reverse order.

~~~scenario
given file cleanup-fail-bash.md
and file cleanup.yaml
and file cleanup.sh
when I try to run sp-codegen --run cleanup-fail-bash.md -o test.sh
then scenario "Cleanup" was run
and step "given foo" was run, and then step "given bar"
and cleanup for "given bar" was run, and then for "given foo"
and cleanup for "given failure" was not run
and exit code is non-zero
~~~

~~~~~{#cleanup-fail-bash.md .file .markdown .numberLines}
---
title: Cleanup
bindings: cleanup.yaml
functions: cleanup.sh
template: bash
...

# Cleanup

~~~scenario
given foo
given bar
given failure
~~~
~~~~~



## Capturing parts of steps for functions

A scenario step binding can capture parts of a scenario step, to be
passed to the function implementing the step as an argument. Captures
can be done using regular expressions.

### Capture using simple patterns

~~~scenario
given file simplepattern.md
and file simplepattern.yaml
and file capture.py
when I run sp-codegen --run simplepattern.md -o test.py
then scenario "Simple pattern" was run
and step "given I am Tomjon" was run
and output matches /function got argument name as Tomjon/
and program finished successfully
~~~

~~~~{#simplepattern.md .file .markdown .numberLines}
---
title: Simple pattern capture
bindings: simplepattern.yaml
functions: capture.py
...

# Simple pattern

~~~scenario
given I am Tomjon
~~~
~~~~

~~~{#simplepattern.yaml .file .yaml .numberLines}
- given: I am {name}
  function: func
~~~

~~~{#capture.py .file .python .numberLines}
def func(ctx, name=None):
    print('function got argument name as', name)
~~~

### Simple patterns with regex metacharacters: forbidden case

Help use to avoid accidental regular expression versus simple pattern
confusion. The rule is that a simple pattern mustn't contain regular
expression meta characters unless the rule is explicitly marked as not
being a regular expression pattern.

~~~scenario
given file confusedpattern.md
and file confusedpattern.yaml
and file capture.py
when I try to run sp-codegen --run confusedpattern.md -o test.py
then exit code is non-zero
and stderr matches /simple pattern contains regex/
~~~

~~~~{#confusedpattern.md .file .markdown .numberLines}
---
title: Simple pattern capture
bindings: confusedpattern.yaml
functions: capture.py
...

# Simple pattern

~~~scenario
given I* am Tomjon
~~~
~~~~

~~~{#confusedpattern.yaml .file .yaml .numberLines}
- given: I* am {name}
  function: func
~~~

### Simple patterns with regex metacharacters: allowed case

~~~scenario
given file confusedbutok.md
and file confusedbutok.yaml
and file capture.py
when I run sp-codegen --run confusedbutok.md -o test.py
then program finished successfully
~~~

~~~~{#confusedbutok.md .file .markdown .numberLines}
---
title: Simple pattern capture
bindings: confusedbutok.yaml
functions: capture.py
...

# Simple pattern

~~~scenario
given I* am Tomjon
~~~
~~~~

~~~{#confusedbutok.yaml .file .yaml .numberLines}
- given: I* am {name}
  function: func
  regex: false
~~~

### Capture using regular expressions

~~~scenario
given file regex.md
and file regex.yaml
and file capture.py
when I run sp-codegen --run regex.md -o test.py
then scenario "Regex" was run
and step "given I am Tomjon" was run
and output matches /function got argument name as Tomjon/
and program finished successfully
~~~

~~~~{#regex.md .file .markdown .numberLines}
---
title: Regex capture
bindings: regex.yaml
functions: capture.py
...

# Regex

~~~scenario
given I am Tomjon
~~~
~~~~

~~~{#regex.yaml .file .yaml .numberLines}
- given: I am (?P<name>\S+)
  function: func
  regex: true
~~~


## Avoid changing typesetting output file needlessly

### Avoid typesetting if output is newer than source files

This scenario make sure that if docgen generates the bitwise identical
output to the existing output file, it doesn't actually write it to
the output file, including its timestamp. This avoids triggering
programs that monitor the output file for changes.

~~~scenario
given file simple.md
and file b.yaml
and file f.py
when I run sp-docgen simple.md -o simple.pdf
then file simple.pdf exists
when I remember the metadata for simple.pdf
and I run sp-docgen simple.md -o simple.pdf
then simple.pdf has the same metadata as before
and only files simple.md, b.yaml, f.py, simple.pdf exist
~~~

### Do typeset if output is older than markdown

~~~scenario
given file simple.md
and file b.yaml
and file f.py
when I run sp-docgen simple.md -o simple.pdf
then file simple.pdf exists
when I remember the metadata for simple.pdf
and I touch simple.md
and I run sp-docgen simple.md -o simple.pdf
then simple.pdf has changed from before
~~~

### Do typeset if output is older than functions

~~~scenario
given file simple.md
and file b.yaml
and file f.py
when I run sp-docgen simple.md -o simple.pdf
then file simple.pdf exists
when I remember the metadata for simple.pdf
and I touch f.py
and I run sp-docgen simple.md -o simple.pdf
then simple.pdf has changed from before
~~~

### Do typeset if output is older than bindings

~~~scenario
given file simple.md
and file b.yaml
and file f.py
when I run sp-docgen simple.md -o simple.pdf
then file simple.pdf exists
when I remember the metadata for simple.pdf
and I touch b.yaml
and I run sp-docgen simple.md -o simple.pdf
then simple.pdf has changed from before
~~~

## Document structure

Subplot uses chapters and sections to keep together scenario snippets
that form a complete scenario. The lowest level heading before a
snippet starts a scenario and is the name of the scenario. If there's
subheadings, they divide the description of the scenario into parts,
but don't start a new scenario. The next heading at the same or a
higher level starts a new scenario.

### Lowest level heading is name of scenario

~~~scenario
given file scenarioislowest.md
and file b.yaml
and file f.py
when I run sp-codegen --run scenarioislowest.md -o test.py
then scenario "heading 1.1.1" was run
and program finished successfully
~~~

~~~~{#scenarioislowest.md .file .markdown .numberLines}

---
title: Test scenario
bindings: b.yaml
functions: f.py
...

# heading 1
## heading 1.1
### heading 1.1.1

```scenario
given precondition foo
```
~~~~

### Subheadings don't start new scenario

~~~scenario
given file subisnotnewscenario.md
and file b.yaml
and file f.py
when I run sp-codegen --run subisnotnewscenario.md -o test.py
then scenario "heading 1.1a" was run
and program finished successfully
~~~

~~~~{#subisnotnewscenario.md .file .markdown .numberLines}

---
title: Test scenario
bindings: b.yaml
functions: f.py
...

# heading 1
## heading 1.1a

```scenario
given precondition foo
```

### heading 1.1.1
### heading 1.1.2

~~~~

### Next heading at same level starts new scenario

~~~scenario
given file samelevelisnewscenario.md
and file b.yaml
and file f.py
when I run sp-codegen --run samelevelisnewscenario.md -o test.py
then scenario "heading 1.1.1" was run
and scenario "heading 1.1.2" was run
and program finished successfully
~~~

~~~~{#samelevelisnewscenario.md .file .markdown .numberLines}

---
title: Test scenario
bindings: b.yaml
functions: f.py
...

# heading 1
## heading 1.1
### heading 1.1.1

```scenario
given precondition foo
```
### heading 1.1.2

```scenario
given precondition foo
```
~~~~


### Next heading at higher level starts new scenario

~~~scenario
given file higherisnewscenario.md
and file b.yaml
and file f.py
when I run sp-codegen --run higherisnewscenario.md -o test.py
then scenario "heading 1.1.1" was run
and scenario "heading 1.2" was run
and program finished successfully
~~~

~~~~{#higherisnewscenario.md .file .markdown .numberLines}

---
title: Test scenario
bindings: b.yaml
functions: f.py
...

# heading 1
## heading 1.1
### heading 1.1.1

```scenario
given precondition foo
```
## heading 1.2

```scenario
given precondition foo
```
~~~~


### Document titles

The document and code generators require a document title, because
it's a common user error to not have one, and Subplot should help make
good documents. The Pandoc filter, however, mustn't require a document
title, because it's used for things like formatting websites using
ikiwiki, and ikiwiki has a different way of specifying page titles.

#### Document generator gives an error if input document lacks title

~~~scenario
given file notitle.md
when I try to run sp-docgen notitle.md -o foo.md
then exit code is non-zero
~~~

~~~{#notitle.md .file .markdown .numberLines}
---
bindings: b.yaml
functions: f.py
...


# Introduction

This is a very simple Markdown file without a YAML metadata block,
and thus also no document title.

```scenario
given precondition foo
when I do bar
then bar was done
~~~

#### Code generator gives an error if input document lacks title

~~~scenario
given file notitle.md
when I try to run sp-codegen --run notitle.md -o test.py
then exit code is non-zero
~~~


## Running only chosen scenarios

To make the edit-test loop more convenient for the test programs
generated by Subplot, we allow the user to specify patterns for
scenarios to run. Default is to run all scenarios.

### Running only chosen scenarios with Python

This verifies that the generated Python test program can run only
chosen scenarios.

~~~scenario
given file twoscenarios-python.md
and file b.yaml
and file f.py
when I run sp-codegen twoscenarios-python.md -o test.py
and I run python3 test.py on
then scenario "One" was run
and scenario "Two" was not run
and program finished successfully
~~~

~~~{#twoscenarios-python.md .file .markdown .numberLines}
---
title: Test scenario
bindings: b.yaml
functions: f.py
...

# One

```scenario
given precondition foo
when I do bar
then bar was done
```

# Two

```scenario
given precondition foo
when I do bar
then bar was done
```
~~~

### Running only chosen scenarios with Bash

This verifies that the generated Bash test program can run only
chosen scenarios.

~~~scenario
given file twoscenarios-bash.md
and file b.yaml
and file f.sh
when I run sp-codegen twoscenarios-bash.md -o test.sh
and I run bash test.sh on
then scenario "One" was run
and scenario "Two" was not run
and program finished successfully
~~~


~~~{#twoscenarios-bash.md .file .markdown .numberLines}
---
title: Test scenario
bindings: b.yaml
functions: f.sh
template: bash
...

# One

```scenario
given precondition foo
when I do bar
then bar was done
```

# Two

```scenario
given precondition foo
when I do bar
then bar was done
```
~~~

~~~{#f.sh .file .bash .numberLines}
precond_foo() {
    ctx_set bar_none 0
    ctx_set foobar_none 0
}

do_bar() {
    ctx_set bar_done 1
}

do_foobar() {
    ctx_set foobar_done 1
}

bar_was_done() {
    actual="$(ctx_get bar_done)"
    assert_eq "$actual" 1
}

foobar_was_done() {
    actual="$(ctx_get foobar_done)"
    assert_eq "$actual" 1
}
~~~

## Document metadata

Some document metadata should end up in the typeset document,
especially the title, authors. The document date is more complicated,
to cater to different use cases:

* a work-in-progress document needs a new date for each revision
  - maintaining the `date` metadata field manually is quite tedious,
    so Subplot provides it automatically using the document source
    file modification time
  - some people would prefer a `git describe` or similar method for
    indicating the document revision, so Subplot allows the date to be
    specified via the command line
* a finished, reviewed, officiall stamped document needs a fixed date
  - Subplot allows this to be written as the `date` metadata field

The rules for what Subplot uses as the date or document revision
information are, then:

* if there is `date` metadata field, that is used
* otherwise, if the user gives the `--date` command line option, that
  is used
* otherwise, the markdown file's modification time is used

### Date given in metadata

This scenario tests that the `date` field in metadata is used if
specified.

~~~scenario
given file metadate.md
when I run sp-docgen metadate.md -o metadate.html
then file metadate.html exists
and file metadate.html contains "<title>The Fabulous Title</title>"
and file metadate.html contains "Alfred Pennyworth"
and file metadate.html contains "Geoffrey Butler"
and file metadate.html contains "WIP"
~~~

~~~{#metadate.md .file .markdown .numberLines}
---
title: The Fabulous Title
author:
- Alfred Pennyworth
- Geoffrey Butler
date: WIP
...
# Introduction
This is a test document. That's all.
~~~

### Date given on command line

This scenario tests that the `--date` command line option is used.

~~~scenario
given file dateless.md
when I run sp-docgen dateless.md -o dateoption.html --date=FANCYDATE
then file dateoption.html exists
and file dateoption.html contains "<title>The Fabulous Title</title>" 
and file dateoption.html contains "Alfred Pennyworth"
and file dateoption.html contains "Geoffrey Butler"
and file dateoption.html contains "FANCYDATE"
~~~

~~~{#dateless.md .file .markdown .numberLines}
---
title: The Fabulous Title
author:
- Alfred Pennyworth
- Geoffrey Butler
...
# Introduction
This is a test document. It has no date metadata.
~~~

### No date anywhere

This scenario tests the case of no metadata `date` and no command line
option, either. The date in the typeset document shall come from the
modification time of the input file, and shall have the date in ISO
8601 format, with time to the minute.

~~~scenario
given file dateless.md
and file dateless.md has modification time 2020-02-26 07:53:17
when I run sp-docgen dateless.md -o mtime.html
then file mtime.html exists
and file mtime.html contains "<title>The Fabulous Title</title>"
and file mtime.html contains "Alfred Pennyworth"
and file mtime.html contains "Geoffrey Butler"
and file mtime.html contains "2020-02-26 07:53"
~~~

### Missing bindings file

If a bindings file is missing, the error message should name the
missing file.

~~~scenario
given file missing-binding.md
when I try to run sp-docgen missing-binding.md -o foo.htmlh
then exit code is non-zero
and stderr matches /: missing-binding.yaml:/
~~~

~~~{#missing-binding.md .file .markdown .numberLines}
---
title: Missing binding
bindings: missing-binding.yaml
...
~~~

### Missing functions file

If a functions file is missing, the error message should name the
missing file.

~~~scenario
given file missing-functions.md
and file b.yaml
when I try to run sp-codegen --run missing-functions.md -o foo.py
then exit code is non-zero
and stderr matches /: missing-functions.py:/
~~~

~~~{#missing-functions.md .file .markdown .numberLines}
---
title: Missing functions
bindings: b.yaml
functions: missing-functions.py
...
~~~

### Extracting metadata from a document

The **sp-meta** program extracts metadata from a document. It is
useful to see the scenarios, for example. For example, given a
document like this:

sp-meta would extract this information from the **simple.md** example:

~~~
title: Test scenario
bindings: b.yaml
functions: f.py
scenario Simple
~~~

This scenario check sp-meta works. Note that it requires the bindings
or functions files.

~~~scenario
given file images.md
and file b.yaml
and file other.yaml
and file f.py
and file other.py
and file foo.bib
and file bar.bib
and file expected.json
when I run sp-meta images.md
then output matches /source: images.md/
and output matches /source: b.yaml/
and output matches /source: other.yaml/
and output matches /source: f.py/
and output matches /source: other.py/
and output matches /source: foo.bib/
and output matches /source: bar.bib/
and output matches /source: image.gif/
and output matches /bindings: b.yaml/
and output matches /bindings: other.yaml/
and output matches /functions: f.py/
when I run sp-meta images.md -o json
then JSON output matches expected.json
~~~


~~~{#images.md .file .markdown .numberLines}
---
title: Document refers to external images
bindings: 
- b.yaml
- other.yaml
functions: 
- f.py
- other.py
bibliography: [foo.bib, bar.bib]
...

![alt text](image.gif)
~~~

~~~{#other.yaml .file .yaml .numberLines}
[]
~~~

~~~{#other.py .file .python .numberLines}
~~~

~~~{#foo.bib .file .numberLines}
@book{foo2020,
 author    = "James Random",
 title     = "The Foo book",
 publisher = "The Internet",
 year      =  2020,
 address   = "World Wide Web",
}
~~~

~~~{#bar.bib .file .numberLines}
@book{foo2020,
 author    = "James Random",
 title     = "The Bar book",
 publisher = "The Internet",
 year      =  2020,
 address   = "World Wide Web",
}
~~~

~~~{#expected.json .file .json}
{
	"title": "Document refers to external images",
    "sources": [
	  "images.md",
	  "b.yaml",
	  "other.yaml",
	  "f.py",
	  "other.py",
	  "foo.bib",
	  "bar.bib",
	  "image.gif"
    ],
	"binding_files": [
	  "b.yaml",
	  "other.yaml"
	],
	"function_files": [
	  "f.py",
	  "other.py"
	],
	"bibliographies": [
	  "foo.bib",
	  "bar.bib"
	],
	"files": [],
	"scenarios": []
}
~~~


## Embedded files

Subplot allows data files to be embedded in the input document. This
is handy for small test files and the like.

Handling of a newline character on the last line is tricky. Pandoc
doesn't include a newline on the last line. Sometimes one is
needed&mdash;but sometimes it's not wanted. A newline can be added by
having an empty line at the end, but that is subtle and easy to miss.
Subplot helps the situation by allowing a `add-newline=` class to be added
to the code blocks, with one of three allowed cases:

* no `add-newline` class&mdash;default handling: same as `add-newline=auto`
* `add-newline=auto`&mdash;add a newline, if one isn't there
* `add-newline=no`&mdash;never add a newline, but keep one if it's there
* `add-newline=yes`&mdash;always add a newline, even if one is already
  there

The scenarios below test the various cases. 

### Extract embedded file

This scenario checks that an embedded file can be extracted, and used
in a subplot.

~~~scenario
given file embedded.md
when I run sp-docgen embedded.md -o foo.html
then file foo.html exists
and file foo.html matches /embedded\.txt/
~~~

~~~~~~~{#embedded.md .file .markdown .numberLines}
---
title: One embedded file
...

~~~{#embedded.txt .file}
This is the embedded file.
~~~
~~~~~~~


### Extract embedded file, by default add missing newline

This scenario checks the default handling: add a newline if one is
missing.

~~~scenario
given file default-without-newline.txt
then default-without-newline.txt ends in one newline
~~~

~~~{#default-without-newline.txt .file .numberLines}
This file does not end in a newline.
~~~


### Extract embedded file, by default do not add a second newline

This scenario checks the default handling: if content already ends in
a newline, do not add another newline.

~~~scenario
given file default-has-newline.txt
then default-has-newline.txt ends in one newline
~~~

~~~{#default-has-newline.txt .file .numberLines}
This file ends in a newline.

~~~

### Extract embedded file, automatically add missing newline

Explicitly request automatic newlines, when the file does not end in
one.

~~~scenario
given file auto-without-newline.txt
then auto-without-newline.txt ends in one newline
~~~

~~~{#auto-without-newline.txt .file add-newline=auto .numberLines}
This file does not end in a newline.
~~~


### Extract embedded file, do not automatically add second newline

Explicitly request automatic newlines, when the file already ends in
one.

~~~scenario
given file auto-has-newline.txt
then auto-has-newline.txt ends in one newline
~~~

~~~{#auto-has-newline.txt .file add-newline=auto .numberLines}
This file ends in a newline.

~~~


### Extract embedded file, explicitly add missing newline

Explicitly request automatic newlines, when the file doesn't end with
one.

~~~scenario
given file add-without-newline.txt
then add-without-newline.txt ends in one newline
~~~

~~~{#add-without-newline.txt .file add-newline=yes .numberLines}
This file does not end in a newline.
~~~


### Extract embedded file, explicitly add second newline

Explicitly request automatic newlines, when the file already ends with
one.

~~~scenario
given file add-has-newline.txt
then add-has-newline.txt ends in two newlines
~~~

~~~{#add-has-newline.txt .file add-newline=yes .numberLines}
This file ends in a newline.

~~~



### Extract embedded file, do not add missing newline

Explicitly ask for no newline to be added.

~~~scenario
given file no-adding-without-newline.txt
then no-adding-without-newline.txt does not end in a newline
~~~

~~~{#no-adding-without-newline.txt .file add-newline=no .numberLines}
This file does not end in a newline.
~~~


### Fail if the same filename is used twice

~~~scenario
given file onefiletwice.md
when I try to run sp-docgen onefiletwice.md -o onefiletwice.html
then exit code is non-zero
and file onefiletwice.html does not exist
~~~

~~~~{#onefiletwice.md .file .markdown .numberLines}
---
title: Two embedded files with the same name
...

```{#filename .file}
This is the embedded file.
```

```{#filename .file}
This is another embedded file, and has the same name.
```
~~~~


### Fail if two filenames only differ in case

~~~scenario
given file casediff.md
when I try to run sp-docgen casediff.md -o casediff.html
then exit code is non-zero
and file casediff.html does not exist
~~~

~~~~{#casediff.md .file .markdown .numberLines}
---
title: Two embedded files with names differing only in case
...

```{#filename .file}
This is the embedded file.
```

```{#FILENAME .file}
This is another embedded file, and has the same name in uppercase.
```
~~~~

## Steps must match bindings

Subplot permits the binding author to define arbitrarily complex regular
expressions for binding matches.  In order to ensure that associating steps
to bindings is both reliable and tractable, a step must match _exactly one_
binding.

```{#badbindings.yaml .file .yaml}
- given: a binding
  function: a_binding
- given: a (?:broken)? binding
  function: a_broken_binding
  regex: true
- given: a capitalised Binding
  function: os.getcwd
  case_sensitive: true
```

### Steps which do not match bindings do not work

~~~~{#nobinding.md .file .markdown}
---
title: No bindings available
bindings:
- badbindings.yaml
...
# Broken scenario because step has no binding

```scenario
given a missing binding
then nothing works
```
~~~~

```scenario
given file nobinding.md
and file badbindings.yaml
when I try to run sp-codegen --run nobinding.md -o test.py
then exit code is non-zero
```

### Steps which do not case-sensitively match sensitive bindings do not work

~~~~{#casemismatch.md .file .markdown}
---
title: Case sensitivity mismatch
bindings:
- badbindings.yaml
...
# Broken scenario because step has a case mismatch with sensitive binding

```scenario
given a capitalised binding
```
~~~~

```scenario
given file casemismatch.md
and file badbindings.yaml
when I try to run sp-codegen --run casemismatch.md -o test.py
then exit code is non-zero
```

### Steps which match more than one binding do not work

~~~~{#twobindings.md .file .markdown}
---
title: Two bindings match
bindings:
- badbindings.yaml
...
# Broken scenario because step has two possible bindings

```scenario
given a binding
```
~~~~

```scenario
given file twobindings.md
and file badbindings.yaml
when I try to run sp-codegen --run twobindings.md -o test.py
then exit code is non-zero
```


### List embedded files

The `sp-meta` command lists embedded files in its output.

~~~scenario
given file two-embedded.md
when I run sp-meta two-embedded.md
then output matches /foo.txt/
and output matches /bar.yaml/
~~~

~~~~~~{#two-embedded.md .file .markdown .numberLines}
---
title: Two embedded files
...

~~~{#foo.txt .file}
~~~

~~~{#bar.yaml. .file}
~~~
~~~~~~


## Embedded graphs

Subplot allows embedding markup to generate graphs into the Markdown document.

### Dot

[Graphviz]: http://www.graphviz.org/

Dot is a program from the [Graphviz][] suite to generate directed
graphs, such as this one.

~~~dot
digraph "example" {
thing -> other
}
~~~

The scenario checks that a graph is generated and embedded into the
HTML output, not referenced as an external image.

~~~scenario
given file dot.md
and file b.yaml
when I run pandoc --filter sp-filter dot.md -o dot.html
then file dot.html matches /img src="data:image/svg\+xml;base64,/
~~~

The sample input file **dot.md**:

~~~~~~~~{#dot.md .file .markdown .numberLines}
This is an example Markdown file, which embeds a graph using dot markup.

~~~dot
digraph "example" {
thing -> other
}
~~~
~~~~~~~~



### PlantUML

[PlantUML]: https://plantuml.com/

[PlantUML][] is a program to generate various kinds of graphs for
describing software, such as this one:

~~~plantuml
@startuml
Alice -> Bob: Authentication Request
Bob --> Alice: Authentication Response

Alice -> Bob: Another authentication Request
Alice <-- Bob: Another authentication Response
@enduml
~~~

The scenario below checks that a graph is generated and embedded into
the HTML output, not referenced as an external image.

~~~scenario
given file plantuml.md
and file b.yaml
when I run pandoc --filter sp-filter plantuml.md -o plantuml.html
then file plantuml.html matches /img src="data:image/svg\+xml;base64,/
~~~

The sample input file **plantuml.md**:

~~~~~~~~{#plantuml.md .file .markdown .numberLines}
This is an example Markdown file, which embeds a graph using
PlantUML markup.

~~~plantuml
@startuml
Alice -> Bob: Authentication Request
Bob --> Alice: Authentication Response

Alice -> Bob: Another authentication Request
Alice <-- Bob: Another authentication Response
@enduml
~~~
~~~~~~~~


### Roadmap

Subplot supports visual roadmaps using a YAML based markup language,
implemnted by the [roadmap][] Rust library. The library converts the
roadmap into dot, and that gets rendered as SVG and embedded in the
output document by Subplot.

An example:

~~~roadmap
goal:
  label: |
    This is the end goal:
    if we reach here, there
    is nothing more to be
    done in the project
  depends:
  - finished
  - blocked

finished:
  status: finished
  label: |
    This task is finished;
    the arrow indicates what
    follows this task (unless
    it's blocked)

ready:
  status: ready
  label: |
    This task is ready 
    to be done: it is not
    blocked by anything

next:
  status: next
  label: |
    This task is chosen 
    to be done next

blocked:
  status: blocked
  label: |
    This task is blocked
    and can't be done until
    something happens
  depends:
  - ready
  - next
~~~

This scenario checks that a graph is generated and embedded into the
HTML output, not referenced as an external image.

~~~scenario
given file roadmap.md
and file b.yaml
when I run pandoc --filter sp-filter roadmap.md -o roadmap.html
then file roadmap.html matches /img src="data:image/svg\+xml;base64,/
~~~

The sample input file **roadmap.md**:

~~~~~~~~{#roadmap.md .file .markdown .numberLines}
This is an example Markdown file, which embeds a roadmap.

~~~roadmap
goal:
  label: |
    This is the end goal:
    if we reach here, there
    is nothing more to be
    done in the project
  depends:
  - finished
  - blocked

finished:
  status: finished
  label: |
    This task is finished;
    the arrow indicates what
    follows this task (unless
    it's blocked)

ready:
  status: ready
  label: |
    This task is ready 
    to be done: it is not
    blocked by anything

next:
  status: next
  label: |
    This task is chosen 
    to be done next

blocked:
  status: blocked
  label: |
    This task is blocked
    and can't be done until
    something happens
  depends:
  - ready
  - next
~~~
~~~~~~~~


### Class name validation

When Subplot loads a document it will validate that the block classes
match a known set.  Subplot has a built-in set which it treats as special,
and it knows some pandoc-specific classes and a number of file type classes.

If the author of a document wishes to use additional class names then they can
include a `classes` list in the document metadata which subplot will treat
as valid.

~~~scenario
given file unknown-class-name.md
and file known-class-name.md
and file b.yaml
when I try to run sp-docgen unknown-class-name.md -o unknown-class-name.html
then exit code is non-zero
and file unknown-class-name.html does not exist
and stderr matches /Unknown classes found in the document: foobar/
when I run sp-docgen known-class-name.md -o known-class-name.html
then file known-class-name.html exists
~~~

~~~~~~~~{#unknown-class-name.md .file .markdown .numberLines}
---
title: A document with an unknown class name
...

```foobar
This content is foobarish
```

~~~~~~~~

~~~~~~~~{#known-class-name.md .file .markdown .numberLines}
---
title: A document with a previously unknown class name
classes:
- foobar
...

```foobar
This content is foobarish
```

~~~~~~~~

## Using as a Pandoc filter

Subplot can be used as a Pandoc _filter_, which means Pandoc can allow
Subplot to modify the document while it is being converted or typeset.
This can useful in a variety of ways, such as when using Pandoc to
improve Markdown processing in the [ikiwiki][] blog engine.

[ikiwiki]: http://ikiwiki.info/

The way filters work is that Pandoc parses the input document into an
abstract syntax tree, serializes that into JSON, gives that to the
filter (via the standard input), gets a modified abstract syntax tree
(again as JSON, via the filter's standard output).

Subplot supports this via the **sp-filter** executable. It is built
using the same internal logic as Subplot's docgen. The interface is
merely different to be usable as a Pandoc filter.

This scenarios verifies that the filter works at all. More
importantly, it does that by feeding the filter a Markdown file that
does not have a YAML metadata block. For the ikiwiki use case, that's
what the input files are like.

~~~scenario
given file justdata.md
when I run pandoc --filter sp-filter justdata.md -o justdata.html
then file justdata.html matches /does not have a YAML metadata/
~~~

The input file **justdata.md**:

~~~~~~~~{#justdata.md .file .markdown .numberLines}
This is an example Markdown file.
It does not have a YAML metadata block.
~~~~~~~~


# Extract embedded files

`sp-extract` extracts embedded files from a subplot file.

~~~scenario
given file embedded-file.md
and file expected.txt
when I run sp-extract embedded-file.md foo.txt -d .
then files foo.txt and expected.txt match
~~~

~~~~~~{#embedded-file.md .file .markdown .numberLines}
---
title: Embedded file
...

~~~{#foo.txt .file}
This is a test file.
~~~

~~~~~~

~~~{#expected.txt .file}
This is a test file.
~~~




---
title: "Subplot"
author: The Subplot project
bindings: 
- subplot.yaml
- runcmd.yaml
- files.yaml
functions: 
- subplot.py
- runcmd.py
- files.py
classes:
- json
...