File: test_Instr.py

package info (click to toggle)
python-mcstasscript 0.0.46%2Bgit20250402111921.bfa5a26-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,440 kB
  • sloc: python: 13,421; makefile: 14
file content (2519 lines) | stat: -rw-r--r-- 97,275 bytes parent folder | download
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
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
import os
import os.path
import io
import unittest
import unittest.mock
import datetime

from libpyvinyl.Parameters.Collections import CalculatorParameters

from mcstasscript.interface.instr import McStas_instr
from mcstasscript.interface.instr import McXtrace_instr
from mcstasscript.helper.formatting import bcolors
from mcstasscript.tests.helpers_for_tests import WorkInTestDir
from mcstasscript.helper.exceptions import McStasError
from mcstasscript.helper.mcstas_objects import Component
from mcstasscript.helper.beam_dump_database import BeamDump

run_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '.')

class DummyComponent(Component):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def set_parameters(self, *args, **kwargs):
        pass

def setup_instr_no_path():
    """
    Sets up a neutron instrument without a package_path
    """

    with WorkInTestDir() as handler:
        instrument = McStas_instr("test_instrument")

    return instrument


def setup_x_ray_instr_no_path():
    """
    Sets up a X-ray instrument without a package_path
    """

    with WorkInTestDir() as handler:
        instrument = McXtrace_instr("test_instrument")

    return instrument


def setup_instr_root_path():
    """
    Sets up a neutron instrument with root package_path
    """
    with WorkInTestDir() as handler:
        instrument = McStas_instr("test_instrument", package_path="/")

    return instrument


def setup_x_ray_instr_root_path():
    """
    Sets up a X-ray instrument with root package_path
    """
    with WorkInTestDir() as handler:
        instrument = McXtrace_instr("test_instrument", package_path="/")

    return instrument


def setup_instr_with_path():
    """
    Sets up an instrument with a valid package_path, but it points to
    the dummy installation in the test folder.
    """

    with WorkInTestDir() as handler:
        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        dummy_path = os.path.join(THIS_DIR, "dummy_mcstas")
        instrument = McStas_instr("test_instrument",
                                  package_path=dummy_path, executable_path=dummy_path)

    return instrument


def setup_x_ray_instr_with_path():
    """
    Sets up an instrument with a valid package_path, but it points to
    the dummy installation in the test folder.
    """

    THIS_DIR = os.path.dirname(os.path.abspath(__file__))
    dummy_path = os.path.join(THIS_DIR, "dummy_mcstas")

    with WorkInTestDir() as handler:
        instrument = McXtrace_instr("test_instrument", package_path=dummy_path)

    return instrument


def setup_instr_with_input_path():
    """
    Sets up an instrument with a valid package_path, but it points to
    the dummy installation in the test folder. In addition the input_path
    is set to a folder in the test directory using an absolute path.
    """

    THIS_DIR = os.path.dirname(os.path.abspath(__file__))
    dummy_path = os.path.join(THIS_DIR, "dummy_mcstas")
    input_path = os.path.join(THIS_DIR, "test_input_folder")

    with WorkInTestDir() as handler:
        instrument = McStas_instr("test_instrument",
                                  package_path=dummy_path,
                                  input_path=input_path)

    return instrument


def setup_instr_with_input_path_relative():
    """
    Sets up an instrument with a valid package_path, but it points to
    the dummy installation in the test folder. In addition the input_path
    is set to a folder in the test directory using a relative path.
    """

    with WorkInTestDir() as handler:
        instrument = McStas_instr("test_instrument",
                                  package_path="dummy_mcstas",
                                  input_path="test_input_folder")

    return instrument


def setup_populated_instr():
    """
    Sets up a neutron instrument with some features used and three components
    """
    instr = setup_instr_root_path()

    instr.add_parameter("double", "theta")
    instr.add_parameter("double", "has_default", value=37)
    instr.add_declare_var("double", "two_theta")
    instr.append_initialize("two_theta = 2.0*theta;")

    instr.add_component("first_component", "test_for_reading")
    instr.add_component("second_component", "test_for_reading")
    instr.add_component("third_component", "test_for_reading")

    return instr


def setup_populated_instr_with_dummy_MCPL_comps():
    """
    Sets up a neutron instrument with some features used and three components
    """
    instr = setup_populated_instr()

    instr.component_class_lib["MCPL_input"] = DummyComponent
    instr.component_class_lib["MCPL_output"] = DummyComponent

    return instr

def setup_populated_instr_with_dummy_path():
    """
    Sets up a neutron instrument with some features used and three components

    Here uses the dummy mcstas installation as path and sets required
    parameters so that a run is possible.
    """
    instr = setup_instr_with_path()

    instr.add_parameter("double", "theta")
    instr.add_parameter("double", "has_default", value=37)
    instr.add_declare_var("double", "two_theta")
    instr.append_initialize("two_theta = 2.0*theta;")

    comp1 = instr.add_component("first_component", "test_for_reading")
    comp1.gauss = 1.2
    comp1.test_string = "a_string"
    comp2 = instr.add_component("second_component", "test_for_reading")
    comp2.gauss = 1.4
    comp2.test_string = "b_string"
    comp3 = instr.add_component("third_component", "test_for_reading")
    comp3.gauss = 1.6
    comp3.test_string = "c_string"

    return instr


def setup_populated_x_ray_instr():
    """
    Sets up a X-ray instrument with some features used and three components
    """
    instr = setup_x_ray_instr_root_path()

    instr.add_parameter("double", "theta")
    instr.add_parameter("double", "has_default", value=37)
    instr.add_declare_var("double", "two_theta")
    instr.append_initialize("two_theta = 2.0*theta;")

    instr.add_component("first_component", "test_for_reading")
    instr.add_component("second_component", "test_for_reading")
    instr.add_component("third_component", "test_for_reading")

    return instr


def setup_populated_x_ray_instr_with_dummy_path():
    """
    Sets up a x-ray instrument with some features used and three components

    Here uses the dummy mcstas installation as path and sets required
    parameters so that a run is possible.
    """
    instr = setup_x_ray_instr_with_path()

    instr.add_parameter("double", "theta")
    instr.add_parameter("double", "has_default", value=37)
    instr.add_declare_var("double", "two_theta")
    instr.append_initialize("two_theta = 2.0*theta;")

    comp1 = instr.add_component("first_component", "test_for_reading")
    comp1.gauss = 1.2
    comp1.test_string = "a_string"
    comp2 = instr.add_component("second_component", "test_for_reading")
    comp2.gauss = 1.4
    comp2.test_string = "b_string"
    comp3 = instr.add_component("third_component", "test_for_reading")
    comp3.gauss = 1.6
    comp3.test_string = "c_string"

    return instr


def setup_populated_with_some_options_instr():
    """
    Sets up a neutron instrument with some features used and two components
    """
    instr = setup_instr_root_path()

    instr.add_parameter("double", "theta")
    instr.add_parameter("double", "has_default", value=37)
    instr.add_declare_var("double", "two_theta")
    instr.append_initialize("two_theta = 2.0*theta;")

    comp1 = instr.add_component("first_component", "test_for_reading")
    comp1.set_AT([0, 0, 1])
    comp1.set_GROUP("Starters")
    comp2 = instr.add_component("second_component", "test_for_reading")
    comp2.set_AT([0, 0, 2], RELATIVE="first_component")
    comp2.set_ROTATED([0, 30, 0])
    comp2.set_WHEN("1==1")
    comp2.yheight = 1.23
    instr.add_component("third_component", "test_for_reading")

    return instr


def insert_mock_dump(instr, component_name, run_name="Run", tag=0):
    dump = BeamDump("", {}, component_name, run_name, tag=tag)
    dump.file_present = lambda *_: True  # Overwrite file check

    instr.dump_database.data[component_name] = {}
    instr.dump_database.data[component_name][run_name] = {}
    instr.dump_database.data[component_name][run_name][tag] = dump


class TestMcStas_instr(unittest.TestCase):
    """
    Tests of the main class in McStasScript called McStas_instr.
    """

    def test_simple_initialize(self):
        """
        Test basic initialization runs
        """
        my_instrument = setup_instr_root_path()

        self.assertEqual(my_instrument.name, "test_instrument")

    def test_complex_initialize(self):
        """
        Tests all keywords work in initialization
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        current_work_dir = os.getcwd()
        os.chdir(THIS_DIR)  # Set work directory to test folder

        my_instrument = McStas_instr("test_instrument",
                                     author="Mads",
                                     origin="DMSC",
                                     executable_path="./dummy_mcstas/contrib",
                                     package_path="./dummy_mcstas/misc")

        os.chdir(current_work_dir)

        self.assertEqual(my_instrument.author, "Mads")
        self.assertEqual(my_instrument.origin, "DMSC")
        self.assertEqual(my_instrument._run_settings["executable_path"],
                         "./dummy_mcstas/contrib")
        self.assertEqual(my_instrument._run_settings["package_path"],
                         "./dummy_mcstas/misc")

    def test_load_config_file(self):
        """
        Test that configuration file is read correctly. In order to have
        an independent test, the yaml file is read manually instead of
        using the yaml package.
        """
        # Load configuration file and read manually
        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        configuration_file_name = os.path.join(THIS_DIR,
                                               "..", "configuration.yaml")

        if not os.path.isfile(configuration_file_name):
            raise NameError("Could not find configuration file!")

        f = open(configuration_file_name, "r")

        lines = f.readlines()
        for line in lines:
            line = line.strip()
            if line.startswith("mcrun_path:"):
                parts = line.split(" ")
                correct_mcrun_path = parts[1]

            if line.startswith("mcstas_path:"):
                parts = line.split(" ")
                correct_mcstas_path = parts[1]

            if line.startswith("characters_per_line:"):
                parts = line.split(" ")
                correct_n_of_characters = int(parts[1])

        f.close()

        # Check the value matches what is loaded by initialization
        my_instrument = setup_instr_no_path()

        self.assertEqual(my_instrument._run_settings["executable_path"], correct_mcrun_path)
        self.assertEqual(my_instrument._run_settings["package_path"], correct_mcstas_path)
        self.assertEqual(my_instrument.line_limit, correct_n_of_characters)

    def test_load_config_file_x_ray(self):
        """
        Test that configuration file is read correctly. In order to have
        an independent test, the yaml file is read manually instead of
        using the yaml package.
        """
        # Load configuration file and read manually
        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        configuration_file_name = os.path.join(THIS_DIR,
                                               "..", "configuration.yaml")

        if not os.path.isfile(configuration_file_name):
            raise NameError("Could not find configuration file!")

        f = open(configuration_file_name, "r")

        lines = f.readlines()
        for line in lines:
            line = line.strip()
            if line.startswith("mxrun_path:"):
                parts = line.split(" ")
                correct_mxrun_path = parts[1]

            if line.startswith("mcxtrace_path:"):
                parts = line.split(" ")
                correct_mcxtrace_path = parts[1]

            if line.startswith("characters_per_line:"):
                parts = line.split(" ")
                correct_n_of_characters = int(parts[1])

        f.close()

        # Check the value matches what is loaded by initialization
        my_instrument = setup_x_ray_instr_no_path()

        self.assertEqual(my_instrument._run_settings["executable_path"], correct_mxrun_path)
        self.assertEqual(my_instrument._run_settings["package_path"], correct_mcxtrace_path)
        self.assertEqual(my_instrument.line_limit, correct_n_of_characters)

    def test_load_libpyvinyl_parameters(self):
        parameters = CalculatorParameters()
        int_par = parameters.new_parameter("int_parameter", comment="integer parameter")
        int_par.value = 3

        double_par = parameters.new_parameter("double_parameter", unit="meV")
        double_par.value = 3.0

        string_par = parameters.new_parameter("string_parameter")
        string_par.value = "hello world"

        secret_par = parameters.new_parameter("no_value_par")

        instr = McStas_instr("test_instr", parameters=parameters)

        self.assertEqual(int_par.type, "double")
        self.assertEqual(double_par.type, "double")
        self.assertEqual(string_par.type, "string")
        self.assertEqual(secret_par.type, None)

        instr.set_parameters(int_parameter=4)
        self.assertEqual(int_par.value, 4)

        int_par.value = 5
        self.assertEqual(instr.parameters["int_parameter"].value, 5)

    def test_simple_add_parameter(self):
        """
        This is just an interface to a function that is tested
        elsewhere, so only a basic test is performed here.

        ParameterVariable is tested in test_parameter_variable.
        """
        instr = setup_instr_root_path()

        parameter = instr.add_parameter("double", "theta", comment="test par")

        self.assertEqual(parameter.name, "theta")
        self.assertEqual(parameter.comment, "test par")
        self.assertTrue(parameter in instr.parameters.parameters.values())

    def test_user_var_block_add_parameter(self):
        """
        Checks that adding a parameter with a name already used for a
        user variable fails with NameError
        """
        instr = setup_instr_root_path()

        instr.add_user_var("double", "theta")

        with self.assertRaises(NameError):
            instr.add_parameter("double", "theta", comment="test par")


    def test_declare_var_block_add_parameter(self):
        """
        Checks that adding a parameter with a name already used for a
        declared variable fails with NameError
        """
        instr = setup_instr_root_path()

        instr.add_declare_var("double", "theta")

        with self.assertRaises(NameError):
            instr.add_parameter("double", "theta", comment="test par")

    def test_infer_name_add_parameter(self):
        """
        Test that name can be ommited when defining a parameter and that
        the python variable name is used in its place.
        """
        instr = setup_instr_root_path()

        theta = instr.add_parameter(type="double", comment="test par")

        self.assertEqual(theta.name, "theta")
        self.assertEqual(theta.comment, "test par")
        self.assertTrue(theta in instr.parameters.parameters.values())

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_show_parameters(self, mock_stdout):
        """
        Testing that parameters are displayed correctly
        """
        instr = setup_instr_root_path()

        instr.add_parameter("theta", comment="test par")
        instr.add_parameter("double", "par_double", comment="test par")
        instr.add_parameter("int", "int_par", value=8, comment="test par")
        instr.add_parameter("int", "slits", comment="test par")
        instr.add_parameter("string", "ref",
                            value="string", comment="new string")

        instr.show_parameters(line_length=300)

        output = mock_stdout.getvalue().split("\n")

        self.assertEqual(output[0], "       theta                 // test par")
        self.assertEqual(output[1], "double par_double            // test par")
        self.assertEqual(output[2], "int    int_par     = 8       // test par")
        self.assertEqual(output[3], "int    slits                 // test par")
        self.assertEqual(output[4], "string ref         = string  // new string")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_show_parameters_line_break(self, mock_stdout):
        """
        Testing that parameters are displayed correctly

        Here multiple lines are used for a long comment that was
        dynamically broken up.
        """
        instr = setup_instr_root_path()

        instr.add_parameter("theta", comment="test par")
        instr.add_parameter("double", "par_double", comment="test par")
        instr.add_parameter("int", "int_par", value=8, comment="test par")
        instr.add_parameter("int", "slits", comment="test par")
        instr.add_parameter("string", "ref",
                            value="string", comment="new string")

        longest_comment = ("This is a very long comment meant for "
                           + "testing the dynamic line breaking "
                           + "that is used in this method. It needs "
                           + "to have many lines in order to ensure "
                           + "it really works.")

        instr.add_parameter("double", "value",
                            value="37", comment=longest_comment)

        instr.show_parameters(line_length=80)

        output = mock_stdout.getvalue().split("\n")

        self.assertEqual(output[0], "       theta                 // test par")
        self.assertEqual(output[1], "double par_double            // test par")
        self.assertEqual(output[2], "int    int_par     = 8       // test par")
        self.assertEqual(output[3], "int    slits                 // test par")
        self.assertEqual(output[4], "string ref         = string  // new string")
        comment_line = "This is a very long comment meant for "
        self.assertEqual(output[5], "double value       = 37      // "
                                    + comment_line)
        comment_line = "testing the dynamic line breaking that is "
        self.assertEqual(output[6], " "*33 + comment_line)
        comment_line = "used in this method. It needs to have many "
        self.assertEqual(output[7], " "*33 + comment_line)
        comment_line = "lines in order to ensure it really works. "
        self.assertEqual(output[8], " "*33 + comment_line)

    def test_simple_add_declare_variable(self):
        """
        This is just an interface to a function that is tested
        elsewhere, so only a basic test is performed here.

        DeclareVariable is tested in test_declare_variable.
        """
        instr = setup_instr_root_path()

        instr.add_declare_var("double", "two_theta", comment="test par")

        self.assertEqual(instr.declare_list[0].name, "two_theta")
        self.assertEqual(instr.declare_list[0].comment, " // test par")

    def test_parameter_block_add_declare_variable(self):
        """
        Checks a NameError is raised when using declare variable of same
        name as instrument parameter.
        """
        instr = setup_instr_root_path()

        instr.add_parameter("two_theta")
        with self.assertRaises(NameError):
            instr.add_declare_var("double", "two_theta")

    def test_user_var_block_add_declare_variable(self):
        """
        Checks a NameError is raised when using declare variable of same
        name as declared variable.
        """
        instr = setup_instr_root_path()

        instr.add_user_var("double", "two_theta")
        with self.assertRaises(NameError):
            instr.add_declare_var("double", "two_theta")

    def test_infer_add_declare_variable(self):
        """
        Check that name can be inferred from python variable when
        adding a declared variable.
        """
        instr = setup_instr_root_path()

        two_theta = instr.add_declare_var("double", comment="test par")

        self.assertEqual(instr.declare_list[0].name, "two_theta")
        self.assertEqual(instr.declare_list[0].comment, " // test par")

    def test_simple_add_user_variable(self):
        """
        This is just an interface to a function that is tested
        elsewhere, so only a basic test is performed here.

        DeclareVariable is tested in test_declare_variable.
        """
        instr = setup_instr_root_path()

        user_var = instr.add_user_var("double", "two_theta_user", comment="test par")

        self.assertEqual(user_var.name, "two_theta_user")
        self.assertEqual(user_var.comment, " // test par")
        self.assertEqual(instr.user_var_list[0].name, "two_theta_user")
        self.assertEqual(instr.user_var_list[0].comment, " // test par")

        with self.assertRaises(ValueError):
            instr.add_user_var("double", "illegal", value=8)

    def test_declare_block_add_user_variable(self):
        """
        Checks a NameError is raised when using user variable of same
        name as declare variable already defined.
        """
        instr = setup_instr_root_path()

        instr.add_declare_var("double", "two_theta")
        with self.assertRaises(NameError):
            instr.add_user_var("double", "two_theta")

    def test_parameter_block_add_user_variable(self):
        """
        Checks a NameError is raised when using user variable of same
        name as parameter already defined.
        """
        instr = setup_instr_root_path()

        instr.add_parameter("two_theta")
        with self.assertRaises(NameError):
            instr.add_user_var("double", "two_theta")

    def test_simple_append_declare(self):
        """
        Appending to declare adds an object to the declare list, and the
        allowed types are either strings or DeclareVariable objects.
        Here only strings are added.
        """
        instr = setup_instr_root_path()

        instr.append_declare("First line of declare")
        instr.append_declare("Second line of declare")
        instr.append_declare("Third line of declare")

        self.assertEqual(instr.declare_list[0],
                         "First line of declare")
        self.assertEqual(instr.declare_list[1],
                         "Second line of declare")
        self.assertEqual(instr.declare_list[2],
                         "Third line of declare")

    def test_simple_append_declare_var_mix(self):
        """
        Appending to declare adds an object to the declare list, and the
        allowed types are either strings or DeclareVariable objects.
        Here a mix of strings and DeclareVariable objects are added.
        """
        instr = setup_instr_root_path()

        instr.append_declare("First line of declare")
        instr.add_declare_var("double", "two_theta", comment="test par")
        instr.append_declare("Third line of declare")

        self.assertEqual(instr.declare_list[0],
                         "First line of declare")
        self.assertEqual(instr.declare_list[1].name, "two_theta")
        self.assertEqual(instr.declare_list[1].comment, " // test par")
        self.assertEqual(instr.declare_list[2],
                         "Third line of declare")

    def test_simple_append_initialize(self):
        """
        The initialize section is held as a string. This method
        appends that string.
        """
        instr = setup_instr_root_path()

        self.assertEqual(instr.initialize_section,
                         "// Start of initialize for generated "
                         + "test_instrument\n")

        instr.append_initialize("First line of initialize")
        instr.append_initialize("Second line of initialize")
        instr.append_initialize("Third line of initialize")

        self.assertEqual(instr.initialize_section,
                         "// Start of initialize for generated "
                         + "test_instrument\n"
                         + "First line of initialize\n"
                         + "Second line of initialize\n"
                         + "Third line of initialize\n")

    def test_simple_append_initialize_no_new_line(self):
        """
        The initialize section is held as a string. This method
        appends that string without making a new line.
        """
        instr = setup_instr_root_path()

        self.assertEqual(instr.initialize_section,
                         "// Start of initialize for generated "
                         + "test_instrument\n")

        instr.append_initialize_no_new_line("A")
        instr.append_initialize_no_new_line("B")
        instr.append_initialize_no_new_line("CD")

        self.assertEqual(instr.initialize_section,
                         "// Start of initialize for generated "
                         + "test_instrument\n"
                         + "ABCD")

    def test_simple_append_finally(self):
        """
        The finally section is held as a string. This method
        appends that string.
        """
        instr = setup_instr_root_path()

        self.assertEqual(instr.finally_section,
                         "// Start of finally for generated "
                         + "test_instrument\n")

        instr.append_finally("First line of finally")
        instr.append_finally("Second line of finally")
        instr.append_finally("Third line of finally")

        self.assertEqual(instr.finally_section,
                         "// Start of finally for generated "
                         + "test_instrument\n"
                         + "First line of finally\n"
                         + "Second line of finally\n"
                         + "Third line of finally\n")

    def test_simple_append_finally_no_new_line(self):
        """
        The finally section is held as a string. This method
        appends that string without making a new line.
        """
        instr = setup_instr_root_path()

        self.assertEqual(instr.finally_section,
                         "// Start of finally for generated "
                         + "test_instrument\n")

        instr.append_finally_no_new_line("A")
        instr.append_finally_no_new_line("B")
        instr.append_finally_no_new_line("CD")

        self.assertEqual(instr.finally_section,
                         "// Start of finally for generated "
                         + "test_instrument\n"
                         + "ABCD")

    def test_simple_append_trace(self):
        """
        The trace section is held as a string. This method
        appends that string. Only used for writing c files, which is not
        the main way to use McStasScript.
        """
        instr = setup_instr_root_path()

        self.assertEqual(instr.trace_section,
                         "// Start of trace section for generated "
                         + "test_instrument\n")

        instr.append_trace("First line of trace")
        instr.append_trace("Second line of trace")
        instr.append_trace("Third line of trace")

        self.assertEqual(instr.trace_section,
                         "// Start of trace section for generated "
                         + "test_instrument\n"
                         + "First line of trace\n"
                         + "Second line of trace\n"
                         + "Third line of trace\n")

    def test_simple_append_trace_no_new_line(self):
        """
        The trace section is held as a string. This method appends that string
        without making a new line. Only used for writing c files, which is not
        the main way to use McStasScript.
        """
        instr = setup_instr_root_path()

        self.assertEqual(instr.trace_section,
                         "// Start of trace section for generated "
                         + "test_instrument\n")

        instr.append_trace_no_new_line("A")
        instr.append_trace_no_new_line("B")
        instr.append_trace_no_new_line("CD")

        self.assertEqual(instr.trace_section,
                         "// Start of trace section for generated "
                         + "test_instrument\n"
                         + "ABCD")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_available_components_simple(self, mock_stdout):
        """
        Simple test of show components to show component categories
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))

        current_work_dir = os.getcwd()
        os.chdir(THIS_DIR)  # Set work directory to test folder

        instr = setup_instr_with_path()

        instr.available_components()

        os.chdir(current_work_dir)

        output = mock_stdout.getvalue()
        output = output.split("\n")

        self.assertEqual(output[0],
                         "The following components are found in the "
                         + "work directory / input_path:")
        self.assertEqual(output[1], "     test_for_reading.comp")
        self.assertEqual(output[2], "These definitions will be used "
                         + "instead of the installed versions.")
        self.assertEqual(output[3],
                         "Here are the available component categories:")
        self.assertEqual(output[4], " misc")
        self.assertEqual(output[5], " sources")
        self.assertEqual(output[6], " work directory")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_available_components_folder(self, mock_stdout):
        """
        Simple test of show components to show components in current work
        directory.
        """
        instr = setup_instr_with_path()

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))

        current_work_dir = os.getcwd()
        os.chdir(THIS_DIR)  # Set work directory to test folder

        instr.available_components("work directory")

        os.chdir(current_work_dir)

        output = mock_stdout.getvalue()
        output = output.split("\n")

        self.assertEqual(output[0],
                         "The following components are found in the "
                         + "work directory / input_path:")
        self.assertEqual(output[1], "     test_for_reading.comp")
        self.assertEqual(output[2], "These definitions will be used "
                         + "instead of the installed versions.")
        self.assertEqual(output[3],
                         "Here are all components in the work directory "
                         + "category.")
        self.assertEqual(output[4], " test_for_reading")
        self.assertEqual(output[5], "")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_available_components_input_path_simple(self, mock_stdout):
        """
        Simple test of input_path being recognized and passed
        to component_reader so PSDlin_monitor is overwritten
        """
        instr = setup_instr_with_input_path()

        instr.available_components()

        output = mock_stdout.getvalue()
        output = output.split("\n")

        self.assertEqual(output[0],
                         "The following components are found in the "
                         + "work directory / input_path:")
        self.assertEqual(output[1], "     test_for_structure.comp")
        self.assertEqual(output[2], "These definitions will be used "
                         + "instead of the installed versions.")
        self.assertEqual(output[3],
                         "Here are the available component categories:")
        self.assertEqual(output[4], " misc")
        self.assertEqual(output[5], " sources")
        self.assertEqual(output[6], " work directory")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_available_components_input_path_custom(self, mock_stdout):
        """
        Simple test of input_path being recognized and passed
        to component_reader so PSDlin_monitor is overwritten
        Here dummy_mcstas and input_path are set using relative
        paths instead of absolute paths.
        """
        instr = setup_instr_with_input_path_relative()

        instr.available_components()

        output = mock_stdout.getvalue()
        output = output.split("\n")

        self.assertEqual(output[0],
                         "The following components are found in the "
                         + "work directory / input_path:")
        self.assertEqual(output[1], "     test_for_structure.comp")
        self.assertEqual(output[2], "These definitions will be used "
                         + "instead of the installed versions.")
        self.assertEqual(output[3],
                         "Here are the available component categories:")
        self.assertEqual(output[4], " misc")
        self.assertEqual(output[5], " sources")
        self.assertEqual(output[6], " work directory")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_component_help(self, mock_stdout):
        """
        Simple test of component help
        """
        instr = setup_instr_with_path()

        instr.component_help("test_for_reading", line_length=90)
        # This call creates a dummy component and calls its
        # show_parameter method which has been tested. Here we
        # need to ensure the call is successful, not test all
        # output from the call.

        output = mock_stdout.getvalue()
        output = output.split("\n")

        self.assertEqual(output[3], " ___ Help test_for_reading " + "_"*63)

        legend = ("|"
                  + bcolors.BOLD + "optional parameter" + bcolors.ENDC
                  + "|"
                  + bcolors.BOLD + bcolors.UNDERLINE
                  + "required parameter"
                  + bcolors.ENDC + bcolors.ENDC
                  + "|"
                  + bcolors.BOLD + bcolors.OKBLUE
                  + "default value"
                  + bcolors.ENDC + bcolors.ENDC
                  + "|"
                  + bcolors.BOLD + bcolors.OKGREEN
                  + "user specified value"
                  + bcolors.ENDC + bcolors.ENDC
                  + "|")

        self.assertEqual(output[4], legend)

        par_name = bcolors.BOLD + "radius" + bcolors.ENDC
        value = (bcolors.BOLD + bcolors.OKBLUE
                 + "0.1" + bcolors.ENDC + bcolors.ENDC)
        comment = ("// Radius of circle in (x,y,0) plane where "
                   + "neutrons are generated.")
        self.assertEqual(output[5],
                         par_name + " = " + value + " [m] " + comment)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_create_component_instance_simple(self, mock_stdout):
        """
        Tests successful use of _create_component_instance

        _create_component_instance will make a dynamic subclass of
        component with the information from the component files read
        from disk.  The subclass is saved in a dict for reuse in
        case the same component type is requested again.
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))

        current_work_dir = os.getcwd()
        os.chdir(THIS_DIR)  # Set work directory to test folder

        instr = setup_instr_with_path()

        os.chdir(current_work_dir)

        comp = instr._create_component_instance("test_component",
                                                "test_for_reading")

        self.assertEqual(comp.radius, None)
        self.assertIn("radius", comp.parameter_names)
        self.assertEqual(comp.parameter_defaults["radius"], 0.1)
        self.assertEqual(comp.parameter_types["radius"], "double")
        self.assertEqual(comp.parameter_units["radius"], "m")

        comment = ("Radius of circle in (x,y,0) plane where "
                   + "neutrons are generated.")
        self.assertEqual(comp.parameter_comments["radius"], comment)
        self.assertEqual(comp.category, "work directory")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_create_component_instance_complex(self, mock_stdout):
        """
        Tests successful use of _create_component_instance while using
        keyword arguments in creation

        _create_component_instance will make a dynamic subclass of
        component with the information from the component files read
        from disk.  The subclasses is saved in a dict for reuse in
        case the same component type is requested again.
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))

        current_work_dir = os.getcwd()
        os.chdir(THIS_DIR)  # Set work directory to test folder

        instr = setup_instr_with_path()

        os.chdir(current_work_dir)

        # Setting relative to home, should be passed to component
        comp = instr._create_component_instance("test_component",
                                                "test_for_reading",
                                                RELATIVE="home")

        self.assertEqual(comp.radius, None)
        self.assertIn("radius", comp.parameter_names)
        self.assertEqual(comp.parameter_defaults["radius"], 0.1)
        self.assertEqual(comp.parameter_types["radius"], "double")
        self.assertEqual(comp.parameter_units["radius"], "m")

        comment = ("Radius of circle in (x,y,0) plane where "
                   + "neutrons are generated.")
        self.assertEqual(comp.parameter_comments["radius"], comment)
        self.assertEqual(comp.category, "work directory")

        # The keyword arguments of the call should be passed to the
        # new instance of the component. This is checked by reading
        # the relative attributes which were set to home in the call
        self.assertEqual(comp.AT_relative, "RELATIVE home")
        self.assertEqual(comp.ROTATED_relative, "RELATIVE home")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_add_component_simple(self, mock_stdout):
        """
        Testing add_component in simple case.

        The add_component method adds a new component object to the
        instrument and keeps track of its location within the
        sequence of components.  Normally a new component is added to
        the end of the sequence, but the before and after keywords can
        be used to select another location.
        """

        instr = setup_instr_with_path()

        comp = instr.add_component("test_component", "test_for_reading")

        self.assertEqual(len(instr.component_list), 1)
        self.assertEqual(instr.component_list[0].name, "test_component")

        # Test the resulting object functions as intended
        comp.set_GROUP("developers")
        self.assertEqual(instr.component_list[0].GROUP, "developers")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_add_component_infer_name(self, mock_stdout):
        """
        Testing add_component works when name is left out and inferred
        from the name of the python variable in the call.
        """

        instr = setup_instr_with_path()

        test_component = instr.add_component("test_for_reading")

        self.assertEqual(len(instr.component_list), 1)
        self.assertEqual(instr.component_list[0].name, "test_component")

        # Test the resulting object functions as intended
        test_component.set_GROUP("developers")
        self.assertEqual(instr.component_list[0].GROUP, "developers")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_add_component_simple_keyword(self, mock_stdout):
        """
        Testing add_component with keyword argument for the component

        The add_component method adds a new component object to the
        instrument and keeps track of its location within the
        sequence of components.  Normally a new component is added to
        the end of the sequence, but the before and after keywords can
        be used to select another location. Here keyword passing is
        tested.
        """

        instr = setup_instr_with_path()

        instr.add_component("test_component",
                            "test_for_reading",
                            WHEN="1<2")

        self.assertEqual(len(instr.component_list), 1)
        self.assertEqual(instr.component_list[0].name, "test_component")
        self.assertEqual(instr.component_list[0].component_name,
                         "test_for_reading")

        self.assertEqual(instr.component_list[0].WHEN, "WHEN (1<2)")

    def test_add_component_simple_before(self):
        """
        Testing add_component with before keyword argument for the method

        The add_component method adds a new component object to the
        instrument and keeps track of its location within the
        sequence of components.  Normally a new component is added to
        the end of the sequence, but the before and after keywords can
        be used to select another location, here before is tested.
        """

        instr = setup_populated_instr()

        instr.add_component("test_component",
                            "test_for_reading",
                            before="first_component")

        self.assertEqual(len(instr.component_list), 4)
        self.assertEqual(instr.component_list[0].name, "test_component")
        self.assertEqual(instr.component_list[3].name, "third_component")

    def test_add_component_simple_after(self):
        """
        Testing add_component with after keyword argument for the method

        The add_component method adds a new component object to the
        instrument and keeps track of its location within the
        sequence of components.  Normally a new component is added to
        the end of the sequence, but the before and after keywords can
        be used to select another location, here after is tested.
        """

        instr = setup_populated_instr()

        instr.add_component("test_component",
                            "test_for_reading",
                            after="first_component")

        self.assertEqual(len(instr.component_list), 4)
        self.assertEqual(instr.component_list[1].name, "test_component")
        self.assertEqual(instr.component_list[3].name, "third_component")

    def test_add_component_simple_after_error(self):
        """
        Checks add_component raises a NameError if after keyword specifies a
        non-existent component

        The add_component method adds a new component object to the
        instrument and keeps track of its location within the
        sequence of components.  Normally a new component is added to
        the end of the sequence, but the before and after keywords can
        be used to select another location, here before is tested.
        """

        instr = setup_populated_instr()

        with self.assertRaises(NameError):
            instr.add_component("test_component",
                                "test_for_reading",
                                after="non_existent_component")

    def test_add_component_simple_before_error(self):
        """
        Checks add_component raises a NameError if before keyword specifies a
        non-existent component

        The add_component method adds a new component object to the
        instrument and keeps track of its location within the
        sequence of components.  Normally a new component is added to
        the end of the sequence, but the before and after keywords can
        be used to select another location, here after is tested.
        """

        instr = setup_populated_instr()

        with self.assertRaises(NameError):
            instr.add_component("test_component",
                                "test_for_reading",
                                before="non_existent_component")

    def test_add_component_simple_double_naming_error(self):
        """
        This tests checks that an error occurs when giving a new
        component a name which has already been used.
        """

        instr = setup_populated_instr()

        with self.assertRaises(NameError):
            instr.add_component("first_component", "test_for_reading")

    def test_copy_component_simple(self):
        """
        Checks that a component can be copied using the name
        """

        instr = setup_populated_with_some_options_instr()

        comp = instr.copy_component("copy_of_second_comp", "second_component")

        self.assertEqual(comp.name, "copy_of_second_comp")
        self.assertEqual(comp.yheight, 1.23)
        self.assertEqual(comp.AT_data[0], 0)
        self.assertEqual(comp.AT_data[1], 0)
        self.assertEqual(comp.AT_data[2], 2)

    def test_infer_copy_component_simple(self):
        """
        Checks that a component can be copied using the name
        while giving the new instance name as the python variable
        """

        instr = setup_populated_with_some_options_instr()

        copy_of_second_comp = instr.copy_component("second_component")

        self.assertEqual(copy_of_second_comp.name, "copy_of_second_comp")
        self.assertEqual(copy_of_second_comp.yheight, 1.23)
        self.assertEqual(copy_of_second_comp.AT_data[0], 0)
        self.assertEqual(copy_of_second_comp.AT_data[1], 0)
        self.assertEqual(copy_of_second_comp.AT_data[2], 2)

    def test_copy_component_simple_fail(self):
        """
        Checks a NameError is raised if trying to copy a component that does
        not exist
        """

        instr = setup_populated_with_some_options_instr()

        with self.assertRaises(NameError):
            instr.copy_component("copy_of_second_comp", "unknown_component")

    def test_copy_component_simple_object(self):
        """
        Checks that a component can be copied using the object
        """

        instr = setup_populated_with_some_options_instr()

        comp = instr.get_component("second_component")

        comp = instr.copy_component("copy_of_second_comp", comp)

        self.assertEqual(comp.name, "copy_of_second_comp")
        self.assertEqual(comp.yheight, 1.23)
        self.assertEqual(comp.AT_data[0], 0)
        self.assertEqual(comp.AT_data[1], 0)
        self.assertEqual(comp.AT_data[2], 2)

    def test_copy_component_keywords(self):
        """
        Checks that a component can be copied and that keyword
        arguments given under copy operation is successfully
        applied to the new component. A check is also made to
        ensure that the original component was not modified.
        """

        instr = setup_populated_with_some_options_instr()

        comp = instr.copy_component("copy_of_second_comp", "second_component",
                                    AT=[1, 2, 3], SPLIT=10)

        self.assertEqual(comp.name, "copy_of_second_comp")
        self.assertEqual(comp.yheight, 1.23)
        self.assertEqual(comp.AT_data[0], 1)
        self.assertEqual(comp.AT_data[1], 2)
        self.assertEqual(comp.AT_data[2], 3)
        self.assertEqual(comp.SPLIT, 10)

        # ensure original component was not changed
        original = instr.get_component("second_component")
        self.assertEqual(original.name, "second_component")
        self.assertEqual(original.yheight, 1.23)
        self.assertEqual(original.AT_data[0], 0)
        self.assertEqual(original.AT_data[1], 0)
        self.assertEqual(original.AT_data[2], 2)
        self.assertEqual(original.SPLIT, 0)

    def test_remove_component(self):
        """
        Ensure a component can be removed
        """
        instr = setup_populated_instr()

        instr.remove_component("second_component")

        self.assertEqual(len(instr.component_list), 2)
        self.assertEqual(instr.component_list[0].name, "first_component")
        self.assertEqual(instr.component_list[1].name, "third_component")

    def test_move_component(self):
        """
        Ensure a component can be moved
        """
        instr = setup_populated_instr()

        instr.move_component("second_component", before="first_component")

        self.assertEqual(len(instr.component_list), 3)
        self.assertEqual(instr.component_list[0].name, "second_component")
        self.assertEqual(instr.component_list[1].name, "first_component")
        self.assertEqual(instr.component_list[2].name, "third_component")

    def test_RELATIVE_error(self):
        """
        Ensure check_for_errors finds impossible relative statement
        """

        instr = setup_populated_instr()

        second_component = instr.get_component("second_component")
        second_component.set_AT([0, 0, 0], RELATIVE="third_component")

        self.assertTrue(instr.has_errors())

        with self.assertRaises(McStasError):
            instr.check_for_errors()

    @unittest.mock.patch('__main__.__builtins__.open',
                         new_callable=unittest.mock.mock_open)
    def test_RELATIVE_error_and_checks_false(self, mock_f):
        """
        Ensure check_for_errors finds impossible relative statement
        """

        instr = setup_populated_instr()

        second_component = instr.get_component("second_component")
        second_component.set_AT([0, 0, 0], RELATIVE="third_component")

        self.assertTrue(instr.has_errors())

        with self.assertRaises(McStasError):
            instr.write_full_instrument()

        instr.settings(checks=False)
        instr.write_full_instrument()

    def test_get_component_simple(self):
        """
        get_component retrieves a component with a given name for
        easier manipulation. Check it works as intended.
        """

        instr = setup_populated_instr()

        comp = instr.get_component("second_component")

        self.assertEqual(comp.name, "second_component")

    def test_get_component_simple_error(self):
        """
        get_component retrieves a component with a given name for
        easier manipulation. Check it fails when the component name
        doesn't correspond to a component in the instrument.
        """

        instr = setup_populated_instr()

        with self.assertRaises(NameError):
            instr.get_component("non_existing_component")

    def test_get_last_component_simple(self):
        """
        Check get_last_component retrieves the last component
        """

        instr = setup_populated_instr()

        comp = instr.get_last_component()

        self.assertEqual(comp.name, "third_component")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_print_component(self, mock_stdout):
        """
        print_component calls the print_long method in the component
        class.
        """

        instr = setup_populated_instr()
        instr.get_component("second_component").set_parameters(dist=5)

        instr.print_component("second_component")

        output = mock_stdout.getvalue().split("\n")

        self.assertEqual(output[0],
                         "COMPONENT second_component = test_for_reading(")

        par_name = bcolors.BOLD + "dist" + bcolors.ENDC
        value = (bcolors.BOLD + bcolors.OKGREEN
                 + "5" + bcolors.ENDC + bcolors.ENDC)
        self.assertEqual(output[1], "  " + par_name + " = " + value + " // [m]")

        par_name = bcolors.BOLD + "gauss" + bcolors.ENDC
        warning = (bcolors.FAIL
                   + " : Required parameter not yet specified"
                   + bcolors.ENDC)
        self.assertEqual(output[2], "  " + par_name + warning)

        par_name = bcolors.BOLD + "test_string" + bcolors.ENDC
        warning = (bcolors.FAIL
                   + " : Required parameter not yet specified"
                   + bcolors.ENDC)
        self.assertEqual(output[3], "  " + par_name + warning)

        self.assertEqual(output[4], ")")
        self.assertEqual(output[5], "AT (0, 0, 0) ABSOLUTE")

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_print_component_short(self, mock_stdout):
        """
        print_component_short calls the print_short method in the
        component class.
        """

        instr = setup_populated_instr()
        instr.get_component("second_component").set_AT([-1, 2, 3.4],
                                                       RELATIVE="home")

        instr.print_component_short("second_component")

        output = mock_stdout.getvalue().split("\n")

        expected = ("second_component = test_for_reading "
                    + "\tAT [-1, 2, 3.4] RELATIVE home "
                    + "ROTATED [0, 0, 0] RELATIVE home")

        self.assertEqual(output[0], expected)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_show_components_simple(self, mock_stdout):
        """
        Tests show_components for simple case

        show_components calls the print_short method in the component
        class for each component and aligns the data for display
        """

        instr = setup_populated_instr()

        instr.show_components(line_length=300)

        output = mock_stdout.getvalue().split("\n")

        expected = ("first_component  test_for_reading"
                    + " AT (0, 0, 0) ABSOLUTE")
        self.assertEqual(output[0], expected)

        expected = ("second_component test_for_reading"
                    + " AT (0, 0, 0) ABSOLUTE")
        self.assertEqual(output[1], expected)

        expected = ("third_component  test_for_reading"
                    + " AT (0, 0, 0) ABSOLUTE")
        self.assertEqual(output[2], expected)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_show_components_complex(self, mock_stdout):
        """
        Tests show_components for complex case

        show_components calls the print_short method in the component
        class for each component and aligns the data for display
        """

        instr = setup_populated_instr()

        instr.get_component("first_component").set_AT([-0.1, 12, "dist"],
                                                      RELATIVE="home")
        instr.get_component("second_component").set_ROTATED([-4, 0.001, "theta"],
                                                            RELATIVE="etc")
        comp = instr.get_last_component()
        comp.component_name = "test_name"

        instr.show_components(line_length=300)

        output = mock_stdout.getvalue().split("\n")

        expected = ("first_component  test_for_reading"
                    + " AT (-0.1, 12, dist) RELATIVE home")
        self.assertEqual(output[0], expected)

        expected = ("second_component test_for_reading"
                    + " AT (0, 0, 0)        ABSOLUTE"
                    + "      ROTATED (-4, 0.001, theta) RELATIVE etc")
        self.assertEqual(output[1], expected)

        expected = ("third_component  test_name"
                    + "        AT (0, 0, 0)        ABSOLUTE     ")
        self.assertEqual(output[2], expected)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_show_components_complex_2lines(self, mock_stdout):
        """
        show_components calls the print_short method in the component
        class for each component and aligns the data for display

        This version of the tests forces two lines of output.
        """

        instr = setup_populated_instr()

        instr.get_component("first_component").set_AT([-0.1, 12, "dist"],
                                                      RELATIVE="home")
        instr.get_component("second_component").set_ROTATED([-4, 0.001, "theta"],
                                                            RELATIVE="etc")
        comp = instr.get_last_component()
        comp.component_name = "test_name"

        instr.show_components(line_length=80)

        output = mock_stdout.getvalue().split("\n")

        expected = ("first_component  test_for_reading"
                    + " AT      (-0.1, 12, dist)   RELATIVE home")
        self.assertEqual(output[0], expected)

        expected = ("second_component test_for_reading"
                    + " AT      (0, 0, 0)          ABSOLUTE      ")
        self.assertEqual(output[1], expected)

        expected = ("                                 "
                    + " ROTATED (-4, 0.001, theta) RELATIVE etc")
        self.assertEqual(output[2], expected)

        expected = ("third_component  test_name       "
                    + " AT      (0, 0, 0)          ABSOLUTE     ")
        self.assertEqual(output[3], expected)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_show_components_complex_3lines(self, mock_stdout):
        """
        show_components calls the print_short method in the component
        class for each component and aligns the data for display

        This version of the tests forces three lines of output.
        """

        instr = setup_populated_instr()

        instr.get_component("first_component").set_AT([-0.1, 12, "dist"],
                                                      RELATIVE="home")
        instr.get_component("second_component").set_ROTATED([-4, 0.001, "theta"],
                                                            RELATIVE="etc")
        comp = instr.get_last_component()
        comp.component_name = "test_name"

        instr.show_components(line_length=1)  # Three lines maximum

        output = mock_stdout.getvalue().split("\n")

        expected = (bcolors.BOLD
                    + "first_component"
                    + bcolors.ENDC
                    + "  "
                    + bcolors.BOLD
                    + "test_for_reading"
                    + bcolors.ENDC
                    + " ")
        self.assertEqual(output[0], expected)

        expected = "  AT      (-0.1, 12, dist) RELATIVE home"
        self.assertEqual(output[1], expected)

        expected = (bcolors.BOLD
                    + "second_component"
                    + bcolors.ENDC
                    + "  "
                    + bcolors.BOLD
                    + "test_for_reading"
                    + bcolors.ENDC
                    + " ")
        self.assertEqual(output[2], expected)

        expected = "  AT      (0, 0, 0) ABSOLUTE "
        self.assertEqual(output[3], expected)

        expected = "  ROTATED (-4, 0.001, theta) RELATIVE etc"
        self.assertEqual(output[4], expected)

        expected = (bcolors.BOLD
                    + "third_component"
                    + bcolors.ENDC
                    + "  "
                    + bcolors.BOLD
                    + "test_name"
                    + bcolors.ENDC
                    + " ")
        self.assertEqual(output[5], expected)

        expected = "  AT      (0, 0, 0) ABSOLUTE"
        self.assertEqual(output[6], expected)

    @unittest.mock.patch('__main__.__builtins__.open',
                         new_callable=unittest.mock.mock_open)
    def test_write_c_files_simple(self, mock_f):
        """
        Write_c_files writes the strings for declare, initialize,
        and trace to files that are then included in McStas files.
        This is an obsolete method, but may be repurposed later
        so that instrument parts can be created with the modern
        syntax.

        The generated includes file in the test directory is written
        by this test. It will fail if it does not have rights to
        create the directory.
        """

        instr = setup_populated_instr()

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        current_directory = os.getcwd()
        os.chdir(THIS_DIR)

        try:
            instr.write_c_files()
        finally:
            os.chdir(current_directory)

        base_path = os.path.join(".", "generated_includes")
        expected_path = os.path.join(base_path, "test_instrument_declare.c")
        mock_f.assert_any_call(expected_path, "w")
        mock_f.assert_any_call(expected_path, "a")

        expected_path = os.path.join(base_path, "test_instrument_initialize.c")
        mock_f.assert_any_call(expected_path, "w")

        expected_path = os.path.join(base_path, "test_instrument_trace.c")
        mock_f.assert_any_call(expected_path, "w")

        expected_path = os.path.join(base_path, "test_instrument_component_trace.c")
        mock_f.assert_any_call(expected_path, "w")

        # This does not check that the right thing is written to the
        # right file. Can be improved by splitting the method into
        # several for easier testing. Acceptable since it is rarely
        # used.
        handle = mock_f()
        call = unittest.mock.call
        wrts = [
         call("// declare section for test_instrument \n"),
         call("double two_theta;"),
         call("\n"),
         call("// Start of initialize for generated test_instrument\n"
              + "two_theta = 2.0*theta;\n"),
         call("// Start of trace section for generated test_instrument\n"),
         call("COMPONENT first_component = test_for_reading("),
         call(")\n"),
         call("AT (0,0,0)"),
         call(" ABSOLUTE\n"),
         call("\n"),
         call("COMPONENT second_component = test_for_reading("),
         call(")\n"),
         call("AT (0,0,0)"),
         call(" ABSOLUTE\n"),
         call("\n"),
         call("COMPONENT third_component = test_for_reading("),
         call(")\n"),
         call("AT (0,0,0)"),
         call(" ABSOLUTE\n"),
         call("\n")]

        handle.write.assert_has_calls(wrts, any_order=False)

    @unittest.mock.patch('__main__.__builtins__.open',
                         new_callable=unittest.mock.mock_open)
    @unittest.mock.patch('datetime.datetime')
    def test_write_full_instrument_simple(self, mock_datetime, mock_f):
        """
        The write_full_instrument method write the information
        contained in the instrument instance to a file with McStas
        syntax.

        The test includes a time stamp in the written and expected
        data that has an accuracy of 1 second.  It is unlikely to fail
        due to this, but it can happen.
        """

        # Fix datetime for call
        fixed_datetime = datetime.datetime(2023, 12, 14, 12, 44, 21)
        mock_datetime.now.return_value = fixed_datetime

        instr = setup_populated_instr()
        instr.write_full_instrument()

        t_format = "%H:%M:%S on %B %d, %Y"

        my_call = unittest.mock.call
        wrts = [
         my_call("/" + 80*"*" + "\n"),
         my_call("* \n"),
         my_call("* McStas, neutron ray-tracing package\n"),
         my_call("*         Copyright (C) 1997-2008, All rights reserved\n"),
         my_call("*         Risoe National Laboratory, Roskilde, Denmark\n"),
         my_call("*         Institut Laue Langevin, Grenoble, France\n"),
         my_call("* \n"),
         my_call("* This file was written by McStasScript, which is a \n"),
         my_call("* python based McStas instrument generator written by \n"),
         my_call("* Mads Bertelsen in 2019 while employed at the \n"),
         my_call("* European Spallation Source Data Management and \n"),
         my_call("* Software Centre\n"),
         my_call("* \n"),
         my_call("* Instrument test_instrument\n"),
         my_call("* \n"),
         my_call("* %Identification\n"),
         my_call("* Written by: Python McStas Instrument Generator\n"),
         my_call("* Date: %s\n" % fixed_datetime.strftime(t_format)),
         my_call("* Origin: ESS DMSC\n"),
         my_call("* %INSTRUMENT_SITE: Generated_instruments\n"),
         my_call("* \n"),
         my_call("* \n"),
         my_call("* %Parameters\n"),
         my_call("* \n"),
         my_call("* %End \n"),
         my_call("*"*80 + "/\n"),
         my_call("\n"),
         my_call("DEFINE INSTRUMENT test_instrument ("),
         my_call("\n"),
         my_call("double theta"),
         my_call(", "),
         my_call(""),
         my_call("\n"),
         my_call("double has_default"),
         my_call(" = 37"),
         my_call(" "),
         my_call(""),
         my_call("\n"),
         my_call(")\n"),
         my_call("\n"),
         my_call("DECLARE \n%{\n"),
         my_call("double two_theta;"),
         my_call("\n"),
         my_call("%}\n\n"),
         my_call("INITIALIZE \n%{\n"),
         my_call("// Start of initialize for generated test_instrument\n"
                 + "two_theta = 2.0*theta;\n"),
         my_call("%}\n\n"),
         my_call("TRACE \n"),
         my_call("COMPONENT first_component = test_for_reading("),
         my_call(")\n"),
         my_call("AT (0,0,0)"),
         my_call(" ABSOLUTE\n"),
         my_call("\n"),
         my_call("COMPONENT second_component = test_for_reading("),
         my_call(")\n"),
         my_call("AT (0,0,0)"),
         my_call(" ABSOLUTE\n"),
         my_call("\n"),
         my_call("COMPONENT third_component = test_for_reading("),
         my_call(")\n"),
         my_call("AT (0,0,0)"),
         my_call(" ABSOLUTE\n"),
         my_call("\n"),
         my_call("FINALLY \n%{\n"),
         my_call("// Start of finally for generated test_instrument\n"),
         my_call("%}\n"),
         my_call("\nEND\n")]

        expected_path = os.path.join(".", "test_instrument.instr")
        mock_f.assert_called_with(expected_path, "w")
        handle = mock_f()
        handle.write.assert_has_calls(wrts, any_order=False)

    @unittest.mock.patch('__main__.__builtins__.open',
                         new_callable=unittest.mock.mock_open)
    def test_write_full_instrument_dependency(self, mock_f):
        """
        The write_full_instrument method write the information
        contained in the instrument instance to a file with McStas
        syntax. Here tested with the dependency section enabled.

        The test includes a time stamp in the written and expected
        data that has an accuracy of 1 second.  It is unlikely to fail
        due to this, but it can happen.
        """

        instr = setup_populated_instr()
        instr.set_dependency("-DMCPLPATH=GETPATH(data)")
        instr.write_full_instrument()

        t_format = "%H:%M:%S on %B %d, %Y"

        my_call = unittest.mock.call
        wrts = [
            my_call("/" + 80 * "*" + "\n"),
            my_call("* \n"),
            my_call("* McStas, neutron ray-tracing package\n"),
            my_call("*         Copyright (C) 1997-2008, All rights reserved\n"),
            my_call("*         Risoe National Laboratory, Roskilde, Denmark\n"),
            my_call("*         Institut Laue Langevin, Grenoble, France\n"),
            my_call("* \n"),
            my_call("* This file was written by McStasScript, which is a \n"),
            my_call("* python based McStas instrument generator written by \n"),
            my_call("* Mads Bertelsen in 2019 while employed at the \n"),
            my_call("* European Spallation Source Data Management and \n"),
            my_call("* Software Centre\n"),
            my_call("* \n"),
            my_call("* Instrument test_instrument\n"),
            my_call("* \n"),
            my_call("* %Identification\n"),
            my_call("* Written by: Python McStas Instrument Generator\n"),
            my_call("* Date: %s\n" % datetime.datetime.now().strftime(t_format)),
            my_call("* Origin: ESS DMSC\n"),
            my_call("* %INSTRUMENT_SITE: Generated_instruments\n"),
            my_call("* \n"),
            my_call("* \n"),
            my_call("* %Parameters\n"),
            my_call("* \n"),
            my_call("* %End \n"),
            my_call("*" * 80 + "/\n"),
            my_call("\n"),
            my_call("DEFINE INSTRUMENT test_instrument ("),
            my_call("\n"),
            my_call("double theta"),
            my_call(", "),
            my_call(""),
            my_call("\n"),
            my_call("double has_default"),
            my_call(" = 37"),
            my_call(" "),
            my_call(""),
            my_call("\n"),
            my_call(")\n"),
            my_call('DEPENDENCY "-DMCPLPATH=GETPATH(data)"\n'),
            my_call("\n"),
            my_call("DECLARE \n%{\n"),
            my_call("double two_theta;"),
            my_call("\n"),
            my_call("%}\n\n"),
            my_call("INITIALIZE \n%{\n"),
            my_call("// Start of initialize for generated test_instrument\n"
                    + "two_theta = 2.0*theta;\n"),
            my_call("%}\n\n"),
            my_call("TRACE \n"),
            my_call("COMPONENT first_component = test_for_reading("),
            my_call(")\n"),
            my_call("AT (0,0,0)"),
            my_call(" ABSOLUTE\n"),
            my_call("\n"),
            my_call("COMPONENT second_component = test_for_reading("),
            my_call(")\n"),
            my_call("AT (0,0,0)"),
            my_call(" ABSOLUTE\n"),
            my_call("\n"),
            my_call("COMPONENT third_component = test_for_reading("),
            my_call(")\n"),
            my_call("AT (0,0,0)"),
            my_call(" ABSOLUTE\n"),
            my_call("\n"),
            my_call("FINALLY \n%{\n"),
            my_call("// Start of finally for generated test_instrument\n"),
            my_call("%}\n"),
            my_call("\nEND\n")]

        expected_path = os.path.join(".", "test_instrument.instr")
        mock_f.assert_called_with(expected_path, "w")
        handle = mock_f()
        handle.write.assert_has_calls(wrts, any_order=False)

    @unittest.mock.patch('__main__.__builtins__.open',
                         new_callable=unittest.mock.mock_open)
    def test_write_full_instrument_search(self, mock_f):
        """
        The write_full_instrument method write the information
        contained in the instrument instance to a file with McStas
        syntax. Here tested with the search section enabled.

        The test includes a time stamp in the written and expected
        data that has an accuracy of 1 second.  It is unlikely to fail
        due to this, but it can happen.
        """

        instr = setup_populated_instr()
        instr.add_search("first_search")
        instr.add_search("second search", SHELL=True)
        instr.write_full_instrument()

        t_format = "%H:%M:%S on %B %d, %Y"

        my_call = unittest.mock.call
        wrts = [
            my_call("/" + 80 * "*" + "\n"),
            my_call("* \n"),
            my_call("* McStas, neutron ray-tracing package\n"),
            my_call("*         Copyright (C) 1997-2008, All rights reserved\n"),
            my_call("*         Risoe National Laboratory, Roskilde, Denmark\n"),
            my_call("*         Institut Laue Langevin, Grenoble, France\n"),
            my_call("* \n"),
            my_call("* This file was written by McStasScript, which is a \n"),
            my_call("* python based McStas instrument generator written by \n"),
            my_call("* Mads Bertelsen in 2019 while employed at the \n"),
            my_call("* European Spallation Source Data Management and \n"),
            my_call("* Software Centre\n"),
            my_call("* \n"),
            my_call("* Instrument test_instrument\n"),
            my_call("* \n"),
            my_call("* %Identification\n"),
            my_call("* Written by: Python McStas Instrument Generator\n"),
            my_call("* Date: %s\n" % datetime.datetime.now().strftime(t_format)),
            my_call("* Origin: ESS DMSC\n"),
            my_call("* %INSTRUMENT_SITE: Generated_instruments\n"),
            my_call("* \n"),
            my_call("* \n"),
            my_call("* %Parameters\n"),
            my_call("* \n"),
            my_call("* %End \n"),
            my_call("*" * 80 + "/\n"),
            my_call("\n"),
            my_call("DEFINE INSTRUMENT test_instrument ("),
            my_call("\n"),
            my_call("double theta"),
            my_call(", "),
            my_call(""),
            my_call("\n"),
            my_call("double has_default"),
            my_call(" = 37"),
            my_call(" "),
            my_call(""),
            my_call("\n"),
            my_call(")\n"),
            my_call("\n"),
            my_call("DECLARE \n%{\n"),
            my_call("double two_theta;"),
            my_call("\n"),
            my_call("%}\n\n"),
            my_call("INITIALIZE \n%{\n"),
            my_call("// Start of initialize for generated test_instrument\n"
                    + "two_theta = 2.0*theta;\n"),
            my_call("%}\n\n"),
            my_call("TRACE \n"),
            my_call('SEARCH "first_search"\n'),
            my_call('SEARCH SHELL "second search"\n'),
            my_call("COMPONENT first_component = test_for_reading("),
            my_call(")\n"),
            my_call("AT (0,0,0)"),
            my_call(" ABSOLUTE\n"),
            my_call("\n"),
            my_call("COMPONENT second_component = test_for_reading("),
            my_call(")\n"),
            my_call("AT (0,0,0)"),
            my_call(" ABSOLUTE\n"),
            my_call("\n"),
            my_call("COMPONENT third_component = test_for_reading("),
            my_call(")\n"),
            my_call("AT (0,0,0)"),
            my_call(" ABSOLUTE\n"),
            my_call("\n"),
            my_call("FINALLY \n%{\n"),
            my_call("// Start of finally for generated test_instrument\n"),
            my_call("%}\n"),
            my_call("\nEND\n")]

        expected_path = os.path.join(".", "test_instrument.instr")
        mock_f.assert_called_with(expected_path, "w")
        handle = mock_f()
        handle.write.assert_has_calls(wrts, any_order=False)

    # mock sys.stdout to avoid printing to terminal
    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_run_full_instrument_required_par_error(self, mock_stdout):
        """
        Tests run_full_instrument raises error when lacking required parameter

        The populated instr has a required parameter, and when not
        given it should raise an error.
        """
        instr = setup_populated_instr()

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        executable_path = os.path.join(THIS_DIR, "dummy_mcstas")

        with self.assertRaises(NameError):
            instr.run_full_instrument(output_path="test_data_set",
                                      increment_folder_name=False,
                                      executable_path=executable_path)

    def test_run_full_instrument_junk_par_error(self):
        """
        Check run_full_instrument raises a NameError if a unrecognized
        parameter is provided, here junk.
        """
        instr = setup_populated_instr()

        pars = {"theta": 2, "junk": "test"}

        with self.assertRaises(KeyError):
            instr.run_full_instrument(output_path="test_data_set",
                                      increment_folder_name=False,
                                      parameters=pars)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    @unittest.mock.patch("subprocess.run")
    def test_x_ray_run_full_instrument_basic(self, mock_sub, mock_stdout):
        """
        Tests x-ray run_full_instrument

        Check a simple run performs the correct system call.  Here
        the output_path is set to a name that does not correspond to a
        existing file so no error is thrown.
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        executable_path = os.path.join(THIS_DIR, "dummy_mcstas")

        with WorkInTestDir() as handler:
            new_folder_name = "folder_name_which_is_unused"
            if os.path.exists(new_folder_name):
                raise RuntimeError("Folder_name was supposed to not "
                                   + "exist before "
                                   + "test_run_backengine_basic")

            instr = setup_populated_x_ray_instr_with_dummy_path()
            instr.run_full_instrument(output_path=new_folder_name,
                                      increment_folder_name=False,
                                      executable_path=executable_path,
                                      parameters={"theta": 1})

        expected_path = os.path.join(executable_path, "mxrun")
        expected_path = '"' + expected_path + '"'

        expected_folder_path = os.path.join(THIS_DIR, new_folder_name)

        # a double space because of a missing option
        expected_call = (expected_path + " -c -n 1000000 "
                         + "-d " + expected_folder_path
                         + "  test_instrument.instr"
                         + " theta=1 has_default=37")

        expected_run_path = os.path.join(THIS_DIR, ".")

        mock_sub.assert_called_with(expected_call,
                                    shell=True,
                                    cwd=expected_run_path,
                                    stderr=-2, stdout=-1,
                                    universal_newlines=True)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    def test_run_backengine_existing_folder(self, mock_stdout):
        """
        Test neutron run of backengine fails if using existing folder
        for output_path and with increment_folder_name disabled.
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        executable_path = os.path.join(THIS_DIR, "dummy_mcstas")

        with WorkInTestDir() as handler:
            instr = setup_populated_instr_with_dummy_path()

            instr.set_parameters({"theta": 1})
            instr.settings(output_path="test_data_set",
                           increment_folder_name=False,
                           executable_path=executable_path)

            with self.assertRaises(NameError):
                instr.backengine()

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    @unittest.mock.patch("subprocess.run")
    def test_run_backengine_basic(self, mock_sub, mock_stdout):
        """
        Test neutron run_full_instrument

        Check a simple run performs the correct system call. Here
        the output_path is set to a name that does not correspond to a
        existing file so no error is thrown.
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        executable_path = os.path.join(THIS_DIR, "dummy_mcstas")

        with WorkInTestDir() as handler:
            new_folder_name = "folder_name_which_is_unused"
            if os.path.exists(new_folder_name):
                raise RuntimeError("Folder_name was supposed to not "
                                   + "exist before "
                                   + "test_run_backengine_basic")

            instr = setup_populated_instr_with_dummy_path()

            instr.set_parameters({"theta": 1})
            instr.settings(output_path=new_folder_name,
                           increment_folder_name=True,
                           executable_path=executable_path)
            instr.backengine()

        expected_path = os.path.join(executable_path, "mcrun")
        expected_path = '"' + expected_path + '"'

        expected_folder_path = os.path.join(THIS_DIR, new_folder_name)

        # a double space because of a missing option
        expected_call = (expected_path + " -c -n 1000000 "
                         + "-d " + expected_folder_path
                         + "  test_instrument.instr"
                         + " theta=1 has_default=37")

        mock_sub.assert_called_with(expected_call,
                                    shell=True,
                                    stderr=-2, stdout=-1,
                                    universal_newlines=True,
                                    cwd=run_path)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    @unittest.mock.patch("subprocess.run")
    def test_run_backengine_complex_settings(self, mock_sub, mock_stdout):
        """
        Test settings are passed to backengine with complex settings

        Check run performs the correct system call with settings. Here
        the output_path is set to a name that does not correspond to a
        existing file so no error is thrown.
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        executable_path = os.path.join(THIS_DIR, "dummy_mcstas")

        with WorkInTestDir() as handler:
            new_folder_name = "folder_name_which_is_unused"
            if os.path.exists(new_folder_name):
                raise RuntimeError("Folder_name was supposed to not "
                                   + "exist before "
                                   + "test_run_backengine_basic")

            instr = setup_populated_instr_with_dummy_path()

            instr.set_parameters({"theta": 1})
            instr.settings(output_path=new_folder_name,
                           increment_folder_name=True,
                           executable_path=executable_path,
                           mpi=5, ncount=19373, openacc=True,
                           NeXus=True, force_compile=False,
                           seed=300, gravity=True, checks=False,
                           save_comp_pars=True)
            instr.backengine()

        expected_path = os.path.join(executable_path, "mcrun")
        expected_path = '"' + expected_path + '"'

        expected_folder_path = os.path.join(THIS_DIR, new_folder_name)

        # a double space because of a missing option
        expected_call = (expected_path + " -g --format=NeXus "
                         + "--openacc "
                         + "-n 19373 --mpi=5 --seed=300 "
                         + "-d " + expected_folder_path
                         + "  test_instrument.instr"
                         + " theta=1 has_default=37")

        mock_sub.assert_called_with(expected_call,
                                    shell=True,
                                    stderr=-2, stdout=-1,
                                    universal_newlines=True,
                                    cwd=run_path)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    @unittest.mock.patch("subprocess.run")
    def test_run_full_instrument_complex(self, mock_sub, mock_stdout):
        """
        Test neutron run_full_instrument in more complex case

        Check a complex run performs the correct system call. Here
        the output_path is set to a name that does not correspond to a
        existing file so no error is thrown.
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        executable_path = os.path.join(THIS_DIR, "dummy_mcstas")

        with WorkInTestDir() as handler:
            new_folder_name = "folder_name_which_is_unused"
            if os.path.exists(new_folder_name):
                raise RuntimeError("Folder_name was supposed to not "
                                   + "exist before "
                                   + "test_run_backengine_basic")

            instr = setup_populated_instr_with_dummy_path()

            # Add some extra parameters for testing
            instr.add_parameter("A")
            instr.add_parameter("BC")

            instr.run_full_instrument(output_path=new_folder_name,
                                      increment_folder_name=False,
                                      executable_path=executable_path,
                                      mpi=7,
                                      seed=300,
                                      ncount=48.4,
                                      gravity=True,
                                      custom_flags="-fo",
                                      parameters={"A": 2,
                                                  "BC": "car",
                                                  "theta": "\"toy\""})

        expected_path = os.path.join(executable_path, "mcrun")
        expected_path = '"' + expected_path + '"'
        expected_folder_path = os.path.join(THIS_DIR, new_folder_name)

        # a double space because of a missing option
        expected_call = (expected_path + " -c -g -n 48 --mpi=7 --seed=300 "
                         + "-d " + expected_folder_path
                         + " -fo test_instrument.instr "
                         + "theta=\"toy\" has_default=37 A=2 BC=car")

        mock_sub.assert_called_with(expected_call,
                                    shell=True,
                                    stderr=-2, stdout=-1,
                                    universal_newlines=True,
                                    cwd=run_path)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    @unittest.mock.patch("subprocess.run")
    def test_run_full_instrument_overwrite_default(self, mock_sub,
                                                   mock_stdout):
        """
        Check that default parameters are overwritten by given
        parameters in run_full_instrument.
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        executable_path = os.path.join(THIS_DIR, "dummy_mcstas")

        with WorkInTestDir() as handler:
            new_folder_name = "folder_name_which_is_unused"
            if os.path.exists(new_folder_name):
                raise RuntimeError("Folder_name was supposed to not "
                                   + "exist before "
                                   + "test_run_backengine_basic")

            instr = setup_populated_instr_with_dummy_path()

            # Add some extra parameters for testing
            instr.add_parameter("A")
            instr.add_parameter("BC")

            instr.run_full_instrument(output_path=new_folder_name,
                                      increment_folder_name=False,
                                      executable_path=executable_path,
                                      mpi=7,
                                      ncount=48.4,
                                      custom_flags="-fo",
                                      parameters={"A": 2,
                                                  "BC": "car",
                                                  "theta": "\"toy\"",
                                                  "has_default": 10})

        expected_path = os.path.join(executable_path, "mcrun")
        expected_path = '"' + expected_path + '"'
        expected_folder_path = os.path.join(THIS_DIR, new_folder_name)

        # a double space because of a missing option
        expected_call = (expected_path + " -c -n 48 --mpi=7 "
                         + "-d " + expected_folder_path
                         + " -fo test_instrument.instr "
                         + "theta=\"toy\" has_default=10 A=2 BC=car")

        mock_sub.assert_called_with(expected_call,
                                    shell=True,
                                    stderr=-2, stdout=-1,
                                    universal_newlines=True,
                                    cwd=run_path)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    @unittest.mock.patch("subprocess.run")
    def test_run_full_instrument_x_ray_basic(self, mock_sub, mock_stdout):
        """
        Test x-ray run_full_instrument

        Check a simple run performs the correct system call.  Here
        the output_path is set to a name that does not correspond to a
        existing file so no error is thrown.
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        executable_path = os.path.join(THIS_DIR, "dummy_mcstas")

        with WorkInTestDir() as handler:
            new_folder_name = "folder_name_which_is_unused"
            if os.path.exists(new_folder_name):
                raise RuntimeError("Folder_name was supposed to not "
                                   + "exist before "
                                   + "test_run_backengine_basic")

            instr = setup_populated_x_ray_instr_with_dummy_path()

            instr.run_full_instrument(output_path=new_folder_name,
                                      increment_folder_name=False,
                                      executable_path=executable_path,
                                      parameters={"theta": 1})

        expected_path = os.path.join(executable_path, "mxrun")
        expected_path = '"' + expected_path + '"'
        expected_folder_path = os.path.join(THIS_DIR, new_folder_name)

        # a double space because of a missing option
        expected_call = (expected_path + " -c -n 1000000 "
                         + "-d " + expected_folder_path
                         + "  test_instrument.instr"
                         + " theta=1 has_default=37")

        mock_sub.assert_called_with(expected_call,
                                    shell=True,
                                    stderr=-2, stdout=-1,
                                    universal_newlines=True,
                                    cwd=run_path)

    @unittest.mock.patch("sys.stdout", new_callable=io.StringIO)
    @unittest.mock.patch("subprocess.run")
    def test_show_instrument_basic(self, mock_sub, mock_stdout):
        """
        Test show_instrument methods makes correct system calls
        """

        THIS_DIR = os.path.dirname(os.path.abspath(__file__))
        executable_path = os.path.join(THIS_DIR, "dummy_mcstas")

        current_work_dir = os.getcwd()
        os.chdir(THIS_DIR)  # Set work directory to test folder

        instr = setup_populated_instr_with_dummy_path()

        instr.set_parameters(theta=1.2)
        instr.show_instrument()

        os.chdir(current_work_dir)

        expected_path = os.path.join(executable_path, "bin", "mcdisplay-webgl")
        expected_path = '"' + expected_path + '"'
        expected_instr_path = os.path.join(THIS_DIR, "test_instrument.instr")

        # a double space because of a missing option
        expected_call = (expected_path
                         + " --dirname test_instrument_mcdisplay"
                         + " " + expected_instr_path
                         + "  theta=1.2 has_default=37")

        mock_sub.assert_called_with(expected_call,
                                    shell=True,
                                    stderr=-1, stdout=-1,
                                    universal_newlines=True,
                                    cwd=".")

    def test_show_dumps_works(self):
        """
        Ensures show_dumps runs
        """

        instr = setup_populated_instr_with_dummy_MCPL_comps()
        insert_mock_dump(instr, "second_component")

        instr.show_dumps()

    def test_show_dump_works(self):
        """
        Ensures show_dump runs and that db can get the stored dump
        """

        instr = setup_populated_instr_with_dummy_MCPL_comps()
        insert_mock_dump(instr, "second_component", run_name="custom_run", tag=31)

        instr.show_dump("second_component", "custom_run", 31)

        dump = instr.dump_database.get_dump("second_component", "custom_run", 31)
        self.assertEqual(dump.data["dump_point"], "second_component")
        self.assertEqual(dump.data["run_name"], "custom_run")
        self.assertEqual(dump.data["tag"], 31)

    def test_set_run_to_component(self):
        """
        Testing run_to method updates instr state correctly
        """

        instr = setup_populated_instr_with_dummy_MCPL_comps()

        second_component = instr.get_component("second_component")

        # Ensure remaining instrument can work
        third_component = instr.get_component("third_component")
        third_component.set_RELATIVE("second_component")

        instr.run_to(second_component)

        self.assertEqual(instr.run_from_ref, None)
        self.assertEqual(instr.run_to_ref, "second_component")
        self.assertEqual(instr.run_to_name, "Run")

        # Check filename added to parameters
        self.assertTrue("run_to_mcpl" in instr.parameters.parameters)
        self.assertEqual(instr.parameters.parameters["run_to_mcpl"].type, "string")

        instr.run_to("third_component", run_name="Test_name")
        self.assertEqual(instr.run_to_ref, "third_component")
        self.assertEqual(instr.run_to_name, "Test_name")

    def test_set_run_to_component_keywords(self):
        """
        Testing run_to method updates instr state with passed keywords
        """

        instr = setup_populated_instr_with_dummy_MCPL_comps()

        second_component = instr.get_component("second_component")

        # Ensure remaining instrument can work
        third_component = instr.get_component("third_component")
        third_component.set_RELATIVE("second_component")

        instr.run_to(second_component, test_keyword=58)

        self.assertIn("test_keyword", instr.run_to_component_parameters)
        self.assertEqual(instr.run_to_component_parameters["test_keyword"], 58)

    def test_set_run_to_nonexistant_component_fails(self):
        """
        Ensures run_to fails if the component doesn't exist
        """

        instr = setup_populated_instr_with_dummy_MCPL_comps()

        with self.assertRaises(ValueError):
            instr.run_to("component_that_does_not_exists")

    def test_set_run_to_component_with_ABSOLUTE_in_remaining_fails(self):
        """
        Ensures run_to fails if the remaining instrument refers to absolute
        """
        instr = setup_populated_instr_with_dummy_MCPL_comps()

        with self.assertRaises(McStasError):
            # Fails because the rest of the instrument has reference to ABSOLUTE
            instr.run_to("second_component")

    def test_set_run_to_component_with_early_ref_in_remaining_fails(self):
        """
        Ensures run_to fails if the remaining instrument refers to absolute
        """
        instr = setup_populated_instr_with_dummy_MCPL_comps()

        comp = instr.get_component("third_component")
        comp.set_RELATIVE("first_component")

        with self.assertRaises(McStasError):
            # Fails because the rest of the instrument has reference to component before split
            instr.run_to("second_component")

    def test_set_run_from_component(self):
        """
        Testing run_from method updates instr state correctly
        """
        instr = setup_populated_instr_with_dummy_MCPL_comps()

        insert_mock_dump(instr, "second_component")

        second_component = instr.get_component("second_component")

        # Ensure remaining instrument can work
        third_component = instr.get_component("third_component")
        third_component.set_RELATIVE("second_component")

        instr.run_from(second_component)

        self.assertEqual(instr.run_to_ref, None)
        self.assertEqual(instr.run_from_ref, "second_component")

        # Check filename added to parameters
        self.assertTrue("run_from_mcpl" in instr.parameters.parameters)
        self.assertEqual(instr.parameters.parameters["run_from_mcpl"].type, "string")

    def test_set_run_from_component_fails_if_no_dump(self):
        """
        Ensure run_from fails if there are no dumps at that location
        """
        instr = setup_populated_instr_with_dummy_MCPL_comps()

        with self.assertRaises(KeyError):
            instr.run_from("second_component")

        # Also fails if database is populated at a different component
        insert_mock_dump(instr, "second_component")

        with self.assertRaises(KeyError):
            instr.run_from("first_component")

    def test_set_run_from_component_keywords(self):
        """
        Testing run_to method updates instr state with passed keywords
        """

        instr = setup_populated_instr_with_dummy_MCPL_comps()

        insert_mock_dump(instr, "second_component")

        second_component = instr.get_component("second_component")

        # Ensure remaining instrument can work
        third_component = instr.get_component("third_component")
        third_component.set_RELATIVE("second_component")

        instr.run_from(second_component, test_keyword=37)

        self.assertIn("test_keyword", instr.run_from_component_parameters)
        self.assertEqual(instr.run_from_component_parameters["test_keyword"], 37)

    def test_set_run_from_and_run_to(self):
        """
        Ensure it is possible to use run_from and run_to, and that reset work
        """

        instr = setup_populated_instr_with_dummy_MCPL_comps()
        insert_mock_dump(instr, "second_component")
        third_component = instr.get_component("third_component")
        third_component.set_RELATIVE("second_component")

        instr.run_from("second_component")
        instr.run_to("third_component")

        self.assertEqual(instr.run_from_ref, "second_component")
        self.assertEqual(instr.run_to_ref, "third_component")

        instr.reset_run_points()

        self.assertEqual(instr.run_from_ref, None)
        self.assertEqual(instr.run_to_ref, None)

if __name__ == '__main__':
    unittest.main()